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