2 * XdccDownloader - Core.java - Copyright © 2013 David Roden
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.
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.
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/>.
18 package net.pterodactylus.xdcc.core;
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;
29 import java.util.Map.Entry;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
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;
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;
67 * The core of XDCC Downloader.
69 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
71 public class Core extends AbstractIdleService {
74 private static final Logger logger = Logger.getLogger(Core.class.getName());
77 private final EventBus eventBus;
79 /** The temporary directory to download files to. */
80 private final String temporaryDirectory;
82 /** The directory to move finished downloads to. */
83 private final String finalDirectory;
85 /** The channels that should be monitored. */
86 private final Collection<Channel> channels = Sets.newHashSet();
88 /** The channels that are currentlymonitored. */
89 private final Collection<Channel> joinedChannels = Sets.newHashSet();
91 /** The channels that are joined but not configured. */
92 private final Collection<Channel> extraChannels = Sets.newHashSet();
94 /** The current network connections. */
95 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
97 /** The currently known bots. */
98 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
100 /** The current downloads. */
101 private final Map<String, Download> downloads = Maps.newHashMap();
103 /** The current DCC receivers. */
104 private final Collection<DccReceiver> dccReceivers = Sets.newHashSet();
107 * Creates a new core.
111 * @param temporaryDirectory
112 * The directory to download files to
113 * @param finalDirectory
114 * The directory to move finished files to
117 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
118 this.eventBus = eventBus;
119 this.temporaryDirectory = temporaryDirectory;
120 this.finalDirectory = finalDirectory;
128 * Returns all configured channels. Due to various circumstances, configured
129 * channels might not actually be joined.
131 * @return All configured channels
133 public Collection<Channel> channels() {
134 return ImmutableSet.copyOf(channels);
138 * Returns all currently joined channels.
140 * @return All currently joined channels
142 public Collection<Channel> joinedChannels() {
143 return ImmutableSet.copyOf(joinedChannels);
147 * Returns all currently joined channels that are not configured.
149 * @return All currently joined but not configured channels
151 public Collection<Channel> extraChannels() {
152 return ImmutableSet.copyOf(extraChannels);
156 * Returns all currently known bots.
158 * @return All currently known bots
160 public Collection<Bot> bots() {
161 return networkBots.values();
165 * Returns the currently active DCC receivers.
167 * @return The currently active DCC receivers
169 public Collection<DccReceiver> dccReceivers() {
178 * Adds a channel to monitor.
181 * The channel to monitor
183 public void addChannel(Channel channel) {
184 channels.add(channel);
188 * Fetches the given pack from the given bot.
191 * The bot to fetch the pack from
195 public void fetch(Bot bot, Pack pack) {
196 Connection connection = networkConnections.get(bot.network());
197 if (connection == null) {
201 Download download = new Download(bot, pack);
202 downloads.put(pack.name(), download);
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);
212 // ABSTRACTIDLESERVICE METHODS
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);
230 /* notify listeners. */
231 eventBus.post(new CoreStarted(this));
235 protected void shutDown() {
243 * If a connection to a network has been established, the channels associated
244 * with this network are joined.
246 * @param connectionEstablished
247 * The connection established event
250 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
252 /* get network for connection. */
253 Optional<Network> network = getNetwork(connectionEstablished.connection());
256 if (!network.isPresent()) {
260 /* join all channels on this network. */
261 for (Channel channel : channels) {
262 if (channel.network().equals(network.get())) {
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);
273 * Shows a message when a channel was joined by us.
275 * @param channelJoined
276 * The channel joined event
279 public void channelJoined(ChannelJoined channelJoined) {
280 if (channelJoined.connection().isSource(channelJoined.client())) {
281 Optional<Network> network = getNetwork(channelJoined.connection());
282 if (!network.isPresent()) {
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()));
294 joinedChannels.add(channel.get());
295 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
300 * If a message on a channel is received, it is parsed for pack information
301 * with is then added to a bot.
303 * @param channelMessageReceived
304 * The channel message received event
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. */
314 Optional<Network> network = getNetwork(channelMessageReceived.connection());
315 if (!network.isPresent()) {
316 /* message for unknown connection? */
320 /* parse pack information. */
321 Optional<Pack> pack = parsePack(message);
322 if (!pack.isPresent()) {
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));
333 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
338 bot.addPack(pack.get());
339 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
343 * Starts a DCC download.
345 * @param dccSendReceived
349 public void dccSendReceived(DccSendReceived dccSendReceived) {
350 Optional<Network> network = getNetwork(dccSendReceived.connection());
351 if (!network.isPresent()) {
355 Download download = downloads.get(dccSendReceived.filename());
356 if (download == null) {
357 /* unknown download, ignore. */
361 logger.info(String.format("Starting download of %s.", dccSendReceived.filename()));
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);
369 eventBus.post(new DownloadStarted(download));
370 } catch (FileNotFoundException fnfe1) {
371 logger.log(Level.WARNING, "Could not open file for download!", fnfe1);
376 * Closes the output stream of the download and moves the file to the final
379 * @param dccDownloadFinished
380 * The DCC download finished event
383 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
384 Download download = downloads.get(dccDownloadFinished.dccReceiver().filename());
385 if (download == null) {
386 /* probably shouldn’t happen. */
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);
406 * Searches all current connections for the given connection, returning the
407 * associated network.
410 * The connection to get the network for
411 * @return The network belonging to the connection, or {@link
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());
420 return Optional.absent();
424 * Returns the configured channel for the given network and name.
427 * The network the channel is located on
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
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);
439 return Optional.absent();
443 * Parses {@link Pack} information from the given 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
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();
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));