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