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