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