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