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