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