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