Rename a bot if its nickname changes.
[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 java.io.File;
21 import java.io.FileNotFoundException;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.OutputStream;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Map.Entry;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
32
33 import net.pterodactylus.irc.Connection;
34 import net.pterodactylus.irc.ConnectionBuilder;
35 import net.pterodactylus.irc.DccReceiver;
36 import net.pterodactylus.irc.event.ChannelJoined;
37 import net.pterodactylus.irc.event.ChannelLeft;
38 import net.pterodactylus.irc.event.ChannelMessageReceived;
39 import net.pterodactylus.irc.event.ClientQuit;
40 import net.pterodactylus.irc.event.ConnectionEstablished;
41 import net.pterodactylus.irc.event.DccAcceptReceived;
42 import net.pterodactylus.irc.event.DccDownloadFailed;
43 import net.pterodactylus.irc.event.DccDownloadFinished;
44 import net.pterodactylus.irc.event.DccSendReceived;
45 import net.pterodactylus.irc.event.NicknameChanged;
46 import net.pterodactylus.irc.event.PrivateMessageReceived;
47 import net.pterodactylus.irc.util.MessageCleaner;
48 import net.pterodactylus.irc.util.RandomNickname;
49 import net.pterodactylus.xdcc.core.event.BotAdded;
50 import net.pterodactylus.xdcc.core.event.CoreStarted;
51 import net.pterodactylus.xdcc.core.event.DownloadFailed;
52 import net.pterodactylus.xdcc.core.event.DownloadFinished;
53 import net.pterodactylus.xdcc.core.event.DownloadStarted;
54 import net.pterodactylus.xdcc.core.event.GenericError;
55 import net.pterodactylus.xdcc.core.event.GenericMessage;
56 import net.pterodactylus.xdcc.core.event.MessageReceived;
57 import net.pterodactylus.xdcc.data.Bot;
58 import net.pterodactylus.xdcc.data.Channel;
59 import net.pterodactylus.xdcc.data.Download;
60 import net.pterodactylus.xdcc.data.Network;
61 import net.pterodactylus.xdcc.data.Pack;
62 import net.pterodactylus.xdcc.data.Server;
63
64 import com.google.common.base.Optional;
65 import com.google.common.collect.HashBasedTable;
66 import com.google.common.collect.ImmutableSet;
67 import com.google.common.collect.Lists;
68 import com.google.common.collect.Maps;
69 import com.google.common.collect.Sets;
70 import com.google.common.collect.Table;
71 import com.google.common.eventbus.EventBus;
72 import com.google.common.eventbus.Subscribe;
73 import com.google.common.io.Closeables;
74 import com.google.common.util.concurrent.AbstractIdleService;
75 import com.google.inject.Inject;
76
77 /**
78  * The core of XDCC Downloader.
79  *
80  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
81  */
82 public class Core extends AbstractIdleService {
83
84         /** The logger. */
85         private static final Logger logger = Logger.getLogger(Core.class.getName());
86
87         /** The event bus. */
88         private final EventBus eventBus;
89
90         /** The temporary directory to download files to. */
91         private final String temporaryDirectory;
92
93         /** The directory to move finished downloads to. */
94         private final String finalDirectory;
95
96         /** The channels that should be monitored. */
97         private final Collection<Channel> channels = Sets.newHashSet();
98
99         /** The channels that are currentlymonitored. */
100         private final Collection<Channel> joinedChannels = Sets.newHashSet();
101
102         /** The channels that are joined but not configured. */
103         private final Collection<Channel> extraChannels = Sets.newHashSet();
104
105         /** The current network connections. */
106         private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
107
108         /** The currently known bots. */
109         private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
110
111         /** The current downloads. */
112         private final Map<String, Download> downloads = Maps.newHashMap();
113
114         /** The current DCC receivers. */
115         private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
116
117         /**
118          * Creates a new core.
119          *
120          * @param eventBus
121          *              The event bus
122          * @param temporaryDirectory
123          *              The directory to download files to
124          * @param finalDirectory
125          *              The directory to move finished files to
126          */
127         @Inject
128         public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
129                 this.eventBus = eventBus;
130                 this.temporaryDirectory = temporaryDirectory;
131                 this.finalDirectory = finalDirectory;
132         }
133
134         //
135         // ACCESSORS
136         //
137
138         /**
139          * Returns all configured channels. Due to various circumstances, configured
140          * channels might not actually be joined.
141          *
142          * @return All configured channels
143          */
144         public Collection<Channel> channels() {
145                 return ImmutableSet.copyOf(channels);
146         }
147
148         /**
149          * Returns all currently joined channels.
150          *
151          * @return All currently joined channels
152          */
153         public Collection<Channel> joinedChannels() {
154                 return ImmutableSet.copyOf(joinedChannels);
155         }
156
157         /**
158          * Returns all currently joined channels that are not configured.
159          *
160          * @return All currently joined but not configured channels
161          */
162         public Collection<Channel> extraChannels() {
163                 return ImmutableSet.copyOf(extraChannels);
164         }
165
166         /**
167          * Returns all currently known bots.
168          *
169          * @return All currently known bots
170          */
171         public Collection<Bot> bots() {
172                 return networkBots.values();
173         }
174
175         /**
176          * Returns the currently active DCC receivers.
177          *
178          * @return The currently active DCC receivers
179          */
180         public Collection<DccReceiver> dccReceivers() {
181                 return dccReceivers;
182         }
183
184         //
185         // ACTIONS
186         //
187
188         /**
189          * Adds a channel to monitor.
190          *
191          * @param channel
192          *              The channel to monitor
193          */
194         public void addChannel(Channel channel) {
195                 channels.add(channel);
196         }
197
198         /**
199          * Fetches the given pack from the given bot.
200          *
201          * @param bot
202          *              The bot to fetch the pack from
203          * @param pack
204          *              The pack to fetch
205          */
206         public void fetch(Bot bot, Pack pack) {
207                 Connection connection = networkConnections.get(bot.network());
208                 if (connection == null) {
209                         return;
210                 }
211
212                 Download download = new Download(bot, pack);
213                 downloads.put(pack.name(), download);
214
215                 try {
216                         connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
217                 } catch (IOException ioe1) {
218                         logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
219                 }
220         }
221
222         //
223         // ABSTRACTIDLESERVICE METHODS
224         //
225
226         @Override
227         protected void startUp() {
228                 for (Channel channel : channels) {
229                         logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
230                         if (!networkConnections.containsKey(channel.network())) {
231                                 /* select a random server. */
232                                 List<Server> servers = Lists.newArrayList(channel.network().servers());
233                                 Server server = servers.get((int) (Math.random() * servers.size()));
234                                 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
235                                 connection.username(RandomNickname.get()).realName(RandomNickname.get());
236                                 networkConnections.put(channel.network(), connection);
237                                 connection.start();
238                         }
239                 }
240
241                 /* notify listeners. */
242                 eventBus.post(new CoreStarted(this));
243         }
244
245         @Override
246         protected void shutDown() {
247         }
248
249         //
250         // EVENT HANDLERS
251         //
252
253         /**
254          * If a connection to a network has been established, the channels associated
255          * with this network are joined.
256          *
257          * @param connectionEstablished
258          *              The connection established event
259          */
260         @Subscribe
261         public void connectionEstablished(ConnectionEstablished connectionEstablished) {
262
263                 /* get network for connection. */
264                 Optional<Network> network = getNetwork(connectionEstablished.connection());
265
266                 /* found network? */
267                 if (!network.isPresent()) {
268                         return;
269                 }
270
271                 /* join all channels on this network. */
272                 for (Channel channel : channels) {
273                         if (channel.network().equals(network.get())) {
274                                 try {
275                                         connectionEstablished.connection().joinChannel(channel.name());
276                                 } catch (IOException ioe1) {
277                                         logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
278                                 }
279                         }
280                 }
281         }
282
283         /**
284          * Shows a message when a channel was joined by us.
285          *
286          * @param channelJoined
287          *              The channel joined event
288          */
289         @Subscribe
290         public void channelJoined(ChannelJoined channelJoined) {
291                 if (channelJoined.connection().isSource(channelJoined.client())) {
292                         Optional<Network> network = getNetwork(channelJoined.connection());
293                         if (!network.isPresent()) {
294                                 return;
295                         }
296
297                         Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
298                         if (!channel.isPresent()) {
299                                 /* it’s an extra channel. */
300                                 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
301                                 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
302                                 return;
303                         }
304
305                         joinedChannels.add(channel.get());
306                         logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
307                 }
308         }
309
310         /**
311          * Removes bots that leave a channel, or channels when it’s us that’s leaving.
312          *
313          * @param channelLeft
314          *              The channel left event
315          */
316         @Subscribe
317         public void channelLeft(ChannelLeft channelLeft) {
318                 Optional<Network> network = getNetwork(channelLeft.connection());
319                 if (!network.isPresent()) {
320                         return;
321                 }
322
323                 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
324                 if (bot == null) {
325                         /* maybe it was us? */
326                         if (channelLeft.connection().isSource(channelLeft.client())) {
327                                 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
328                                 if (!channel.isPresent()) {
329                                         /* maybe it was an extra channel? */
330                                         channel = getExtraChannel(network.get(), channelLeft.channel());
331                                         if (!channel.isPresent()) {
332                                                 /* okay, whatever. */
333                                                 return;
334                                         }
335
336                                         extraChannels.remove(channel);
337                                 } else {
338                                         channels.remove(channel.get());
339                                 }
340
341                                 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
342                         }
343
344                         return;
345                 }
346
347                 Bot removedBot = networkBots.remove(network.get(), channelLeft.client().nick().get());
348                 if (removedBot != null) {
349                         eventBus.post(new GenericMessage(String.format("Bot %s (%s) was removed, %d packs removed.", removedBot.name(), removedBot.network().name(), removedBot.packs().size())));
350                 }
351         }
352
353         /**
354          * Removes a client (which may be a bot) from the table of known bots.
355          *
356          * @param clientQuit
357          *              The client quit event
358          */
359         @Subscribe
360         public void clientQuit(ClientQuit clientQuit) {
361                 Optional<Network> network = getNetwork(clientQuit.connection());
362                 if (!network.isPresent()) {
363                         return;
364                 }
365
366                 Bot removedBot = networkBots.remove(network.get(), clientQuit.client().nick().get());
367                 if (removedBot != null) {
368                         eventBus.post(new GenericMessage(String.format("Bot %s (%s) was removed, %d packs removed.", removedBot.name(), removedBot.network().name(), removedBot.packs().size())));
369                 }
370         }
371
372         /**
373          * If the nickname of a bit changes, remove it from the old name and store it
374          * under the new name.
375          *
376          * @param nicknameChanged
377          *              The nickname changed event
378          */
379         @Subscribe
380         public void nicknameChanged(NicknameChanged nicknameChanged) {
381                 Optional<Network> network = getNetwork(nicknameChanged.connection());
382                 if (!network.isPresent()) {
383                         return;
384                 }
385
386                 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
387                 if (bot == null) {
388                         return;
389                 }
390
391                 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
392         }
393
394         /**
395          * If a message on a channel is received, it is parsed for pack information
396          * with is then added to a bot.
397          *
398          * @param channelMessageReceived
399          *              The channel message received event
400          */
401         @Subscribe
402         public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
403                 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
404                 if (!message.startsWith("#")) {
405                         /* most probably not a pack announcement. */
406                         return;
407                 }
408
409                 Optional<Network> network = getNetwork(channelMessageReceived.connection());
410                 if (!network.isPresent()) {
411                         /* message for unknown connection? */
412                         return;
413                 }
414
415                 /* parse pack information. */
416                 Optional<Pack> pack = parsePack(message);
417                 if (!pack.isPresent()) {
418                         return;
419                 }
420
421                 Bot bot;
422                 synchronized (networkBots) {
423                         if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
424                                 bot = new Bot(network.get()).name(channelMessageReceived.source().nick().get());
425                                 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
426                                 eventBus.post(new BotAdded(bot));
427                         } else {
428                                 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
429                         }
430                 }
431
432                 /* add pack. */
433                 bot.addPack(pack.get());
434                 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
435         }
436
437         /**
438          * Forward all private messages to every console.
439          *
440          * @param privateMessageReceived
441          *              The private message recevied event
442          */
443         @Subscribe
444         public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
445                 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
446         }
447
448         /**
449          * Starts a DCC download.
450          *
451          * @param dccSendReceived
452          *              The DCC SEND event
453          */
454         @Subscribe
455         public void dccSendReceived(DccSendReceived dccSendReceived) {
456                 Optional<Network> network = getNetwork(dccSendReceived.connection());
457                 if (!network.isPresent()) {
458                         return;
459                 }
460
461                 Download download = downloads.get(dccSendReceived.filename());
462                 if (download == null) {
463                         /* unknown download, ignore. */
464                         return;
465                 }
466
467                 /* check if the file already exists. */
468                 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
469                 if (outputFile.exists()) {
470                         long existingFileSize = outputFile.length();
471
472                         /* file already complete? */
473                         if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
474                                 /* file is apparently already complete. just move it. */
475                                 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
476                                         eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
477                                 } else {
478                                         eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
479                                 }
480
481                                 /* remove download. */
482                                 downloads.remove(download);
483                                 return;
484                         }
485
486                         /* file not complete yet, DCC resume it. */
487                         try {
488                                 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
489                                 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
490                         } catch (IOException ioe1) {
491                                 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
492                         }
493
494                         return;
495                 }
496
497                 /* file does not exist, start the download. */
498                 try {
499                         OutputStream fileOutputStream = new FileOutputStream(outputFile);
500                         DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
501                         download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
502                         dccReceivers.add(dccReceiver);
503                         dccReceiver.start();
504                         eventBus.post(new DownloadStarted(download));
505                 } catch (FileNotFoundException fnfe1) {
506                         eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
507                 }
508         }
509
510         @Subscribe
511         public void dccAcceptReceived(DccAcceptReceived dccAcceptReceived) {
512                 Optional<Network> network = getNetwork(dccAcceptReceived.connection());
513                 if (!network.isPresent()) {
514                         return;
515                 }
516
517                 Download download = downloads.get(dccAcceptReceived.filename());
518                 if (download == null) {
519                         /* unknown download, ignore. */
520                         return;
521                 }
522
523                 try {
524                         File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
525                         if (outputFile.length() != dccAcceptReceived.position()) {
526                                 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
527                                 logger.log(Level.WARNING, String.format("Download %s from %s: have %d bytes but wants to resume from %d!", dccAcceptReceived.filename(), dccAcceptReceived.source(), outputFile.length(), dccAcceptReceived.position()));
528
529                                 downloads.remove(download);
530                                 return;
531                         }
532                         OutputStream outputStream = new FileOutputStream(outputFile, true);
533                         DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
534                         download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
535                         dccReceivers.add(dccReceiver);
536                         dccReceiver.start();
537                         eventBus.post(new DownloadStarted(download));
538                 } catch (FileNotFoundException fnfe1) {
539                 }
540         }
541
542         /**
543          * Closes the output stream of the download and moves the file to the final
544          * location.
545          *
546          * @param dccDownloadFinished
547          *              The DCC download finished event
548          */
549         @Subscribe
550         public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
551                 Download download = downloads.get(dccDownloadFinished.dccReceiver().filename());
552                 if (download == null) {
553                         /* probably shouldn’t happen. */
554                         return;
555                 }
556
557                 try {
558                         download.outputStream().close();
559                         File file = new File(download.filename());
560                         file.renameTo(new File(finalDirectory, download.pack().name()));
561                         eventBus.post(new DownloadFinished(download));
562                         dccReceivers.remove(dccDownloadFinished.dccReceiver());
563                         downloads.remove(download);
564                 } catch (IOException ioe1) {
565                         /* TODO - handle all the errors. */
566                         logger.log(Level.WARNING, String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
567                 }
568         }
569
570         /**
571          * Closes the output stream and notifies all listeners of the failure.
572          *
573          * @param dccDownloadFailed
574          *              The DCC download failed event
575          */
576         @Subscribe
577         public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
578                 Download download = downloads.get(dccDownloadFailed.dccReceiver().filename());
579                 if (download == null) {
580                         /* probably shouldn’t happen. */
581                         return;
582                 }
583
584                 try {
585                         Closeables.close(download.outputStream(), true);
586                         eventBus.post(new DownloadFailed(download));
587                         dccReceivers.remove(dccDownloadFailed.dccReceiver());
588                         downloads.remove(download);
589                 } catch (IOException ioe1) {
590                         /* swallow silently. */
591                 }
592         }
593
594         //
595         // PRIVATE METHODS
596         //
597
598         /**
599          * Searches all current connections for the given connection, returning the
600          * associated network.
601          *
602          * @param connection
603          *              The connection to get the network for
604          * @return The network belonging to the connection, or {@link
605          *         Optional#absent()}
606          */
607         private Optional<Network> getNetwork(Connection connection) {
608                 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
609                         if (networkConnectionEntry.getValue().equals(connection)) {
610                                 return Optional.of(networkConnectionEntry.getKey());
611                         }
612                 }
613                 return Optional.absent();
614         }
615
616         /**
617          * Returns the configured channel for the given network and name.
618          *
619          * @param network
620          *              The network the channel is located on
621          * @param channelName
622          *              The name of the channel
623          * @return The configured channel, or {@link Optional#absent()} if no
624          *         configured channel matching the given network and name was found
625          */
626         public Optional<Channel> getChannel(Network network, String channelName) {
627                 for (Channel channel : channels) {
628                         if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
629                                 return Optional.of(channel);
630                         }
631                 }
632                 return Optional.absent();
633         }
634
635         /**
636          * Returns the extra channel for the given network and name.
637          *
638          * @param network
639          *              The network the channel is located on
640          * @param channelName
641          *              The name of the channel
642          * @return The extra channel, or {@link Optional#absent()} if no extra channel
643          *         matching the given network and name was found
644          */
645         public Optional<Channel> getExtraChannel(Network network, String channelName) {
646                 for (Channel channel : extraChannels) {
647                         if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
648                                 return Optional.of(channel);
649                         }
650                 }
651                 return Optional.absent();
652         }
653
654         /**
655          * Parses {@link Pack} information from the given message.
656          *
657          * @param message
658          *              The message to parse pack information from
659          * @return The parsed pack, or {@link Optional#absent()} if the message could
660          *         not be parsed into a pack
661          */
662         private Optional<Pack> parsePack(String message) {
663                 int squareOpen = message.indexOf('[');
664                 int squareClose = message.indexOf(']', squareOpen);
665                 if ((squareOpen == -1) && (squareClose == -1)) {
666                         return Optional.absent();
667                 }
668                 String packSize = message.substring(squareOpen + 1, squareClose);
669                 String packName = message.substring(message.lastIndexOf(' ') + 1);
670                 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
671                 return Optional.of(new Pack(packIndex, packSize, packName));
672         }
673
674 }