Fix constructor.
[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                 /* check if we are already downloading the file? */
224                 if (downloads.containsKey(pack.name())) {
225                         Collection<Download> packDownloads = downloads.get(pack.name());
226                         Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
227                         if (!runningDownloads.isEmpty()) {
228                                 Download download = runningDownloads.iterator().next();
229                                 eventBus.post(new GenericMessage(String.format("File %s is already downloading from %s (%s).", pack.name(), download.bot().name(), download.bot().network().name())));
230                                 return;
231                         }
232                         StringBuilder bots = new StringBuilder();
233                         for (Download download : packDownloads) {
234                                 if (bots.length() > 0) {
235                                         bots.append(", ");
236                                 }
237                                 bots.append(download.bot().name()).append(" (").append(download.bot().network().name()).append(')');
238                         }
239                         eventBus.post(new GenericMessage(String.format("File %s is already requested from %d bots (%s).", pack.name(), packDownloads.size(), bots.toString())));
240                 }
241
242                 Download download = new Download(bot, pack);
243                 downloads.put(pack.name(), download);
244
245                 try {
246                         connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
247                 } catch (IOException ioe1) {
248                         logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
249                 }
250         }
251
252         //
253         // ABSTRACTIDLESERVICE METHODS
254         //
255
256         @Override
257         protected void startUp() {
258                 for (Channel channel : channels) {
259                         logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
260                         connectNetwork(channel.network());
261                 }
262
263                 /* notify listeners. */
264                 eventBus.post(new CoreStarted(this));
265         }
266
267         @Override
268         protected void run() throws Exception {
269                 while (isRunning()) {
270                         try {
271                                 Thread.sleep(TimeUnit.MINUTES.toMillis(1));
272                         } catch (InterruptedException ie1) {
273                                 /* ignore. */
274                         }
275
276                         /* find channels that should be monitored but are not. */
277                         for (Channel channel : channels) {
278                                 if (joinedChannels.contains(channel)) {
279                                         continue;
280                                 }
281
282                                 connectNetwork(channel.network());
283                                 Connection connection = networkConnections.get(channel.network());
284                                 if (connection.established()) {
285                                         eventBus.post(new GenericMessage(String.format("Trying to join %s on %s.", channel.name(), channel.network().name())));
286                                         connection.joinChannel(channel.name());
287                                 }
288                         }
289                 }
290         }
291
292         @Override
293         protected void shutDown() {
294         }
295
296         //
297         // PRIVATE METHODS
298         //
299
300         /**
301          * Starts a new connection for the given network if no such connection exists
302          * already.
303          *
304          * @param network
305          *              The network to connect to
306          */
307         private void connectNetwork(Network network) {
308                 if (!networkConnections.containsKey(network)) {
309                                 /* select a random server. */
310                         List<Server> servers = Lists.newArrayList(network.servers());
311                         if (servers.isEmpty()) {
312                                 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
313                                 return;
314                         }
315                         Server server = servers.get((int) (Math.random() * servers.size()));
316                         Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
317                         connection.username(RandomNickname.get()).realName(RandomNickname.get());
318                         networkConnections.put(network, connection);
319                         connection.start();
320                 }
321         }
322
323         //
324         // EVENT HANDLERS
325         //
326
327         /**
328          * If a connection to a network has been established, the channels associated
329          * with this network are joined.
330          *
331          * @param connectionEstablished
332          *              The connection established event
333          */
334         @Subscribe
335         public void connectionEstablished(ConnectionEstablished connectionEstablished) {
336
337                 /* get network for connection. */
338                 Optional<Network> network = getNetwork(connectionEstablished.connection());
339
340                 /* found network? */
341                 if (!network.isPresent()) {
342                         return;
343                 }
344
345                 /* join all channels on this network. */
346                 for (Channel channel : channels) {
347                         if (channel.network().equals(network.get())) {
348                                 try {
349                                         connectionEstablished.connection().joinChannel(channel.name());
350                                 } catch (IOException ioe1) {
351                                         logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
352                                 }
353                         }
354                 }
355         }
356
357         /**
358          * Remove all data stored for a network if the connection is closed.
359          *
360          * @param connectionClosed
361          *              The connection closed event
362          */
363         @Subscribe
364         public void connectionClosed(ConnectionClosed connectionClosed) {
365                 Optional<Network> network = getNetwork(connectionClosed.connection());
366                 if (!network.isPresent()) {
367                         return;
368                 }
369
370                 /* find all channels that need to be removed. */
371                 for (Collection channels : ImmutableList.of(joinedChannels, extraChannels)) {
372                         for (Iterator<Channel> channelIterator = channels.iterator(); channelIterator.hasNext(); ) {
373                                 Channel joinedChannel = channelIterator.next();
374                                 if (!joinedChannel.network().equals(network.get())) {
375                                         continue;
376                                 }
377
378                                 channelIterator.remove();
379                         }
380                 }
381
382                 /* now remove all bots for that network. */
383                 Map<String, Bot> bots = networkBots.row(network.get());
384                 int botCount = bots.size();
385                 int packCount = 0;
386                 for (Bot bot : bots.values()) {
387                         packCount += bot.packs().size();
388                 }
389                 bots.clear();
390                 eventBus.post(new GenericMessage(String.format("Network %s disconnected, %d bots removed, %d packs removed.", network.get().name(), botCount, packCount)));
391
392                 /* now remove the network. */
393                 networkConnections.remove(network.get());
394         }
395
396         /**
397          * Shows a message when a channel was joined by us.
398          *
399          * @param channelJoined
400          *              The channel joined event
401          */
402         @Subscribe
403         public void channelJoined(ChannelJoined channelJoined) {
404                 if (channelJoined.connection().isSource(channelJoined.client())) {
405                         Optional<Network> network = getNetwork(channelJoined.connection());
406                         if (!network.isPresent()) {
407                                 return;
408                         }
409
410                         Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
411                         if (!channel.isPresent()) {
412                                 /* it’s an extra channel. */
413                                 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
414                                 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
415                                 return;
416                         }
417
418                         joinedChannels.add(channel.get());
419                         logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
420                 }
421         }
422
423         /**
424          * Removes bots that leave a channel, or channels when it’s us that’s leaving.
425          *
426          * @param channelLeft
427          *              The channel left event
428          */
429         @Subscribe
430         public void channelLeft(ChannelLeft channelLeft) {
431                 Optional<Network> network = getNetwork(channelLeft.connection());
432                 if (!network.isPresent()) {
433                         return;
434                 }
435
436                 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
437                 if (bot == null) {
438                         /* maybe it was us? */
439                         if (channelLeft.connection().isSource(channelLeft.client())) {
440                                 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
441                                 if (!channel.isPresent()) {
442                                         /* maybe it was an extra channel? */
443                                         channel = getExtraChannel(network.get(), channelLeft.channel());
444                                         if (!channel.isPresent()) {
445                                                 /* okay, whatever. */
446                                                 return;
447                                         }
448
449                                         extraChannels.remove(channel);
450                                 } else {
451                                         channels.remove(channel.get());
452                                 }
453
454                                 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
455                         }
456
457                         return;
458                 }
459
460                 Bot removedBot = networkBots.remove(network.get(), channelLeft.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          * Removes a client (which may be a bot) from the table of known bots.
468          *
469          * @param clientQuit
470          *              The client quit event
471          */
472         @Subscribe
473         public void clientQuit(ClientQuit clientQuit) {
474                 Optional<Network> network = getNetwork(clientQuit.connection());
475                 if (!network.isPresent()) {
476                         return;
477                 }
478
479                 Bot removedBot = networkBots.remove(network.get(), clientQuit.client().nick().get());
480                 if (removedBot != null) {
481                         eventBus.post(new GenericMessage(String.format("Bot %s (%s) was removed, %d packs removed.", removedBot.name(), removedBot.network().name(), removedBot.packs().size())));
482                 }
483         }
484
485         /**
486          * If the nickname of a bit changes, remove it from the old name and store it
487          * under the new name.
488          *
489          * @param nicknameChanged
490          *              The nickname changed event
491          */
492         @Subscribe
493         public void nicknameChanged(NicknameChanged nicknameChanged) {
494                 Optional<Network> network = getNetwork(nicknameChanged.connection());
495                 if (!network.isPresent()) {
496                         return;
497                 }
498
499                 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
500                 if (bot == null) {
501                         return;
502                 }
503
504                 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
505         }
506
507         /**
508          * If a message on a channel is received, it is parsed for pack information
509          * with is then added to a bot.
510          *
511          * @param channelMessageReceived
512          *              The channel message received event
513          */
514         @Subscribe
515         public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
516                 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
517                 if (!message.startsWith("#")) {
518                         /* most probably not a pack announcement. */
519                         return;
520                 }
521
522                 Optional<Network> network = getNetwork(channelMessageReceived.connection());
523                 if (!network.isPresent()) {
524                         /* message for unknown connection? */
525                         return;
526                 }
527
528                 /* parse pack information. */
529                 Optional<Pack> pack = parsePack(message);
530                 if (!pack.isPresent()) {
531                         return;
532                 }
533
534                 Bot bot;
535                 synchronized (networkBots) {
536                         if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
537                                 bot = new Bot(network.get(), channelMessageReceived.source().nick().get());
538                                 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
539                                 eventBus.post(new BotAdded(bot));
540                         } else {
541                                 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
542                         }
543                 }
544
545                 /* add pack. */
546                 bot.addPack(pack.get());
547                 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
548         }
549
550         /**
551          * Forward all private messages to every console.
552          *
553          * @param privateMessageReceived
554          *              The private message recevied event
555          */
556         @Subscribe
557         public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
558                 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
559         }
560
561         /**
562          * Sends a message to all console when a notice was received.
563          *
564          * @param privateNoticeReceived
565          *              The notice received event
566          */
567         @Subscribe
568         public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
569                 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
570                 if (!network.isPresent()) {
571                         return;
572                 }
573
574                 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.reply().source(), network.get(), privateNoticeReceived.text())));
575         }
576
577         /**
578          * Starts a DCC download.
579          *
580          * @param dccSendReceived
581          *              The DCC SEND event
582          */
583         @Subscribe
584         public void dccSendReceived(final DccSendReceived dccSendReceived) {
585                 final Optional<Network> network = getNetwork(dccSendReceived.connection());
586                 if (!network.isPresent()) {
587                         return;
588                 }
589
590                 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
591                 if (packDownloads.isEmpty()) {
592                         /* unknown download, ignore. */
593                         return;
594                 }
595
596                 /* check if it’s already downloading. */
597                 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
598                 if (!runningDownloads.isEmpty()) {
599                         eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
600                         return;
601                 }
602
603                 /* locate the correct download. */
604                 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
605
606                         @Override
607                         public boolean apply(Download download) {
608                                 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
609                         }
610                 }).toSet();
611
612                 /* we did not request this download. */
613                 if (requestedDownload.isEmpty()) {
614                         return;
615                 }
616
617                 Download download = requestedDownload.iterator().next();
618
619                 /* check if the file already exists. */
620                 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
621                 if (outputFile.exists()) {
622                         long existingFileSize = outputFile.length();
623
624                         /* file already complete? */
625                         if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
626                                 /* file is apparently already complete. just move it. */
627                                 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
628                                         eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
629                                 } else {
630                                         eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
631                                 }
632
633                                 /* remove download. */
634                                 downloads.removeAll(download.pack().name());
635                                 return;
636                         }
637
638                         /* file not complete yet, DCC resume it. */
639                         try {
640                                 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
641                                 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
642                         } catch (IOException ioe1) {
643                                 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
644                         }
645
646                         return;
647                 }
648
649                 /* file does not exist, start the download. */
650                 try {
651                         OutputStream fileOutputStream = new FileOutputStream(outputFile);
652                         DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
653                         download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
654                         dccReceivers.add(dccReceiver);
655                         dccReceiver.start();
656                         eventBus.post(new DownloadStarted(download));
657                 } catch (FileNotFoundException fnfe1) {
658                         eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
659                 }
660         }
661
662         @Subscribe
663         public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
664                 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
665                 if (!network.isPresent()) {
666                         return;
667                 }
668
669                 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
670                 if (packDownloads.isEmpty()) {
671                         /* unknown download, ignore. */
672                         return;
673                 }
674
675                 /* check if it’s already downloading. */
676                 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
677                 if (!runningDownloads.isEmpty()) {
678                         eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
679                         return;
680                 }
681
682                 /* locate the correct download. */
683                 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
684
685                         @Override
686                         public boolean apply(Download download) {
687                                 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
688                         }
689                 }).toSet();
690
691                 /* we did not request this download. */
692                 if (requestedDownload.isEmpty()) {
693                         return;
694                 }
695
696                 Download download = requestedDownload.iterator().next();
697
698                 try {
699                         File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
700                         if (outputFile.length() != dccAcceptReceived.position()) {
701                                 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
702                                 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()));
703
704                                 downloads.removeAll(download.pack().name());
705                                 return;
706                         }
707                         OutputStream outputStream = new FileOutputStream(outputFile, true);
708                         DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
709                         download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
710                         dccReceivers.add(dccReceiver);
711                         dccReceiver.start();
712                         eventBus.post(new DownloadStarted(download));
713                 } catch (FileNotFoundException fnfe1) {
714                 }
715         }
716
717         /**
718          * Closes the output stream of the download and moves the file to the final
719          * location.
720          *
721          * @param dccDownloadFinished
722          *              The DCC download finished event
723          */
724         @Subscribe
725         public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
726
727                 /* locate the correct download. */
728                 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
729                 if (requestedDownload.isEmpty()) {
730                         /* this seems wrong. */
731                         logger.warning("Download finished but could not be located.");
732                         return;
733                 }
734                 Download download = requestedDownload.iterator().next();
735
736                 try {
737                         download.outputStream().close();
738                         File file = new File(download.filename());
739                         file.renameTo(new File(finalDirectory, download.pack().name()));
740                         eventBus.post(new DownloadFinished(download));
741                         dccReceivers.remove(dccDownloadFinished.dccReceiver());
742                         downloads.removeAll(download.pack().name());
743                 } catch (IOException ioe1) {
744                         /* TODO - handle all the errors. */
745                         logger.log(Level.WARNING, String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
746                 }
747         }
748
749         /**
750          * Closes the output stream and notifies all listeners of the failure.
751          *
752          * @param dccDownloadFailed
753          *              The DCC download failed event
754          */
755         @Subscribe
756         public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
757
758                 /* locate the correct download. */
759                 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
760                 if (requestedDownload.isEmpty()) {
761                         /* this seems wrong. */
762                         logger.warning("Download finished but could not be located.");
763                         return;
764                 }
765                 Download download = requestedDownload.iterator().next();
766
767                 try {
768                         Closeables.close(download.outputStream(), true);
769                         eventBus.post(new DownloadFailed(download));
770                         dccReceivers.remove(dccDownloadFailed.dccReceiver());
771                         downloads.removeAll(download.pack().name());
772                 } catch (IOException ioe1) {
773                         /* swallow silently. */
774                 }
775         }
776
777         //
778         // PRIVATE METHODS
779         //
780
781         /**
782          * Searches all current connections for the given connection, returning the
783          * associated network.
784          *
785          * @param connection
786          *              The connection to get the network for
787          * @return The network belonging to the connection, or {@link
788          *         Optional#absent()}
789          */
790         private Optional<Network> getNetwork(Connection connection) {
791                 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
792                         if (networkConnectionEntry.getValue().equals(connection)) {
793                                 return Optional.of(networkConnectionEntry.getKey());
794                         }
795                 }
796                 return Optional.absent();
797         }
798
799         /**
800          * Returns the configured 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 configured channel, or {@link Optional#absent()} if no
807          *         configured channel matching the given network and name was found
808          */
809         public Optional<Channel> getChannel(Network network, String channelName) {
810                 for (Channel channel : channels) {
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          * Returns the extra channel for the given network and name.
820          *
821          * @param network
822          *              The network the channel is located on
823          * @param channelName
824          *              The name of the channel
825          * @return The extra channel, or {@link Optional#absent()} if no extra channel
826          *         matching the given network and name was found
827          */
828         public Optional<Channel> getExtraChannel(Network network, String channelName) {
829                 for (Channel channel : extraChannels) {
830                         if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
831                                 return Optional.of(channel);
832                         }
833                 }
834                 return Optional.absent();
835         }
836
837         /**
838          * Parses {@link Pack} information from the given message.
839          *
840          * @param message
841          *              The message to parse pack information from
842          * @return The parsed pack, or {@link Optional#absent()} if the message could
843          *         not be parsed into a pack
844          */
845         private Optional<Pack> parsePack(String message) {
846                 int squareOpen = message.indexOf('[');
847                 int squareClose = message.indexOf(']', squareOpen);
848                 if ((squareOpen == -1) && (squareClose == -1)) {
849                         return Optional.absent();
850                 }
851                 String packSize = message.substring(squareOpen + 1, squareClose);
852                 String packName = message.substring(message.lastIndexOf(' ') + 1);
853                 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
854                 return Optional.of(new Pack(packIndex, packSize, packName));
855         }
856
857 }