Add method to return all connected networks.
[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.xdcc.data.Channel.TO_NETWORK;
21 import static net.pterodactylus.xdcc.data.Download.FILTER_RUNNING;
22
23 import java.io.File;
24 import java.io.FileNotFoundException;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.OutputStream;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Map.Entry;
34 import java.util.concurrent.TimeUnit;
35 import java.util.logging.Level;
36 import java.util.logging.Logger;
37
38 import net.pterodactylus.irc.Connection;
39 import net.pterodactylus.irc.ConnectionBuilder;
40 import net.pterodactylus.irc.DccReceiver;
41 import net.pterodactylus.irc.event.ChannelJoined;
42 import net.pterodactylus.irc.event.ChannelLeft;
43 import net.pterodactylus.irc.event.ChannelMessageReceived;
44 import net.pterodactylus.irc.event.ClientQuit;
45 import net.pterodactylus.irc.event.ConnectionClosed;
46 import net.pterodactylus.irc.event.ConnectionEstablished;
47 import net.pterodactylus.irc.event.ConnectionFailed;
48 import net.pterodactylus.irc.event.DccAcceptReceived;
49 import net.pterodactylus.irc.event.DccDownloadFailed;
50 import net.pterodactylus.irc.event.DccDownloadFinished;
51 import net.pterodactylus.irc.event.DccSendReceived;
52 import net.pterodactylus.irc.event.NicknameChanged;
53 import net.pterodactylus.irc.event.PrivateMessageReceived;
54 import net.pterodactylus.irc.event.PrivateNoticeReceived;
55 import net.pterodactylus.irc.event.ReplyReceived;
56 import net.pterodactylus.irc.util.MessageCleaner;
57 import net.pterodactylus.irc.util.RandomNickname;
58 import net.pterodactylus.xdcc.core.event.BotAdded;
59 import net.pterodactylus.xdcc.core.event.CoreStarted;
60 import net.pterodactylus.xdcc.core.event.DownloadFailed;
61 import net.pterodactylus.xdcc.core.event.DownloadFinished;
62 import net.pterodactylus.xdcc.core.event.DownloadStarted;
63 import net.pterodactylus.xdcc.core.event.GenericError;
64 import net.pterodactylus.xdcc.core.event.GenericMessage;
65 import net.pterodactylus.xdcc.core.event.MessageReceived;
66 import net.pterodactylus.xdcc.data.Bot;
67 import net.pterodactylus.xdcc.data.Channel;
68 import net.pterodactylus.xdcc.data.Download;
69 import net.pterodactylus.xdcc.data.Network;
70 import net.pterodactylus.xdcc.data.Pack;
71 import net.pterodactylus.xdcc.data.Server;
72
73 import com.google.common.base.Function;
74 import com.google.common.base.Optional;
75 import com.google.common.base.Predicate;
76 import com.google.common.collect.FluentIterable;
77 import com.google.common.collect.HashBasedTable;
78 import com.google.common.collect.HashMultimap;
79 import com.google.common.collect.ImmutableList;
80 import com.google.common.collect.ImmutableSet;
81 import com.google.common.collect.Lists;
82 import com.google.common.collect.Maps;
83 import com.google.common.collect.Multimap;
84 import com.google.common.collect.Sets;
85 import com.google.common.collect.Table;
86 import com.google.common.eventbus.EventBus;
87 import com.google.common.eventbus.Subscribe;
88 import com.google.common.io.Closeables;
89 import com.google.common.util.concurrent.AbstractExecutionThreadService;
90 import com.google.inject.Inject;
91
92 /**
93  * The core of XDCC Downloader.
94  *
95  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
96  */
97 public class Core extends AbstractExecutionThreadService {
98
99         /** The logger. */
100         private static final Logger logger = Logger.getLogger(Core.class.getName());
101
102         /** The event bus. */
103         private final EventBus eventBus;
104
105         /** The temporary directory to download files to. */
106         private final String temporaryDirectory;
107
108         /** The directory to move finished downloads to. */
109         private final String finalDirectory;
110
111         /** The channels that should be monitored. */
112         private final Collection<Channel> channels = Sets.newHashSet();
113
114         /** The channels that are currentlymonitored. */
115         private final Collection<Channel> joinedChannels = Sets.newHashSet();
116
117         /** The channels that are joined but not configured. */
118         private final Collection<Channel> extraChannels = Sets.newHashSet();
119
120         /** The current network connections. */
121         private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
122
123         /** The currently known bots. */
124         private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
125
126         /** The current downloads. */
127         private final Multimap<String, Download> downloads = HashMultimap.create();
128
129         /** The current DCC receivers. */
130         private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
131
132         /**
133          * Creates a new core.
134          *
135          * @param eventBus
136          *              The event bus
137          * @param temporaryDirectory
138          *              The directory to download files to
139          * @param finalDirectory
140          *              The directory to move finished files to
141          */
142         @Inject
143         public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
144                 this.eventBus = eventBus;
145                 this.temporaryDirectory = temporaryDirectory;
146                 this.finalDirectory = finalDirectory;
147         }
148
149         //
150         // ACCESSORS
151         //
152
153         /**
154          * Returns all currently known connections.
155          *
156          * @return All currently known connections
157          */
158         public Collection<Connection> connections() {
159                 return networkConnections.values();
160         }
161
162         /**
163          * Returns all defined networks.
164          *
165          * @return All defined networks
166          */
167         public Collection<Network> networks() {
168                 return FluentIterable.from(channels).transform(TO_NETWORK).toSet();
169         }
170
171         /**
172          * Returns all connected networks.
173          *
174          * @return All connected networks
175          */
176         public Collection<Network> connectedNetworks() {
177                 return Lists.newArrayList(Optional.presentInstances(FluentIterable.from(networkConnections.values()).transform(new Function<Connection, Optional<Network>>() {
178                         @Override
179                         public Optional<Network> apply(Connection connection) {
180                                 return getNetwork(connection);
181                         }
182                 })));
183         }
184
185         /**
186          * Returns all configured channels. Due to various circumstances, configured
187          * channels might not actually be joined.
188          *
189          * @return All configured channels
190          */
191         public Collection<Channel> channels() {
192                 return ImmutableSet.copyOf(channels);
193         }
194
195         /**
196          * Returns all currently joined channels.
197          *
198          * @return All currently joined channels
199          */
200         public Collection<Channel> joinedChannels() {
201                 return ImmutableSet.copyOf(joinedChannels);
202         }
203
204         /**
205          * Returns all currently joined channels that are not configured.
206          *
207          * @return All currently joined but not configured channels
208          */
209         public Collection<Channel> extraChannels() {
210                 return ImmutableSet.copyOf(extraChannels);
211         }
212
213         /**
214          * Returns all currently known bots.
215          *
216          * @return All currently known bots
217          */
218         public Collection<Bot> bots() {
219                 return networkBots.values();
220         }
221
222         /**
223          * Returns all currently running downloads.
224          *
225          * @return All currently running downloads
226          */
227         public Collection<Download> downloads() {
228                 return downloads.values();
229         }
230
231         //
232         // ACTIONS
233         //
234
235         /**
236          * Adds a channel to monitor.
237          *
238          * @param channel
239          *              The channel to monitor
240          */
241         public void addChannel(Channel channel) {
242                 channels.add(channel);
243         }
244
245         /**
246          * Fetches the given pack from the given bot.
247          *
248          * @param bot
249          *              The bot to fetch the pack from
250          * @param pack
251          *              The pack to fetch
252          */
253         public void fetch(Bot bot, Pack pack) {
254                 Connection connection = networkConnections.get(bot.network());
255                 if (connection == null) {
256                         return;
257                 }
258
259                 /* check if we are already downloading the file? */
260                 if (downloads.containsKey(pack.name())) {
261                         Collection<Download> packDownloads = downloads.get(pack.name());
262                         Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
263                         if (!runningDownloads.isEmpty()) {
264                                 Download download = runningDownloads.iterator().next();
265                                 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
266                                 return;
267                         }
268                         StringBuilder bots = new StringBuilder();
269                         for (Download download : packDownloads) {
270                                 if (bots.length() > 0) {
271                                         bots.append(", ");
272                                 }
273                                 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
274                         }
275                         eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
276                 }
277
278                 Download download = new Download(bot, pack);
279                 downloads.put(pack.name(), download);
280
281                 try {
282                         connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
283                 } catch (IOException ioe1) {
284                         logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
285                 }
286         }
287
288         /**
289          * Cancels the download of the given pack from the given bot.
290          *
291          * @param bot
292          *              The bot the pack is being downloaded from
293          * @param pack
294          *              The pack being downloaded
295          */
296         public void cancelDownload(Bot bot, Pack pack) {
297                 Optional<Download> download = getDownload(pack, bot);
298                 if (!download.isPresent()) {
299                         return;
300                 }
301
302                 /* get connection. */
303                 Connection connection = networkConnections.get(bot.network());
304                 if (connection == null) {
305                         /* request for unknown network? */
306                         return;
307                 }
308
309                 /* stop the DCC receiver. */
310                 if (download.get().dccReceiver() != null) {
311                         download.get().dccReceiver().stop();
312                 } else {
313                         /* remove download if it hasn’t started yet. */
314                         downloads.remove(pack.name(), download.get());
315                 }
316
317                 /* remove the request from the bot, too. */
318                 try {
319                         connection.sendMessage(bot.name(), String.format("XDCC %s", (download.get().dccReceiver() != null) ? "CANCEL" : "REMOVE"));
320                 } catch (IOException ioe1) {
321                         logger.log(Level.WARNING, String.format("Could not cancel DCC from %s (%s)!", bot.name(), bot.network().name()), ioe1);
322                 }
323         }
324
325         /**
326          * Closes the given connection.
327          *
328          * @param connection
329          *              The connection to close
330          */
331         public void closeConnection(Connection connection) {
332                 try {
333                         connection.close();
334                 } catch (IOException ioe1) {
335                         /* TODO */
336                 }
337         }
338
339         //
340         // ABSTRACTIDLESERVICE METHODS
341         //
342
343         @Override
344         protected void startUp() {
345                 for (Channel channel : channels) {
346                         logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
347                         connectNetwork(channel.network());
348                 }
349
350                 /* notify listeners. */
351                 eventBus.post(new CoreStarted(this));
352         }
353
354         @Override
355         protected void run() throws Exception {
356                 while (isRunning()) {
357                         try {
358                                 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
359                         } catch (InterruptedException ie1) {
360                                 /* ignore. */
361                         }
362
363                         /* find channels that should be monitored but are not. */
364                         for (Channel channel : channels) {
365                                 if (joinedChannels.contains(channel)) {
366                                         continue;
367                                 }
368
369                                 connectNetwork(channel.network());
370                                 Connection connection = networkConnections.get(channel.network());
371                                 if (connection.established()) {
372                                         eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
373                                         try {
374                                                 connection.joinChannel(channel.name());
375                                         } catch (IOException ioe1) {
376                                                 eventBus.post(new GenericMessage(String.format("Could not join %s on %s.", channel.name(), channel.network().name())));
377                                         }
378                                 }
379                         }
380                 }
381         }
382
383         @Override
384         protected void shutDown() {
385         }
386
387         //
388         // PRIVATE METHODS
389         //
390
391         /**
392          * Starts a new connection for the given network if no such connection exists
393          * already.
394          *
395          * @param network
396          *              The network to connect to
397          */
398         private void connectNetwork(Network network) {
399                 if (!networkConnections.containsKey(network)) {
400                                 /* select a random server. */
401                         List<Server> servers = Lists.newArrayList(network.servers());
402                         if (servers.isEmpty()) {
403                                 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
404                                 return;
405                         }
406                         Server server = servers.get((int) (Math.random() * servers.size()));
407                         Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
408                         connection.username(RandomNickname.get()).realName(RandomNickname.get());
409                         networkConnections.put(network, connection);
410                         connection.start();
411                 }
412         }
413
414         /**
415          * Removes the given connection and all its channels and bots.
416          *
417          * @param connection
418          *              The connection to remove
419          */
420         private void removeConnection(Connection connection) {
421                 Optional<Network> network = getNetwork(connection);
422                 if (!network.isPresent()) {
423                         return;
424                 }
425
426                 /* find all channels that need to be removed. */
427                 for (Collection<Channel> channels : ImmutableList.of(joinedChannels, extraChannels)) {
428                         for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
429                                 Channel joinedChannel = channelIterator.next();
430                                 if (!joinedChannel.network().equals(network.get())) {
431                                         continue;
432                                 }
433
434                                 channelIterator.remove();
435                         }
436                 }
437
438                 /* now remove all bots for that network. */
439                 Map<String, Bot> bots = networkBots.row(network.get());
440                 int botCount = bots.size();
441                 int packCount = 0;
442                 for (Bot bot : bots.values()) {
443                         packCount += bot.packs().size();
444                 }
445                 bots.clear();
446                 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
447
448                 /* now remove the network. */
449                 networkConnections.remove(network.get());
450         }
451
452         //
453         // EVENT HANDLERS
454         //
455
456         /**
457          * If a connection to a network has been established, the channels associated
458          * with this network are joined.
459          *
460          * @param connectionEstablished
461          *              The connection established event
462          */
463         @Subscribe
464         public void connectionEstablished(ConnectionEstablished connectionEstablished) {
465
466                 /* get network for connection. */
467                 Optional<Network> network = getNetwork(connectionEstablished.connection());
468
469                 /* found network? */
470                 if (!network.isPresent()) {
471                         eventBus.post(new GenericMessage(String.format("Connected to unknown network: %s", connectionEstablished.connection().hostname())));
472                         return;
473                 }
474
475                 eventBus.post(new GenericMessage(String.format("Connected to network %s.", network.get().name())));
476
477                 /* join all channels on this network. */
478                 for (Channel channel : channels) {
479                         if (channel.network().equals(network.get())) {
480                                 try {
481                                         eventBus.post(new GenericMessage(String.format("Trying to join %s on %s...", channel.name(), network.get().name())));
482                                         connectionEstablished.connection().joinChannel(channel.name());
483                                 } catch (IOException ioe1) {
484                                         logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
485                                 }
486                         }
487                 }
488         }
489
490         /**
491          * Remove all data stored for a network if the connection is closed.
492          *
493          * @param connectionClosed
494          *              The connection closed event
495          */
496         @Subscribe
497         public void connectionClosed(ConnectionClosed connectionClosed) {
498                 removeConnection(connectionClosed.connection());
499         }
500
501         /**
502          * Remove all data stored for a network if the connection fails.
503          *
504          * @param connectionFailed
505          *              The connection failed event
506          */
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 = MessageCleaner.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.fine(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.log(Level.WARNING, 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.warning("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.log(Level.WARNING, 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.warning("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.log(Level.FINEST, 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 }