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