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