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