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.ChannelLeft;
38 import net.pterodactylus.irc.event.ChannelMessageReceived;
39 import net.pterodactylus.irc.event.ClientQuit;
40 import net.pterodactylus.irc.event.ConnectionEstablished;
41 import net.pterodactylus.irc.event.DccDownloadFailed;
42 import net.pterodactylus.irc.event.DccDownloadFinished;
43 import net.pterodactylus.irc.event.DccSendReceived;
44 import net.pterodactylus.irc.event.PrivateMessageReceived;
45 import net.pterodactylus.irc.util.MessageCleaner;
46 import net.pterodactylus.irc.util.RandomNickname;
47 import net.pterodactylus.xdcc.core.event.BotAdded;
48 import net.pterodactylus.xdcc.core.event.CoreStarted;
49 import net.pterodactylus.xdcc.core.event.DownloadFailed;
50 import net.pterodactylus.xdcc.core.event.DownloadFinished;
51 import net.pterodactylus.xdcc.core.event.DownloadStarted;
52 import net.pterodactylus.xdcc.core.event.GenericMessage;
53 import net.pterodactylus.xdcc.core.event.MessageReceived;
54 import net.pterodactylus.xdcc.data.Bot;
55 import net.pterodactylus.xdcc.data.Channel;
56 import net.pterodactylus.xdcc.data.Download;
57 import net.pterodactylus.xdcc.data.Network;
58 import net.pterodactylus.xdcc.data.Pack;
59 import net.pterodactylus.xdcc.data.Server;
61 import com.google.common.base.Optional;
62 import com.google.common.collect.HashBasedTable;
63 import com.google.common.collect.ImmutableSet;
64 import com.google.common.collect.Lists;
65 import com.google.common.collect.Maps;
66 import com.google.common.collect.Sets;
67 import com.google.common.collect.Table;
68 import com.google.common.eventbus.EventBus;
69 import com.google.common.eventbus.Subscribe;
70 import com.google.common.io.Closeables;
71 import com.google.common.util.concurrent.AbstractIdleService;
72 import com.google.inject.Inject;
75 * The core of XDCC Downloader.
77 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
79 public class Core extends AbstractIdleService {
82 private static final Logger logger = Logger.getLogger(Core.class.getName());
85 private final EventBus eventBus;
87 /** The temporary directory to download files to. */
88 private final String temporaryDirectory;
90 /** The directory to move finished downloads to. */
91 private final String finalDirectory;
93 /** The channels that should be monitored. */
94 private final Collection<Channel> channels = Sets.newHashSet();
96 /** The channels that are currentlymonitored. */
97 private final Collection<Channel> joinedChannels = Sets.newHashSet();
99 /** The channels that are joined but not configured. */
100 private final Collection<Channel> extraChannels = Sets.newHashSet();
102 /** The current network connections. */
103 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
105 /** The currently known bots. */
106 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
108 /** The current downloads. */
109 private final Map<String, Download> downloads = Maps.newHashMap();
111 /** The current DCC receivers. */
112 private final Collection<DccReceiver> dccReceivers = Lists.newArrayList();
115 * Creates a new core.
119 * @param temporaryDirectory
120 * The directory to download files to
121 * @param finalDirectory
122 * The directory to move finished files to
125 public Core(EventBus eventBus, String temporaryDirectory, String finalDirectory) {
126 this.eventBus = eventBus;
127 this.temporaryDirectory = temporaryDirectory;
128 this.finalDirectory = finalDirectory;
136 * Returns all configured channels. Due to various circumstances, configured
137 * channels might not actually be joined.
139 * @return All configured channels
141 public Collection<Channel> channels() {
142 return ImmutableSet.copyOf(channels);
146 * Returns all currently joined channels.
148 * @return All currently joined channels
150 public Collection<Channel> joinedChannels() {
151 return ImmutableSet.copyOf(joinedChannels);
155 * Returns all currently joined channels that are not configured.
157 * @return All currently joined but not configured channels
159 public Collection<Channel> extraChannels() {
160 return ImmutableSet.copyOf(extraChannels);
164 * Returns all currently known bots.
166 * @return All currently known bots
168 public Collection<Bot> bots() {
169 return networkBots.values();
173 * Returns the currently active DCC receivers.
175 * @return The currently active DCC receivers
177 public Collection<DccReceiver> dccReceivers() {
186 * Adds a channel to monitor.
189 * The channel to monitor
191 public void addChannel(Channel channel) {
192 channels.add(channel);
196 * Fetches the given pack from the given bot.
199 * The bot to fetch the pack from
203 public void fetch(Bot bot, Pack pack) {
204 Connection connection = networkConnections.get(bot.network());
205 if (connection == null) {
209 Download download = new Download(bot, pack);
210 downloads.put(pack.name(), download);
213 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
214 } catch (IOException ioe1) {
215 logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
220 // ABSTRACTIDLESERVICE METHODS
224 protected void startUp() {
225 for (Channel channel : channels) {
226 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
227 if (!networkConnections.containsKey(channel.network())) {
228 /* select a random server. */
229 List<Server> servers = Lists.newArrayList(channel.network().servers());
230 Server server = servers.get((int) (Math.random() * servers.size()));
231 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
232 connection.username(RandomNickname.get()).realName(RandomNickname.get());
233 networkConnections.put(channel.network(), connection);
238 /* notify listeners. */
239 eventBus.post(new CoreStarted(this));
243 protected void shutDown() {
251 * If a connection to a network has been established, the channels associated
252 * with this network are joined.
254 * @param connectionEstablished
255 * The connection established event
258 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
260 /* get network for connection. */
261 Optional<Network> network = getNetwork(connectionEstablished.connection());
264 if (!network.isPresent()) {
268 /* join all channels on this network. */
269 for (Channel channel : channels) {
270 if (channel.network().equals(network.get())) {
272 connectionEstablished.connection().joinChannel(channel.name());
273 } catch (IOException ioe1) {
274 logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
281 * Shows a message when a channel was joined by us.
283 * @param channelJoined
284 * The channel joined event
287 public void channelJoined(ChannelJoined channelJoined) {
288 if (channelJoined.connection().isSource(channelJoined.client())) {
289 Optional<Network> network = getNetwork(channelJoined.connection());
290 if (!network.isPresent()) {
294 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
295 if (!channel.isPresent()) {
296 /* it’s an extra channel. */
297 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
298 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
302 joinedChannels.add(channel.get());
303 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
308 * Removes bots that leave a channel, or channels when it’s us that’s leaving.
311 * The channel left event
314 public void channelLeft(ChannelLeft channelLeft) {
315 Optional<Network> network = getNetwork(channelLeft.connection());
316 if (!network.isPresent()) {
320 Bot bot = networkBots.get(network.get(), channelLeft.client().nick().get());
322 /* maybe it was us? */
323 if (channelLeft.connection().isSource(channelLeft.client())) {
324 Optional<Channel> channel = getChannel(network.get(), channelLeft.channel());
325 if (!channel.isPresent()) {
326 /* maybe it was an extra channel? */
327 channel = getExtraChannel(network.get(), channelLeft.channel());
328 if (!channel.isPresent()) {
329 /* okay, whatever. */
333 extraChannels.remove(channel);
335 channels.remove(channel.get());
338 eventBus.post(new GenericMessage(String.format("Left Channel %s on %s.", channel.get().name(), channel.get().network().name())));
344 networkBots.remove(network.get(), channelLeft.client().nick().get());
348 * Removes a client (which may be a bot) from the table of known bots.
351 * The client quit event
354 public void clientQuit(ClientQuit clientQuit) {
355 Optional<Network> network = getNetwork(clientQuit.connection());
356 if (!network.isPresent()) {
360 networkBots.remove(network.get(), clientQuit.client().nick().get());
364 * If a message on a channel is received, it is parsed for pack information
365 * with is then added to a bot.
367 * @param channelMessageReceived
368 * The channel message received event
371 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
372 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
373 if (!message.startsWith("#")) {
374 /* most probably not a pack announcement. */
378 Optional<Network> network = getNetwork(channelMessageReceived.connection());
379 if (!network.isPresent()) {
380 /* message for unknown connection? */
384 /* parse pack information. */
385 Optional<Pack> pack = parsePack(message);
386 if (!pack.isPresent()) {
391 synchronized (networkBots) {
392 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
393 bot = new Bot(network.get()).name(channelMessageReceived.source().nick().get());
394 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
395 eventBus.post(new BotAdded(bot));
397 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
402 bot.addPack(pack.get());
403 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
407 * Forward all private messages to every console.
409 * @param privateMessageReceived
410 * The private message recevied event
413 public void privateMessageReceived(PrivateMessageReceived privateMessageReceived) {
414 eventBus.post(new MessageReceived(privateMessageReceived.source(), privateMessageReceived.message()));
418 * Starts a DCC download.
420 * @param dccSendReceived
424 public void dccSendReceived(DccSendReceived dccSendReceived) {
425 Optional<Network> network = getNetwork(dccSendReceived.connection());
426 if (!network.isPresent()) {
430 Download download = downloads.get(dccSendReceived.filename());
431 if (download == null) {
432 /* unknown download, ignore. */
436 logger.info(String.format("Starting download of %s.", dccSendReceived.filename()));
438 File outputFile = new File(temporaryDirectory, dccSendReceived.filename());
439 OutputStream fileOutputStream = new FileOutputStream(outputFile);
440 DccReceiver dccReceiver = new DccReceiver(eventBus, dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
441 download.filename(outputFile.getPath()).outputStream(fileOutputStream).dccReceiver(dccReceiver);
442 dccReceivers.add(dccReceiver);
444 eventBus.post(new DownloadStarted(download));
445 } catch (FileNotFoundException fnfe1) {
446 logger.log(Level.WARNING, "Could not open file for download!", fnfe1);
451 * Closes the output stream of the download and moves the file to the final
454 * @param dccDownloadFinished
455 * The DCC download finished event
458 public void dccDownloadFinished(DccDownloadFinished dccDownloadFinished) {
459 Download download = downloads.get(dccDownloadFinished.dccReceiver().filename());
460 if (download == null) {
461 /* probably shouldn’t happen. */
466 download.outputStream().close();
467 File file = new File(download.filename());
468 file.renameTo(new File(finalDirectory, download.pack().name()));
469 eventBus.post(new DownloadFinished(download));
470 dccReceivers.remove(dccDownloadFinished.dccReceiver());
471 downloads.remove(download);
472 } catch (IOException ioe1) {
473 /* TODO - handle all the errors. */
474 logger.log(Level.WARNING, String.format("Could not move file %s to directory %s.", download.filename(), finalDirectory), ioe1);
479 * Closes the output stream and notifies all listeners of the failure.
481 * @param dccDownloadFailed
482 * The DCC download failed event
485 public void dccDownloadFailed(DccDownloadFailed dccDownloadFailed) {
486 Download download = downloads.get(dccDownloadFailed.dccReceiver().filename());
487 if (download == null) {
488 /* probably shouldn’t happen. */
493 Closeables.close(download.outputStream(), true);
494 eventBus.post(new DownloadFailed(download));
495 dccReceivers.remove(dccDownloadFailed.dccReceiver());
496 downloads.remove(download);
497 } catch (IOException ioe1) {
498 /* swallow silently. */
507 * Searches all current connections for the given connection, returning the
508 * associated network.
511 * The connection to get the network for
512 * @return The network belonging to the connection, or {@link
515 private Optional<Network> getNetwork(Connection connection) {
516 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
517 if (networkConnectionEntry.getValue().equals(connection)) {
518 return Optional.of(networkConnectionEntry.getKey());
521 return Optional.absent();
525 * Returns the configured channel for the given network and name.
528 * The network the channel is located on
530 * The name of the channel
531 * @return The configured channel, or {@link Optional#absent()} if no
532 * configured channel matching the given network and name was found
534 public Optional<Channel> getChannel(Network network, String channelName) {
535 for (Channel channel : channels) {
536 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
537 return Optional.of(channel);
540 return Optional.absent();
544 * Returns the extra channel for the given network and name.
547 * The network the channel is located on
549 * The name of the channel
550 * @return The extra channel, or {@link Optional#absent()} if no extra channel
551 * matching the given network and name was found
553 public Optional<Channel> getExtraChannel(Network network, String channelName) {
554 for (Channel channel : extraChannels) {
555 if (channel.network().equals(network) && (channel.name().equalsIgnoreCase(channelName))) {
556 return Optional.of(channel);
559 return Optional.absent();
563 * Parses {@link Pack} information from the given message.
566 * The message to parse pack information from
567 * @return The parsed pack, or {@link Optional#absent()} if the message could
568 * not be parsed into a pack
570 private Optional<Pack> parsePack(String message) {
571 int squareOpen = message.indexOf('[');
572 int squareClose = message.indexOf(']', squareOpen);
573 if ((squareOpen == -1) && (squareClose == -1)) {
574 return Optional.absent();
576 String packSize = message.substring(squareOpen + 1, squareClose);
577 String packName = message.substring(message.lastIndexOf(' ') + 1);
578 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
579 return Optional.of(new Pack(packIndex, packSize, packName));