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.DccDownloadFailed;
40 import net.pterodactylus.irc.event.DccDownloadFinished;
41 import net.pterodactylus.irc.event.DccSendReceived;
42 import net.pterodactylus.irc.util.MessageCleaner;
43 import net.pterodactylus.irc.util.RandomNickname;
44 import net.pterodactylus.xdcc.core.event.BotAdded;
45 import net.pterodactylus.xdcc.core.event.CoreStarted;
46 import net.pterodactylus.xdcc.core.event.DownloadFailed;
47 import net.pterodactylus.xdcc.core.event.DownloadFinished;
48 import net.pterodactylus.xdcc.core.event.DownloadStarted;
49 import net.pterodactylus.xdcc.data.Bot;
50 import net.pterodactylus.xdcc.data.Channel;
51 import net.pterodactylus.xdcc.data.Download;
52 import net.pterodactylus.xdcc.data.Network;
53 import net.pterodactylus.xdcc.data.Pack;
54 import net.pterodactylus.xdcc.data.Server;
56 import com.google.common.base.Optional;
57 import com.google.common.collect.HashBasedTable;
58 import com.google.common.collect.ImmutableSet;
59 import com.google.common.collect.Lists;
60 import com.google.common.collect.Maps;
61 import com.google.common.collect.Sets;
62 import com.google.common.collect.Table;
63 import com.google.common.eventbus.EventBus;
64 import com.google.common.eventbus.Subscribe;
65 import com.google.common.io.Closeables;
66 import com.google.common.util.concurrent.AbstractIdleService;
67 import com.google.inject.Inject;
70 * The core of XDCC Downloader.
72 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
74 public class Core extends AbstractIdleService {
77 private static final Logger logger = Logger.getLogger(Core.class.getName());
80 private final EventBus eventBus;
82 /** The temporary directory to download files to. */
83 private final String temporaryDirectory;
85 /** The directory to move finished downloads to. */
86 private final String finalDirectory;
88 /** The channels that should be monitored. */
89 private final Collection<Channel> channels = Sets.newHashSet();
91 /** The channels that are currentlymonitored. */
92 private final Collection<Channel> joinedChannels = Sets.newHashSet();
94 /** The channels that are joined but not configured. */
95 private final Collection<Channel> extraChannels = Sets.newHashSet();
97 /** The current network connections. */
98 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
100 /** The currently known bots. */
101 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
103 /** The current downloads. */
104 private final Map<String, Download> downloads = Maps.newHashMap();
106 /** The current DCC receivers. */
107 private final Collection<DccReceiver> dccReceivers = Sets.newHashSet();
110 * Creates a new core.
114 * @param temporaryDirectory
115 * The directory to download files to
116 * @param finalDirectory
117 * The directory to move finished files to
120 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
121 this.eventBus = eventBus;
122 this.temporaryDirectory = temporaryDirectory;
123 this.finalDirectory = finalDirectory;
131 * Returns all configured channels. Due to various circumstances, configured
132 * channels might not actually be joined.
134 * @return All configured channels
136 public Collection<Channel> channels() {
137 return ImmutableSet.copyOf(channels);
141 * Returns all currently joined channels.
143 * @return All currently joined channels
145 public Collection<Channel> joinedChannels() {
146 return ImmutableSet.copyOf(joinedChannels);
150 * Returns all currently joined channels that are not configured.
152 * @return All currently joined but not configured channels
154 public Collection<Channel> extraChannels() {
155 return ImmutableSet.copyOf(extraChannels);
159 * Returns all currently known bots.
161 * @return All currently known bots
163 public Collection<Bot> bots() {
164 return networkBots.values();
168 * Returns the currently active DCC receivers.
170 * @return The currently active DCC receivers
172 public Collection<DccReceiver> dccReceivers() {
181 * Adds a channel to monitor.
184 * The channel to monitor
186 public void addChannel(Channel channel) {
187 channels.add(channel);
191 * Fetches the given pack from the given bot.
194 * The bot to fetch the pack from
198 public void fetch(Bot bot, Pack pack) {
199 Connection connection = networkConnections.get(bot.network());
200 if (connection == null) {
204 Download download = new Download(bot, pack);
205 downloads.put(pack.name(), download);
208 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
209 } catch (IOException ioe1) {
210 logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
215 // ABSTRACTIDLESERVICE METHODS
219 protected void startUp() {
220 for (Channel channel : channels) {
221 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
222 if (!networkConnections.containsKey(channel.network())) {
223 /* select a random server. */
224 List<Server> servers = Lists.newArrayList(channel.network().servers());
225 Server server = servers.get((int) (Math.random() * servers.size()));
226 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
227 connection.username(RandomNickname.get()).realName(RandomNickname.get());
228 networkConnections.put(channel.network(), connection);
233 /* notify listeners. */
234 eventBus.post(new CoreStarted(this));
238 protected void shutDown() {
246 * If a connection to a network has been established, the channels associated
247 * with this network are joined.
249 * @param connectionEstablished
250 * The connection established event
253 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
255 /* get network for connection. */
256 Optional<Network> network = getNetwork(connectionEstablished.connection());
259 if (!network.isPresent()) {
263 /* join all channels on this network. */
264 for (Channel channel : channels) {
265 if (channel.network().equals(network.get())) {
267 connectionEstablished.connection().joinChannel(channel.name());
268 } catch (IOException ioe1) {
269 logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
276 * Shows a message when a channel was joined by us.
278 * @param channelJoined
279 * The channel joined event
282 public void channelJoined(ChannelJoined channelJoined) {
283 if (channelJoined.connection().isSource(channelJoined.client())) {
284 Optional<Network> network = getNetwork(channelJoined.connection());
285 if (!network.isPresent()) {
289 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
290 if (!channel.isPresent()) {
291 /* it’s an extra channel. */
292 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
293 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
297 joinedChannels.add(channel.get());
298 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
303 * If a message on a channel is received, it is parsed for pack information
304 * with is then added to a bot.
306 * @param channelMessageReceived
307 * The channel message received event
310 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
311 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
312 if (!message.startsWith("#")) {
313 /* most probably not a pack announcement. */
317 Optional<Network> network = getNetwork(channelMessageReceived.connection());
318 if (!network.isPresent()) {
319 /* message for unknown connection? */
323 /* parse pack information. */
324 Optional<Pack> pack = parsePack(message);
325 if (!pack.isPresent()) {
330 synchronized (networkBots) {
331 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
332 bot = new Bot(network.get()).name(channelMessageReceived.source().nick().get());
333 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
334 eventBus.post(new BotAdded(bot));
336 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
341 bot.addPack(pack.get());
342 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
346 * Starts a DCC download.
348 * @param dccSendReceived
352 public void dccSendReceived(DccSendReceived dccSendReceived) {
353 Optional<Network> network = getNetwork(dccSendReceived.connection());
354 if (!network.isPresent()) {
358 Download download = downloads.get(dccSendReceived.filename());
359 if (download == null) {
360 /* unknown download, ignore. */
364 logger.info(String.format("Starting download of %s.", dccSendReceived.filename()));
366 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
367 OutputStream fileOutputStream = new FileOutputStream(outputFile);
368 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
369 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
370 dccReceivers.add(dccReceiver);
372 eventBus.post(new DownloadStarted(download));
373 } catch (FileNotFoundException fnfe1) {
374 logger.log(Level.WARNING, "Could not open file for download!", fnfe1);
379 * Closes the output stream of the download and moves the file to the final
382 * @param dccDownloadFinished
383 * The DCC download finished event
386 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
387 Download download = downloads.get(dccDownloadFinished.dccReceiver().filename());
388 if (download == null) {
389 /* probably shouldn’t happen. */
394 download.outputStream().close();
395 File file = new File(download.filename());
396 file.renameTo(new File(finalDirectory, download.pack().name()));
397 eventBus.post(new DownloadFinished(download));
398 } catch (IOException ioe1) {
399 /* TODO - handle all the errors. */
400 logger.log(Level.WARNING, String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
405 * Closes the output stream and notifies all listeners of the failure.
407 * @param dccDownloadFailed
408 * The DCC download failed event
411 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
412 Download download = downloads.get(dccDownloadFailed.dccReceiver().filename());
413 if (download == null) {
414 /* probably shouldn’t happen. */
419 Closeables.close(download.outputStream(), true);
420 eventBus.post(new DownloadFailed(download));
421 } catch (IOException ioe1) {
422 /* swallow silently. */
431 * Searches all current connections for the given connection, returning the
432 * associated network.
435 * The connection to get the network for
436 * @return The network belonging to the connection, or {@link
439 private Optional<Network> getNetwork(Connection connection) {
440 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
441 if (networkConnectionEntry.getValue().equals(connection)) {
442 return Optional.of(networkConnectionEntry.getKey());
445 return Optional.absent();
449 * Returns the configured channel for the given network and name.
452 * The network the channel is located on
454 * The name of the channel
455 * @return The configured channel, or {@link Optional#absent()} if no
456 * configured channel matching the given network and name was found
458 public Optional<Channel> getChannel(Network network, String channelName) {
459 for (Channel channel : channels) {
460 if (channel.network().equals(network) && (channel.name().equals(channelName))) {
461 return Optional.of(channel);
464 return Optional.absent();
468 * Parses {@link Pack} information from the given message.
471 * The message to parse pack information from
472 * @return The parsed pack, or {@link Optional#absent()} if the message could
473 * not be parsed into a pack
475 private Optional<Pack> parsePack(String message) {
476 int squareOpen = message.indexOf('[');
477 int squareClose = message.indexOf(']', squareOpen);
478 if ((squareOpen == -1) && (squareClose == -1)) {
479 return Optional.absent();
481 String packSize = message.substring(squareOpen + 1, squareClose);
482 String packName = message.substring(message.lastIndexOf(' ') + 1);
483 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
484 return Optional.of(new Pack(packIndex, packSize, packName));