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