Fix message.
[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).getAsInt();
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.source().nick().get());
743                                 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
744                                 eventBus.post(new BotAdded(bot));
745                         } else {
746                                 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
747                         }
748                 }
749
750                 /* add pack. */
751                 bot.addPack(pack.get());
752                 logger.debug(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
753         }
754
755         /**
756          * Forward all private messages to every console.
757          *
758          * @param privateMessageReceived
759          *              The private message recevied event
760          */
761         @Subscribe
762         public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
763                 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
764         }
765
766         /**
767          * Sends a message to all console when a notice was received.
768          *
769          * @param privateNoticeReceived
770          *              The notice received event
771          */
772         @Subscribe
773         public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
774                 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
775                 if (!network.isPresent()) {
776                         return;
777                 }
778
779                 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.source(), network.get(), privateNoticeReceived.text())));
780         }
781
782         /**
783          * Starts a DCC download.
784          *
785          * @param dccSendReceived
786          *              The DCC SEND event
787          */
788         @Subscribe
789         public void dccSendReceived(final DccSendReceived dccSendReceived) {
790                 final Optional<Network> network = getNetwork(dccSendReceived.connection());
791                 if (!network.isPresent()) {
792                         return;
793                 }
794
795                 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
796                 if (packDownloads.isEmpty()) {
797                         /* unknown download, ignore. */
798                         return;
799                 }
800
801                 /* check if it’s already downloading. */
802                 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
803                 if (!runningDownloads.isEmpty()) {
804                         eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
805                         return;
806                 }
807
808                 /* locate the correct download. */
809                 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
810
811                         @Override
812                         public boolean apply(Download download) {
813                                 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
814                         }
815                 }).toSet();
816
817                 /* we did not request this download. */
818                 if (requestedDownload.isEmpty()) {
819                         return;
820                 }
821
822                 Download download = requestedDownload.iterator().next();
823
824                 /* check if the file already exists. */
825                 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
826                 if (outputFile.exists()) {
827                         long existingFileSize = outputFile.length();
828
829                         /* file already complete? */
830                         if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
831                                 /* file is apparently already complete. just move it. */
832                                 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
833                                         eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
834                                 } else {
835                                         eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
836                                 }
837
838                                 /* remove download. */
839                                 downloads.removeAll(download.pack().name());
840                                 return;
841                         }
842
843                         /* file not complete yet, DCC resume it. */
844                         try {
845                                 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
846                                 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
847                         } catch (IOException ioe1) {
848                                 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
849                         }
850
851                         return;
852                 }
853
854                 /* file does not exist, start the download. */
855                 try {
856                         OutputStream fileOutputStream = new FileOutputStream(outputFile);
857                         DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
858                         download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
859                         dccReceivers.add(dccReceiver);
860                         dccReceiver.start();
861                         eventBus.post(new DownloadStarted(download));
862                 } catch (FileNotFoundException fnfe1) {
863                         eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
864                 }
865         }
866
867         @Subscribe
868         public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
869                 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
870                 if (!network.isPresent()) {
871                         return;
872                 }
873
874                 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
875                 if (packDownloads.isEmpty()) {
876                         /* unknown download, ignore. */
877                         return;
878                 }
879
880                 /* check if it’s already downloading. */
881                 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
882                 if (!runningDownloads.isEmpty()) {
883                         eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
884                         return;
885                 }
886
887                 /* locate the correct download. */
888                 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
889
890                         @Override
891                         public boolean apply(Download download) {
892                                 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
893                         }
894                 }).toSet();
895
896                 /* we did not request this download. */
897                 if (requestedDownload.isEmpty()) {
898                         return;
899                 }
900
901                 Download download = requestedDownload.iterator().next();
902
903                 try {
904                         File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
905                         if (outputFile.length() != dccAcceptReceived.position()) {
906                                 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
907                                 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()));
908
909                                 downloads.removeAll(download.pack().name());
910                                 return;
911                         }
912                         OutputStream outputStream = new FileOutputStream(outputFile, true);
913                         DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
914                         download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
915                         dccReceivers.add(dccReceiver);
916                         dccReceiver.start();
917                         eventBus.post(new DownloadStarted(download));
918                 } catch (FileNotFoundException fnfe1) {
919                 }
920         }
921
922         /**
923          * Closes the output stream of the download and moves the file to the final
924          * location.
925          *
926          * @param dccDownloadFinished
927          *              The DCC download finished event
928          */
929         @Subscribe
930         public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
931
932                 /* locate the correct download. */
933                 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
934                 if (requestedDownload.isEmpty()) {
935                         /* this seems wrong. */
936                         logger.warn("Download finished but could not be located.");
937                         return;
938                 }
939                 Download download = requestedDownload.iterator().next();
940
941                 try {
942                         download.outputStream().close();
943                         File file = new File(download.filename());
944                         file.renameTo(new File(finalDirectory, download.pack().name()));
945                         eventBus.post(new DownloadFinished(download));
946                         dccReceivers.remove(dccDownloadFinished.dccReceiver());
947                         downloads.removeAll(download.pack().name());
948                 } catch (IOException ioe1) {
949                         /* TODO - handle all the errors. */
950                         logger.warn(String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
951                 }
952         }
953
954         /**
955          * Closes the output stream and notifies all listeners of the failure.
956          *
957          * @param dccDownloadFailed
958          *              The DCC download failed event
959          */
960         @Subscribe
961         public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
962
963                 /* locate the correct download. */
964                 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
965                 if (requestedDownload.isEmpty()) {
966                         /* this seems wrong. */
967                         logger.warn("Download finished but could not be located.");
968                         return;
969                 }
970                 Download download = requestedDownload.iterator().next();
971
972                 try {
973                         Closeables.close(download.outputStream(), true);
974                         eventBus.post(new DownloadFailed(download));
975                         dccReceivers.remove(dccDownloadFailed.dccReceiver());
976                         downloads.removeAll(download.pack().name());
977                 } catch (IOException ioe1) {
978                         /* swallow silently. */
979                 }
980         }
981
982         @Subscribe
983         public void replyReceived(ReplyReceived replyReceived) {
984                 logger.trace(String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
985         }
986
987         //
988         // PRIVATE METHODS
989         //
990
991         /**
992          * Returns the download of the given pack from the given bot.
993          *
994          * @param pack
995          *              The pack being downloaded
996          * @param bot
997          *              The bot the pack is being downloaded from
998          * @return The download, or {@link Optional#absent()} if the download could not
999          *         be found
1000          */
1001         private Optional<Download> getDownload(Pack pack, Bot bot) {
1002                 if (!downloads.containsKey(pack.name())) {
1003                         return Optional.absent();
1004                 }
1005                 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
1006                         if (download.bot().equals(bot)) {
1007                                 return Optional.of(download);
1008                         }
1009                 }
1010                 return Optional.absent();
1011         }
1012
1013         /**
1014          * Searches all current connections for the given connection, returning the
1015          * associated network.
1016          *
1017          * @param connection
1018          *              The connection to get the network for
1019          * @return The network belonging to the connection, or {@link
1020          *         Optional#absent()}
1021          */
1022         private Optional<Network> getNetwork(Connection connection) {
1023                 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
1024                         if (networkConnectionEntry.getValue().equals(connection)) {
1025                                 return Optional.of(networkConnectionEntry.getKey());
1026                         }
1027                 }
1028                 return Optional.absent();
1029         }
1030
1031         /**
1032          * Returns the configured channel for the given network and name.
1033          *
1034          * @param network
1035          *              The network the channel is located on
1036          * @param channelName
1037          *              The name of the channel
1038          * @return The configured channel, or {@link Optional#absent()} if no
1039          *         configured channel matching the given network and name was found
1040          */
1041         public Optional<Channel> getChannel(Network network, String channelName) {
1042                 for (Channel channel : channels) {
1043                         if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1044                                 return Optional.of(channel);
1045                         }
1046                 }
1047                 return Optional.absent();
1048         }
1049
1050         /**
1051          * Returns the extra channel for the given network and name.
1052          *
1053          * @param network
1054          *              The network the channel is located on
1055          * @param channelName
1056          *              The name of the channel
1057          * @return The extra channel, or {@link Optional#absent()} if no extra channel
1058          *         matching the given network and name was found
1059          */
1060         public Optional<Channel> getExtraChannel(Network network, String channelName) {
1061                 for (Channel channel : extraChannels) {
1062                         if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1063                                 return Optional.of(channel);
1064                         }
1065                 }
1066                 return Optional.absent();
1067         }
1068
1069         /**
1070          * Parses {@link Pack} information from the given message.
1071          *
1072          * @param message
1073          *              The message to parse pack information from
1074          * @return The parsed pack, or {@link Optional#absent()} if the message could
1075          *         not be parsed into a pack
1076          */
1077         private Optional<Pack> parsePack(String message) {
1078                 int squareOpen = message.indexOf('[');
1079                 int squareClose = message.indexOf(']', squareOpen);
1080                 if ((squareOpen == -1) && (squareClose == -1)) {
1081                         return Optional.absent();
1082                 }
1083                 String packSize = message.substring(squareOpen + 1, squareClose);
1084                 String packName = message.substring(message.lastIndexOf(' ') + 1);
1085                 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
1086                 return Optional.of(new Pack(packIndex, packSize, packName));
1087         }
1088
1089 }