Add handler for when a channel can not be joined.
[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                         Optional<Channel> channel = getChannel(network.get(), kickedFromChannel.channel());
603                         if (!channel.isPresent()) {
604                                 /* maybe it was an extra channel? */
605                                 channel = getExtraChannel(network.get(), kickedFromChannel.channel());
606                                 if (!channel.isPresent()) {
607                                         /* okay, whatever. */
608                                         return;
609                                 }
610
611                                 extraChannels.remove(channel);
612                         } else {
613                                 channels.remove(channel.get());
614                         }
615                         eventBus.post(new GenericMessage(format(
616                                         "Kicked from %s/%s by %s: %s",
617                                         kickedFromChannel.channel(), network.get(),
618                                         kickedFromChannel.kicker(),
619                                         kickedFromChannel.reason().or("<unknown>")
620                         )));
621                 }
622         }
623
624         private boolean nicknameMatchesConnection(Connection connection, String nickname) {
625                 return connection.nickname().equalsIgnoreCase(nickname);
626         }
627
628         /**
629          * Removes a client (which may be a bot) from the table of known bots.
630          *
631          * @param clientQuit
632          *              The client quit event
633          */
634         @Subscribe
635         public void clientQuit(ClientQuit clientQuit) {
636                 Optional<Network> network = getNetwork(clientQuit.connection());
637                 if (!network.isPresent()) {
638                         return;
639                 }
640
641                 networkBots.remove(network.get(), clientQuit.client().nick().get());
642         }
643
644         /**
645          * If the nickname of a bit changes, remove it from the old name and store it
646          * under the new name.
647          *
648          * @param nicknameChanged
649          *              The nickname changed event
650          */
651         @Subscribe
652         public void nicknameChanged(NicknameChanged nicknameChanged) {
653                 Optional<Network> network = getNetwork(nicknameChanged.connection());
654                 if (!network.isPresent()) {
655                         return;
656                 }
657
658                 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
659                 if (bot == null) {
660                         return;
661                 }
662
663                 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
664         }
665
666         /**
667          * If a message on a channel is received, it is parsed for pack information
668          * with is then added to a bot.
669          *
670          * @param channelMessageReceived
671          *              The channel message received event
672          */
673         @Subscribe
674         public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
675                 String message = getDefaultInstance().clean(channelMessageReceived.message());
676                 if (!message.startsWith("#")) {
677                         /* most probably not a pack announcement. */
678                         return;
679                 }
680
681                 Optional<Network> network = getNetwork(channelMessageReceived.connection());
682                 if (!network.isPresent()) {
683                         /* message for unknown connection? */
684                         return;
685                 }
686
687                 /* parse pack information. */
688                 Optional<Pack> pack = parsePack(message);
689                 if (!pack.isPresent()) {
690                         return;
691                 }
692
693                 Bot bot;
694                 synchronized (networkBots) {
695                         if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
696                                 bot = new Bot(network.get(), channelMessageReceived.source().nick().get());
697                                 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
698                                 eventBus.post(new BotAdded(bot));
699                         } else {
700                                 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
701                         }
702                 }
703
704                 /* add pack. */
705                 bot.addPack(pack.get());
706                 logger.debug(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
707         }
708
709         /**
710          * Forward all private messages to every console.
711          *
712          * @param privateMessageReceived
713          *              The private message recevied event
714          */
715         @Subscribe
716         public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
717                 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
718         }
719
720         /**
721          * Sends a message to all console when a notice was received.
722          *
723          * @param privateNoticeReceived
724          *              The notice received event
725          */
726         @Subscribe
727         public void privateNoticeReceived(PrivateNoticeReceived privateNoticeReceived) {
728                 Optional<Network> network = getNetwork(privateNoticeReceived.connection());
729                 if (!network.isPresent()) {
730                         return;
731                 }
732
733                 eventBus.post(new GenericMessage(String.format("Notice from %s (%s): %s", privateNoticeReceived.reply().source().get(), network.get(), privateNoticeReceived.text())));
734         }
735
736         /**
737          * Starts a DCC download.
738          *
739          * @param dccSendReceived
740          *              The DCC SEND event
741          */
742         @Subscribe
743         public void dccSendReceived(final DccSendReceived dccSendReceived) {
744                 final Optional<Network> network = getNetwork(dccSendReceived.connection());
745                 if (!network.isPresent()) {
746                         return;
747                 }
748
749                 Collection<Download> packDownloads = downloads.get(dccSendReceived.filename());
750                 if (packDownloads.isEmpty()) {
751                         /* unknown download, ignore. */
752                         return;
753                 }
754
755                 /* check if it’s already downloading. */
756                 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
757                 if (!runningDownloads.isEmpty()) {
758                         eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccSendReceived.filename())));
759                         return;
760                 }
761
762                 /* locate the correct download. */
763                 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
764
765                         @Override
766                         public boolean apply(Download download) {
767                                 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccSendReceived.source().nick().get());
768                         }
769                 }).toSet();
770
771                 /* we did not request this download. */
772                 if (requestedDownload.isEmpty()) {
773                         return;
774                 }
775
776                 Download download = requestedDownload.iterator().next();
777
778                 /* check if the file already exists. */
779                 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
780                 if (outputFile.exists()) {
781                         long existingFileSize = outputFile.length();
782
783                         /* file already complete? */
784                         if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
785                                 /* file is apparently already complete. just move it. */
786                                 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
787                                         eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
788                                 } else {
789                                         eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
790                                 }
791
792                                 /* remove download. */
793                                 downloads.removeAll(download.pack().name());
794                                 return;
795                         }
796
797                         /* file not complete yet, DCC resume it. */
798                         try {
799                                 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
800                                 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
801                         } catch (IOException ioe1) {
802                                 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
803                         }
804
805                         return;
806                 }
807
808                 /* file does not exist, start the download. */
809                 try {
810                         OutputStream fileOutputStream = new FileOutputStream(outputFile);
811                         DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
812                         download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
813                         dccReceivers.add(dccReceiver);
814                         dccReceiver.start();
815                         eventBus.post(new DownloadStarted(download));
816                 } catch (FileNotFoundException fnfe1) {
817                         eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
818                 }
819         }
820
821         @Subscribe
822         public void dccAcceptReceived(final DccAcceptReceived dccAcceptReceived) {
823                 final Optional<Network> network = getNetwork(dccAcceptReceived.connection());
824                 if (!network.isPresent()) {
825                         return;
826                 }
827
828                 Collection<Download> packDownloads = downloads.get(dccAcceptReceived.filename());
829                 if (packDownloads.isEmpty()) {
830                         /* unknown download, ignore. */
831                         return;
832                 }
833
834                 /* check if it’s already downloading. */
835                 Collection<Download> runningDownloads = FluentIterable.from(packDownloads).filter(FILTER_RUNNING).toSet();
836                 if (!runningDownloads.isEmpty()) {
837                         eventBus.post(new GenericMessage(String.format("Ignoring offer for %s, it’s already being downloaded.", dccAcceptReceived.filename())));
838                         return;
839                 }
840
841                 /* locate the correct download. */
842                 Collection<Download> requestedDownload = FluentIterable.from(packDownloads).filter(new Predicate<Download>() {
843
844                         @Override
845                         public boolean apply(Download download) {
846                                 return download.bot().network().equals(network.get()) && download.bot().name().equalsIgnoreCase(dccAcceptReceived.source().nick().get());
847                         }
848                 }).toSet();
849
850                 /* we did not request this download. */
851                 if (requestedDownload.isEmpty()) {
852                         return;
853                 }
854
855                 Download download = requestedDownload.iterator().next();
856
857                 try {
858                         File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
859                         if (outputFile.length() != dccAcceptReceived.position()) {
860                                 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
861                                 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()));
862
863                                 downloads.removeAll(download.pack().name());
864                                 return;
865                         }
866                         OutputStream outputStream = new FileOutputStream(outputFile, true);
867                         DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
868                         download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
869                         dccReceivers.add(dccReceiver);
870                         dccReceiver.start();
871                         eventBus.post(new DownloadStarted(download));
872                 } catch (FileNotFoundException fnfe1) {
873                 }
874         }
875
876         /**
877          * Closes the output stream of the download and moves the file to the final
878          * location.
879          *
880          * @param dccDownloadFinished
881          *              The DCC download finished event
882          */
883         @Subscribe
884         public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
885
886                 /* locate the correct download. */
887                 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFinished.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
888                 if (requestedDownload.isEmpty()) {
889                         /* this seems wrong. */
890                         logger.warn("Download finished but could not be located.");
891                         return;
892                 }
893                 Download download = requestedDownload.iterator().next();
894
895                 try {
896                         download.outputStream().close();
897                         File file = new File(download.filename());
898                         file.renameTo(new File(finalDirectory, download.pack().name()));
899                         eventBus.post(new DownloadFinished(download));
900                         dccReceivers.remove(dccDownloadFinished.dccReceiver());
901                         downloads.removeAll(download.pack().name());
902                 } catch (IOException ioe1) {
903                         /* TODO - handle all the errors. */
904                         logger.warn(String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
905                 }
906         }
907
908         /**
909          * Closes the output stream and notifies all listeners of the failure.
910          *
911          * @param dccDownloadFailed
912          *              The DCC download failed event
913          */
914         @Subscribe
915         public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
916
917                 /* locate the correct download. */
918                 Collection<Download> requestedDownload = FluentIterable.from(downloads.get(dccDownloadFailed.dccReceiver().filename())).filter(FILTER_RUNNING).toSet();
919                 if (requestedDownload.isEmpty()) {
920                         /* this seems wrong. */
921                         logger.warn("Download finished but could not be located.");
922                         return;
923                 }
924                 Download download = requestedDownload.iterator().next();
925
926                 try {
927                         Closeables.close(download.outputStream(), true);
928                         eventBus.post(new DownloadFailed(download));
929                         dccReceivers.remove(dccDownloadFailed.dccReceiver());
930                         downloads.removeAll(download.pack().name());
931                 } catch (IOException ioe1) {
932                         /* swallow silently. */
933                 }
934         }
935
936         @Subscribe
937         public void replyReceived(ReplyReceived replyReceived) {
938                 logger.trace(String.format("%s: %s", replyReceived.connection().hostname(), replyReceived.reply()));
939         }
940
941         //
942         // PRIVATE METHODS
943         //
944
945         /**
946          * Returns the download of the given pack from the given bot.
947          *
948          * @param pack
949          *              The pack being downloaded
950          * @param bot
951          *              The bot the pack is being downloaded from
952          * @return The download, or {@link Optional#absent()} if the download could not
953          *         be found
954          */
955         private Optional<Download> getDownload(Pack pack, Bot bot) {
956                 if (!downloads.containsKey(pack.name())) {
957                         return Optional.absent();
958                 }
959                 for (Download download : Lists.newArrayList(downloads.get(pack.name()))) {
960                         if (download.bot().equals(bot)) {
961                                 return Optional.of(download);
962                         }
963                 }
964                 return Optional.absent();
965         }
966
967         /**
968          * Searches all current connections for the given connection, returning the
969          * associated network.
970          *
971          * @param connection
972          *              The connection to get the network for
973          * @return The network belonging to the connection, or {@link
974          *         Optional#absent()}
975          */
976         private Optional<Network> getNetwork(Connection connection) {
977                 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
978                         if (networkConnectionEntry.getValue().equals(connection)) {
979                                 return Optional.of(networkConnectionEntry.getKey());
980                         }
981                 }
982                 return Optional.absent();
983         }
984
985         /**
986          * Returns the configured channel for the given network and name.
987          *
988          * @param network
989          *              The network the channel is located on
990          * @param channelName
991          *              The name of the channel
992          * @return The configured channel, or {@link Optional#absent()} if no
993          *         configured channel matching the given network and name was found
994          */
995         public Optional<Channel> getChannel(Network network, String channelName) {
996                 for (Channel channel : channels) {
997                         if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
998                                 return Optional.of(channel);
999                         }
1000                 }
1001                 return Optional.absent();
1002         }
1003
1004         /**
1005          * Returns the extra channel for the given network and name.
1006          *
1007          * @param network
1008          *              The network the channel is located on
1009          * @param channelName
1010          *              The name of the channel
1011          * @return The extra channel, or {@link Optional#absent()} if no extra channel
1012          *         matching the given network and name was found
1013          */
1014         public Optional<Channel> getExtraChannel(Network network, String channelName) {
1015                 for (Channel channel : extraChannels) {
1016                         if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
1017                                 return Optional.of(channel);
1018                         }
1019                 }
1020                 return Optional.absent();
1021         }
1022
1023         /**
1024          * Parses {@link Pack} information from the given message.
1025          *
1026          * @param message
1027          *              The message to parse pack information from
1028          * @return The parsed pack, or {@link Optional#absent()} if the message could
1029          *         not be parsed into a pack
1030          */
1031         private Optional<Pack> parsePack(String message) {
1032                 int squareOpen = message.indexOf('[');
1033                 int squareClose = message.indexOf(']', squareOpen);
1034                 if ((squareOpen == -1) && (squareClose == -1)) {
1035                         return Optional.absent();
1036                 }
1037                 String packSize = message.substring(squareOpen + 1, squareClose);
1038                 String packName = message.substring(message.lastIndexOf(' ') + 1);
1039                 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
1040                 return Optional.of(new Pack(packIndex, packSize, packName));
1041         }
1042
1043 }