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.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.Network;
47 import net.pterodactylus.xdcc.data.Pack;
48 import net.pterodactylus.xdcc.data.Server;
50 import com.google.common.base.Optional;
51 import com.google.common.collect.HashBasedTable;
52 import com.google.common.collect.ImmutableSet;
53 import com.google.common.collect.Lists;
54 import com.google.common.collect.Maps;
55 import com.google.common.collect.Sets;
56 import com.google.common.collect.Table;
57 import com.google.common.eventbus.EventBus;
58 import com.google.common.eventbus.Subscribe;
59 import com.google.common.util.concurrent.AbstractIdleService;
60 import com.google.inject.Inject;
63 * The core of XDCC Downloader.
65 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
67 public class Core extends AbstractIdleService {
70 private static final Logger logger = Logger.getLogger(Core.class.getName());
73 private final EventBus eventBus;
75 /** The channels that should be monitored. */
76 private final Collection<Channel> channels = Sets.newHashSet();
78 /** The channels that are currentlymonitored. */
79 private final Collection<Channel> joinedChannels = Sets.newHashSet();
81 /** The channels that are joined but not configured. */
82 private final Collection<Channel> extraChannels = Sets.newHashSet();
84 /** The current network connections. */
85 private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
87 /** The currently known bots. */
88 private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
90 /** The current DCC receivers. */
91 private final Collection<DccReceiver> dccReceivers = Sets.newHashSet();
100 public Core(EventBus eventBus) {
101 this.eventBus = eventBus;
109 * Returns all configured channels. Due to various circumstances, configured
110 * channels might not actually be joined.
112 * @return All configured channels
114 public Collection<Channel> channels() {
115 return ImmutableSet.copyOf(channels);
119 * Returns all currently joined channels.
121 * @return All currently joined channels
123 public Collection<Channel> joinedChannels() {
124 return ImmutableSet.copyOf(joinedChannels);
128 * Returns all currently joined channels that are not configured.
130 * @return All currently joined but not configured channels
132 public Collection<Channel> extraChannels() {
133 return ImmutableSet.copyOf(extraChannels);
137 * Returns all currently known bots.
139 * @return All currently known bots
141 public Collection<Bot> bots() {
142 return networkBots.values();
146 * Returns the currently active DCC receivers.
148 * @return The currently active DCC receivers
150 public Collection<DccReceiver> dccReceivers() {
159 * Adds a channel to monitor.
162 * The channel to monitor
164 public void addChannel(Channel channel) {
165 channels.add(channel);
169 * Fetches the given pack from the given bot.
172 * The bot to fetch the pack from
176 public void fetch(Bot bot, Pack pack) {
177 Connection connection = networkConnections.get(bot.network());
178 if (connection == null) {
183 connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
184 } catch (IOException ioe1) {
185 logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
190 // ABSTRACTIDLESERVICE METHODS
194 protected void startUp() {
195 for (Channel channel : channels) {
196 logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
197 if (!networkConnections.containsKey(channel.network())) {
198 /* select a random server. */
199 List<Server> servers = Lists.newArrayList(channel.network().servers());
200 Server server = servers.get((int) (Math.random() * servers.size()));
201 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
202 connection.username(RandomNickname.get()).realName(RandomNickname.get());
203 networkConnections.put(channel.network(), connection);
208 /* notify listeners. */
209 eventBus.post(new CoreStarted(this));
213 protected void shutDown() {
221 * If a connection to a network has been established, the channels associated
222 * with this network are joined.
224 * @param connectionEstablished
225 * The connection established event
228 public void connectionEstablished(ConnectionEstablished connectionEstablished) {
230 /* get network for connection. */
231 Optional<Network> network = getNetwork(connectionEstablished.connection());
234 if (!network.isPresent()) {
238 /* join all channels on this network. */
239 for (Channel channel : channels) {
240 if (channel.network().equals(network.get())) {
242 connectionEstablished.connection().joinChannel(channel.name());
243 } catch (IOException ioe1) {
244 logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
251 * Shows a message when a channel was joined by us.
253 * @param channelJoined
254 * The channel joined event
257 public void channelJoined(ChannelJoined channelJoined) {
258 if (channelJoined.connection().isSource(channelJoined.client())) {
259 Optional<Network> network = getNetwork(channelJoined.connection());
260 if (!network.isPresent()) {
264 Optional<Channel> channel = getChannel(network.get(), channelJoined.channel());
265 if (!channel.isPresent()) {
266 /* it’s an extra channel. */
267 extraChannels.add(new Channel(network.get(), channelJoined.channel()));
268 logger.info(String.format("Joined extra Channel %s on %s.", channelJoined.channel(), network.get().name()));
272 joinedChannels.add(channel.get());
273 logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
278 * If a message on a channel is received, it is parsed for pack information
279 * with is then added to a bot.
281 * @param channelMessageReceived
282 * The channel message received event
285 public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
286 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
287 if (!message.startsWith("#")) {
288 /* most probably not a pack announcement. */
292 Optional<Network> network = getNetwork(channelMessageReceived.connection());
293 if (!network.isPresent()) {
294 /* message for unknown connection? */
298 /* parse pack information. */
299 Optional<Pack> pack = parsePack(message);
300 if (!pack.isPresent()) {
305 synchronized (networkBots) {
306 if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
307 bot = new Bot(network.get()).name(channelMessageReceived.source().nick().get());
308 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
309 eventBus.post(new BotAdded(bot));
311 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
316 bot.addPack(pack.get());
317 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
321 * Starts a DCC download.
323 * @param dccSendReceived
327 public void dccSendReceived(DccSendReceived dccSendReceived) {
328 logger.info(String.format("Starting download of %s.", dccSendReceived.filename()));
330 OutputStream fileOutputStream = new FileOutputStream(new File("/home/bombe/Temp", dccSendReceived.filename()));
331 DccReceiver dccReceiver = new DccReceiver(dccSendReceived.inetAddress(), dccSendReceived.port(), dccSendReceived.filename(), dccSendReceived.filesize(), fileOutputStream);
332 dccReceivers.add(dccReceiver);
334 } catch (FileNotFoundException fnfe1) {
335 logger.log(Level.WARNING, "Could not open file for download!", fnfe1);
344 * Searches all current connections for the given connection, returning the
345 * associated network.
348 * The connection to get the network for
349 * @return The network belonging to the connection, or {@link
352 private Optional<Network> getNetwork(Connection connection) {
353 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
354 if (networkConnectionEntry.getValue().equals(connection)) {
355 return Optional.of(networkConnectionEntry.getKey());
358 return Optional.absent();
362 * Returns the configured channel for the given network and name.
365 * The network the channel is located on
367 * The name of the channel
368 * @return The configured channel, or {@link Optional#absent()} if no
369 * configured channel matching the given network and name was found
371 public Optional<Channel> getChannel(Network network, String channelName) {
372 for (Channel channel : channels) {
373 if (channel.network().equals(network) && (channel.name().equals(channelName))) {
374 return Optional.of(channel);
377 return Optional.absent();
381 * Parses {@link Pack} information from the given message.
384 * The message to parse pack information from
385 * @return The parsed pack, or {@link Optional#absent()} if the message could
386 * not be parsed into a pack
388 private Optional<Pack> parsePack(String message) {
389 int squareOpen = message.indexOf('[');
390 int squareClose = message.indexOf(']', squareOpen);
391 if ((squareOpen == -1) && (squareClose == -1)) {
392 return Optional.absent();
394 String packSize = message.substring(squareOpen + 1, squareClose);
395 String packName = message.substring(message.lastIndexOf(' ') + 1);
396 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
397 return Optional.of(new Pack(packIndex, packSize, packName));