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