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