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.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;
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;
65 * The core of XDCC Downloader.
67 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
69 public class Core extends AbstractIdleService {
72 private static final Logger logger = Logger.getLogger(Core.class.getName());
75 private final EventBus eventBus;
77 /** The temporary directory to download files to. */
78 private final String temporaryDirectory;
80 /** The directory to move finished downloads to. */
81 private final String finalDirectory;
83 /** The channels that should be monitored. */
84 private final Collection<Channel> channels = Sets.newHashSet();
86 /** The channels that are currentlymonitored. */
87 private final Collection<Channel> joinedChannels = Sets.newHashSet();
89 /** The channels that are joined but not configured. */
90 private final Collection<Channel> extraChannels = Sets.newHashSet();
92 /** The current network connections. */
93 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
95 /** The currently known bots. */
96 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
98 /** The current downloads. */
99 private final Map<String, Download> downloads = Maps.newHashMap();
101 /** The current DCC receivers. */
102 private final Collection<DccReceiver> dccReceivers = Sets.newHashSet();
105 * Creates a new core.
109 * @param temporaryDirectory
110 * The directory to download files to
111 * @param finalDirectory
112 * The directory to move finished files to
115 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
116 this.eventBus = eventBus;
117 this.temporaryDirectory = temporaryDirectory;
118 this.finalDirectory = finalDirectory;
126 * Returns all configured channels. Due to various circumstances, configured
127 * channels might not actually be joined.
129 * @return All configured channels
131 public Collection<Channel> channels() {
132 return ImmutableSet.copyOf(channels);
136 * Returns all currently joined channels.
138 * @return All currently joined channels
140 public Collection<Channel> joinedChannels() {
141 return ImmutableSet.copyOf(joinedChannels);
145 * Returns all currently joined channels that are not configured.
147 * @return All currently joined but not configured channels
149 public Collection<Channel> extraChannels() {
150 return ImmutableSet.copyOf(extraChannels);
154 * Returns all currently known bots.
156 * @return All currently known bots
158 public Collection<Bot> bots() {
159 return networkBots.values();
163 * Returns the currently active DCC receivers.
165 * @return The currently active DCC receivers
167 public Collection<DccReceiver> dccReceivers() {
176 * Adds a channel to monitor.
179 * The channel to monitor
181 public void addChannel(Channel channel) {
182 channels.add(channel);
186 * Fetches the given pack from the given bot.
189 * The bot to fetch the pack from
193 public void fetch(Bot bot, Pack pack) {
194 Connection connection = networkConnections.get(bot.network());
195 if (connection == null) {
199 Download download = new Download(bot, pack);
200 downloads.put(pack.name(), download);
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);
210 // ABSTRACTIDLESERVICE METHODS
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);
228 /* notify listeners. */
229 eventBus.post(new CoreStarted(this));
233 protected void shutDown() {
241 * If a connection to a network has been established, the channels associated
242 * with this network are joined.
244 * @param connectionEstablished
245 * The connection established event
248 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
250 /* get network for connection. */
251 Optional<Network> network = getNetwork(connectionEstablished.connection());
254 if (!network.isPresent()) {
258 /* join all channels on this network. */
259 for (Channel channel : channels) {
260 if (channel.network().equals(network.get())) {
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);
271 * Shows a message when a channel was joined by us.
273 * @param channelJoined
274 * The channel joined event
277 public void channelJoined(ChannelJoined channelJoined) {
278 if (channelJoined.connection().isSource(channelJoined.client())) {
279 Optional<Network> network = getNetwork(channelJoined.connection());
280 if (!network.isPresent()) {
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()));
292 joinedChannels.add(channel.get());
293 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
298 * If a message on a channel is received, it is parsed for pack information
299 * with is then added to a bot.
301 * @param channelMessageReceived
302 * The channel message received event
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. */
312 Optional<Network> network = getNetwork(channelMessageReceived.connection());
313 if (!network.isPresent()) {
314 /* message for unknown connection? */
318 /* parse pack information. */
319 Optional<Pack> pack = parsePack(message);
320 if (!pack.isPresent()) {
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));
331 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
336 bot.addPack(pack.get());
337 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
341 * Starts a DCC download.
343 * @param dccSendReceived
347 public void dccSendReceived(DccSendReceived dccSendReceived) {
348 Optional<Network> network = getNetwork(dccSendReceived.connection());
349 if (!network.isPresent()) {
353 Download download = downloads.get(dccSendReceived.filename());
354 if (download == null) {
355 /* unknown download, ignore. */
359 logger.info(String.format("Starting download of %s.", dccSendReceived.filename()));
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);
367 } catch (FileNotFoundException fnfe1) {
368 logger.log(Level.WARNING, "Could not open file for download!", fnfe1);
373 * Closes the output stream of the download and moves the file to the final
376 * @param dccDownloadFinished
377 * The DCC download finished event
380 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
381 Download download = downloads.get(dccDownloadFinished.dccReceiver().filename());
382 if (download == null) {
383 /* probably shouldn’t happen. */
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);
402 * Searches all current connections for the given connection, returning the
403 * associated network.
406 * The connection to get the network for
407 * @return The network belonging to the connection, or {@link
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());
416 return Optional.absent();
420 * Returns the configured channel for the given network and name.
423 * The network the channel is located on
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
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);
435 return Optional.absent();
439 * Parses {@link Pack} information from the given 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
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();
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));