Move network connecting into its own method.
[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                         connectNetwork(channel.network());
231                 }
232
233                 /* notify listeners. */
234                 eventBus.post(new CoreStarted(this));
235         }
236
237         @Override
238         protected void shutDown() {
239         }
240
241         //
242         // PRIVATE METHODS
243         //
244
245         /**
246          * Starts a new connection for the given network if no such connection exists
247          * already.
248          *
249          * @param network
250          *              The network to connect to
251          */
252         private void connectNetwork(Network network) {
253                 if (!networkConnections.containsKey(network)) {
254                                 /* select a random server. */
255                         List<Server> servers = Lists.newArrayList(network.servers());
256                         if (servers.isEmpty()) {
257                                 eventBus.post(new GenericError(String.format("Network %s does not have any servers.", network.name())));
258                                 return;
259                         }
260                         Server server = servers.get((int) (Math.random() * servers.size()));
261                         Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
262                         connection.username(RandomNickname.get()).realName(RandomNickname.get());
263                         networkConnections.put(network, connection);
264                         connection.start();
265                 }
266         }
267
268         //
269         // EVENT HANDLERS
270         //
271
272         /**
273          * If a connection to a network has been established, the channels associated
274          * with this network are joined.
275          *
276          * @param connectionEstablished
277          *              The connection established event
278          */
279         @Subscribe
280         public void connectionEstablished(ConnectionEstablished connectionEstablished) {
281
282                 /* get network for connection. */
283                 Optional<Network> network = getNetwork(connectionEstablished.connection());
284
285                 /* found network? */
286                 if (!network.isPresent()) {
287                         return;
288                 }
289
290                 /* join all channels on this network. */
291                 for (Channel channel : channels) {
292                         if (channel.network().equals(network.get())) {
293                                 try {
294                                         connectionEstablished.connection().joinChannel(channel.name());
295                                 } catch (IOException ioe1) {
296                                         logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
297                                 }
298                         }
299                 }
300         }
301
302         /**
303          * Shows a message when a channel was joined by us.
304          *
305          * @param channelJoined
306          *              The channel joined event
307          */
308         @Subscribe
309         public void channelJoined(ChannelJoined channelJoined) {
310                 if (channelJoined.connection().isSource(channelJoined.client())) {
311                         Optional<Network> network = getNetwork(channelJoined.connection());
312                         if (!network.isPresent()) {
313                                 return;
314                         }
315
316                         Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
317                         if (!channel.isPresent()) {
318                                 /* it’s an extra channel. */
319                                 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
320                                 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
321                                 return;
322                         }
323
324                         joinedChannels.add(channel.get());
325                         logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
326                 }
327         }
328
329         /**
330          * Removes bots that leave a channel, or channels when it’s us that’s leaving.
331          *
332          * @param channelLeft
333          *              The channel left event
334          */
335         @Subscribe
336         public void channelLeft(ChannelLeft channelLeft) {
337                 Optional<Network> network = getNetwork(channelLeft.connection());
338                 if (!network.isPresent()) {
339                         return;
340                 }
341
342                 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
343                 if (bot == null) {
344                         /* maybe it was us? */
345                         if (channelLeft.connection().isSource(channelLeft.client())) {
346                                 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
347                                 if (!channel.isPresent()) {
348                                         /* maybe it was an extra channel? */
349                                         channel = getExtraChannel(network.get(), channelLeft.channel());
350                                         if (!channel.isPresent()) {
351                                                 /* okay, whatever. */
352                                                 return;
353                                         }
354
355                                         extraChannels.remove(channel);
356                                 } else {
357                                         channels.remove(channel.get());
358                                 }
359
360                                 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
361                         }
362
363                         return;
364                 }
365
366                 Bot removedBot = networkBots.remove(network.get(), channelLeft.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          * Removes a client (which may be a bot) from the table of known bots.
374          *
375          * @param clientQuit
376          *              The client quit event
377          */
378         @Subscribe
379         public void clientQuit(ClientQuit clientQuit) {
380                 Optional<Network> network = getNetwork(clientQuit.connection());
381                 if (!network.isPresent()) {
382                         return;
383                 }
384
385                 Bot removedBot = networkBots.remove(network.get(), clientQuit.client().nick().get());
386                 if (removedBot != null) {
387                         eventBus.post(new GenericMessage(String.format("Bot %s (%s) was removed, %d packs removed.", removedBot.name(), removedBot.network().name(), removedBot.packs().size())));
388                 }
389         }
390
391         /**
392          * If the nickname of a bit changes, remove it from the old name and store it
393          * under the new name.
394          *
395          * @param nicknameChanged
396          *              The nickname changed event
397          */
398         @Subscribe
399         public void nicknameChanged(NicknameChanged nicknameChanged) {
400                 Optional<Network> network = getNetwork(nicknameChanged.connection());
401                 if (!network.isPresent()) {
402                         return;
403                 }
404
405                 Bot bot = networkBots.remove(network.get(), nicknameChanged.client().nick().get());
406                 if (bot == null) {
407                         return;
408                 }
409
410                 networkBots.put(network.get(), nicknameChanged.newNickname(), bot);
411         }
412
413         /**
414          * If a message on a channel is received, it is parsed for pack information
415          * with is then added to a bot.
416          *
417          * @param channelMessageReceived
418          *              The channel message received event
419          */
420         @Subscribe
421         public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
422                 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
423                 if (!message.startsWith("#")) {
424                         /* most probably not a pack announcement. */
425                         return;
426                 }
427
428                 Optional<Network> network = getNetwork(channelMessageReceived.connection());
429                 if (!network.isPresent()) {
430                         /* message for unknown connection? */
431                         return;
432                 }
433
434                 /* parse pack information. */
435                 Optional<Pack> pack = parsePack(message);
436                 if (!pack.isPresent()) {
437                         return;
438                 }
439
440                 Bot bot;
441                 synchronized (networkBots) {
442                         if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
443                                 bot = new Bot(network.get()).name(channelMessageReceived.source().nick().get());
444                                 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
445                                 eventBus.post(new BotAdded(bot));
446                         } else {
447                                 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
448                         }
449                 }
450
451                 /* add pack. */
452                 bot.addPack(pack.get());
453                 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
454         }
455
456         /**
457          * Forward all private messages to every console.
458          *
459          * @param privateMessageReceived
460          *              The private message recevied event
461          */
462         @Subscribe
463         public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
464                 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
465         }
466
467         /**
468          * Starts a DCC download.
469          *
470          * @param dccSendReceived
471          *              The DCC SEND event
472          */
473         @Subscribe
474         public void dccSendReceived(DccSendReceived dccSendReceived) {
475                 Optional<Network> network = getNetwork(dccSendReceived.connection());
476                 if (!network.isPresent()) {
477                         return;
478                 }
479
480                 Download download = downloads.get(dccSendReceived.filename());
481                 if (download == null) {
482                         /* unknown download, ignore. */
483                         return;
484                 }
485
486                 /* check if the file already exists. */
487                 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
488                 if (outputFile.exists()) {
489                         long existingFileSize = outputFile.length();
490
491                         /* file already complete? */
492                         if ((dccSendReceived.filesize() > -1) && (existingFileSize >= dccSendReceived.filesize())) {
493                                 /* file is apparently already complete. just move it. */
494                                 if (outputFile.renameTo(new File(finalDirectory, download.pack().name()))) {
495                                         eventBus.post(new GenericMessage(String.format("File %s already downloaded.", download.pack().name())));
496                                 } else {
497                                         eventBus.post(new GenericMessage(String.format("File %s already downloaded but not moved to %s.", download.pack().name(), finalDirectory)));
498                                 }
499
500                                 /* remove download. */
501                                 downloads.remove(download);
502                                 return;
503                         }
504
505                         /* file not complete yet, DCC resume it. */
506                         try {
507                                 download.remoteAddress(dccSendReceived.inetAddress()).filesize(dccSendReceived.filesize());
508                                 dccSendReceived.connection().sendDccResume(dccSendReceived.source().nick().get(), dccSendReceived.filename(), dccSendReceived.port(), existingFileSize);
509                         } catch (IOException ioe1) {
510                                 eventBus.post(new GenericError(String.format("Could not send DCC RESUME %s to %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), ioe1.getMessage())));
511                         }
512
513                         return;
514                 }
515
516                 /* file does not exist, start the download. */
517                 try {
518                         OutputStream fileOutputStream = new FileOutputStream(outputFile);
519                         DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
520                         download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
521                         dccReceivers.add(dccReceiver);
522                         dccReceiver.start();
523                         eventBus.post(new DownloadStarted(download));
524                 } catch (FileNotFoundException fnfe1) {
525                         eventBus.post(new GenericError(String.format("Could not start download of %s from %s (%s).", dccSendReceived.filename(), dccSendReceived.source().nick().get(), fnfe1.getMessage())));
526                 }
527         }
528
529         @Subscribe
530         public void dccAcceptReceived(DccAcceptReceived dccAcceptReceived) {
531                 Optional<Network> network = getNetwork(dccAcceptReceived.connection());
532                 if (!network.isPresent()) {
533                         return;
534                 }
535
536                 Download download = downloads.get(dccAcceptReceived.filename());
537                 if (download == null) {
538                         /* unknown download, ignore. */
539                         return;
540                 }
541
542                 try {
543                         File outputFile = new File(temporaryDirectory, dccAcceptReceived.filename());
544                         if (outputFile.length() != dccAcceptReceived.position()) {
545                                 eventBus.post(new GenericError(String.format("Download %s from %s does not start at the right position!")));
546                                 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()));
547
548                                 downloads.remove(download);
549                                 return;
550                         }
551                         OutputStream outputStream = new FileOutputStream(outputFile, true);
552                         DccReceiver dccReceiver = new DccReceiver(eventBus, download.remoteAddress(), dccAcceptReceived.port(), dccAcceptReceived.filename(), dccAcceptReceived.position(), download.filesize(), outputStream);
553                         download.filename(outputFile.getPath()).outputStream(outputStream).dccReceiver(dccReceiver);
554                         dccReceivers.add(dccReceiver);
555                         dccReceiver.start();
556                         eventBus.post(new DownloadStarted(download));
557                 } catch (FileNotFoundException fnfe1) {
558                 }
559         }
560
561         /**
562          * Closes the output stream of the download and moves the file to the final
563          * location.
564          *
565          * @param dccDownloadFinished
566          *              The DCC download finished event
567          */
568         @Subscribe
569         public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
570                 Download download = downloads.get(dccDownloadFinished.dccReceiver().filename());
571                 if (download == null) {
572                         /* probably shouldn’t happen. */
573                         return;
574                 }
575
576                 try {
577                         download.outputStream().close();
578                         File file = new File(download.filename());
579                         file.renameTo(new File(finalDirectory, download.pack().name()));
580                         eventBus.post(new DownloadFinished(download));
581                         dccReceivers.remove(dccDownloadFinished.dccReceiver());
582                         downloads.remove(download);
583                 } catch (IOException ioe1) {
584                         /* TODO - handle all the errors. */
585                         logger.log(Level.WARNING, String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
586                 }
587         }
588
589         /**
590          * Closes the output stream and notifies all listeners of the failure.
591          *
592          * @param dccDownloadFailed
593          *              The DCC download failed event
594          */
595         @Subscribe
596         public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
597                 Download download = downloads.get(dccDownloadFailed.dccReceiver().filename());
598                 if (download == null) {
599                         /* probably shouldn’t happen. */
600                         return;
601                 }
602
603                 try {
604                         Closeables.close(download.outputStream(), true);
605                         eventBus.post(new DownloadFailed(download));
606                         dccReceivers.remove(dccDownloadFailed.dccReceiver());
607                         downloads.remove(download);
608                 } catch (IOException ioe1) {
609                         /* swallow silently. */
610                 }
611         }
612
613         //
614         // PRIVATE METHODS
615         //
616
617         /**
618          * Searches all current connections for the given connection, returning the
619          * associated network.
620          *
621          * @param connection
622          *              The connection to get the network for
623          * @return The network belonging to the connection, or {@link
624          *         Optional#absent()}
625          */
626         private Optional<Network> getNetwork(Connection connection) {
627                 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
628                         if (networkConnectionEntry.getValue().equals(connection)) {
629                                 return Optional.of(networkConnectionEntry.getKey());
630                         }
631                 }
632                 return Optional.absent();
633         }
634
635         /**
636          * Returns the configured 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 configured channel, or {@link Optional#absent()} if no
643          *         configured channel matching the given network and name was found
644          */
645         public Optional<Channel> getChannel(Network network, String channelName) {
646                 for (Channel channel : channels) {
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          * Returns the extra channel for the given network and name.
656          *
657          * @param network
658          *              The network the channel is located on
659          * @param channelName
660          *              The name of the channel
661          * @return The extra channel, or {@link Optional#absent()} if no extra channel
662          *         matching the given network and name was found
663          */
664         public Optional<Channel> getExtraChannel(Network network, String channelName) {
665                 for (Channel channel : extraChannels) {
666                         if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
667                                 return Optional.of(channel);
668                         }
669                 }
670                 return Optional.absent();
671         }
672
673         /**
674          * Parses {@link Pack} information from the given message.
675          *
676          * @param message
677          *              The message to parse pack information from
678          * @return The parsed pack, or {@link Optional#absent()} if the message could
679          *         not be parsed into a pack
680          */
681         private Optional<Pack> parsePack(String message) {
682                 int squareOpen = message.indexOf('[');
683                 int squareClose = message.indexOf(']', squareOpen);
684                 if ((squareOpen == -1) && (squareClose == -1)) {
685                         return Optional.absent();
686                 }
687                 String packSize = message.substring(squareOpen + 1, squareClose);
688                 String packName = message.substring(message.lastIndexOf(' ') + 1);
689                 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
690                 return Optional.of(new Pack(packIndex, packSize, packName));
691         }
692
693 }