Add command to initiate a download from a bot.
[xudocci.git] / src / main / java / net / pterodactylus / xdcc / core / Core.java
1 /*
2  * XdccDownloader - Core.java - Copyright © 2013 David Roden
3  *
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.pterodactylus.xdcc.core;
19
20 import java.io.IOException;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
28
29 import net.pterodactylus.irc.Connection;
30 import net.pterodactylus.irc.ConnectionBuilder;
31 import net.pterodactylus.irc.DccReceiver;
32 import net.pterodactylus.irc.event.ChannelMessageReceived;
33 import net.pterodactylus.irc.event.ConnectionEstablished;
34 import net.pterodactylus.irc.util.MessageCleaner;
35 import net.pterodactylus.irc.util.RandomNickname;
36 import net.pterodactylus.xdcc.core.event.BotAdded;
37 import net.pterodactylus.xdcc.core.event.CoreStarted;
38 import net.pterodactylus.xdcc.data.Bot;
39 import net.pterodactylus.xdcc.data.Channel;
40 import net.pterodactylus.xdcc.data.Network;
41 import net.pterodactylus.xdcc.data.Pack;
42 import net.pterodactylus.xdcc.data.Server;
43
44 import com.google.common.base.Optional;
45 import com.google.common.collect.HashBasedTable;
46 import com.google.common.collect.Lists;
47 import com.google.common.collect.Maps;
48 import com.google.common.collect.Sets;
49 import com.google.common.collect.Table;
50 import com.google.common.eventbus.EventBus;
51 import com.google.common.eventbus.Subscribe;
52 import com.google.common.util.concurrent.AbstractIdleService;
53 import com.google.inject.Inject;
54
55 /**
56  * The core of XDCC Downloader.
57  *
58  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
59  */
60 public class Core extends AbstractIdleService {
61
62         /** The logger. */
63         private static final Logger logger = Logger.getLogger(Core.class.getName());
64
65         /** The event bus. */
66         private final EventBus eventBus;
67
68         /** The channels that should be monitored. */
69         private final Collection<Channel> channels = Sets.newHashSet();
70
71         /** The current network connections. */
72         private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
73
74         /** The currently known bots. */
75         private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
76
77         /** The current DCC receivers. */
78         private final Collection<DccReceiver> dccReceivers = Sets.newHashSet();
79
80         /**
81          * Creates a new core.
82          *
83          * @param eventBus
84          *              The event bus
85          */
86         @Inject
87         public Core(EventBus eventBus) {
88                 this.eventBus = eventBus;
89         }
90
91         //
92         // ACCESSORS
93         //
94
95         /**
96          * Returns all currently known bots.
97          *
98          * @return All currently known bots
99          */
100         public Collection<Bot> bots() {
101                 return networkBots.values();
102         }
103
104         /**
105          * Returns the currently active DCC receivers.
106          *
107          * @return The currently active DCC receivers
108          */
109         public Collection<DccReceiver> dccReceivers() {
110                 return dccReceivers;
111         }
112
113         //
114         // ACTIONS
115         //
116
117         /**
118          * Adds a channel to monitor.
119          *
120          * @param channel
121          *              The channel to monitor
122          */
123         public void addChannel(Channel channel) {
124                 channels.add(channel);
125         }
126
127         /**
128          * Fetches the given pack from the given bot.
129          *
130          * @param bot
131          *              The bot to fetch the pack from
132          * @param pack
133          *              The pack to fetch
134          */
135         public void fetch(Bot bot, Pack pack) {
136                 Connection connection = networkConnections.get(bot.network());
137                 if (connection == null) {
138                         return;
139                 }
140
141                 try {
142                         connection.sendMessage(bot.name(), "XDCC SEND " + pack.id());
143                 } catch (IOException ioe1) {
144                         logger.log(Level.WARNING, "Could not send message to bot!", ioe1);
145                 }
146         }
147
148         //
149         // ABSTRACTIDLESERVICE METHODS
150         //
151
152         @Override
153         protected void startUp() {
154                 for (Channel channel : channels) {
155                         logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
156                         if (!networkConnections.containsKey(channel.network())) {
157                                 /* select a random server. */
158                                 List<Server> servers = Lists.newArrayList(channel.network().servers());
159                                 Server server = servers.get((int) (Math.random() * servers.size()));
160                                 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
161                                 connection.username(RandomNickname.get()).realName(RandomNickname.get());
162                                 networkConnections.put(channel.network(), connection);
163                                 connection.start();
164                         }
165                 }
166
167                 /* notify listeners. */
168                 eventBus.post(new CoreStarted(this));
169         }
170
171         @Override
172         protected void shutDown() {
173         }
174
175         //
176         // EVENT HANDLERS
177         //
178
179         /**
180          * If a connection to a network has been established, the channels associated
181          * with this network are joined.
182          *
183          * @param connectionEstablished
184          *              The connection established event
185          */
186         @Subscribe
187         public void connectionEstablished(ConnectionEstablished connectionEstablished) {
188
189                 /* get network for connection. */
190                 Optional<Network> network = getNetwork(connectionEstablished.connection());
191
192                 /* found network? */
193                 if (!network.isPresent()) {
194                         return;
195                 }
196
197                 /* join all channels on this network. */
198                 for (Channel channel : channels) {
199                         if (channel.network().equals(network.get())) {
200                                 try {
201                                         connectionEstablished.connection().joinChannel(channel.name());
202                                 } catch (IOException ioe1) {
203                                         logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
204                                 }
205                         }
206                 }
207         }
208
209         /**
210          * If a message on a channel is received, it is parsed for pack information
211          * with is then added to a bot.
212          *
213          * @param channelMessageReceived
214          *              The channel message received event
215          */
216         @Subscribe
217         public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
218                 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
219                 if (!message.startsWith("#")) {
220                         /* most probably not a pack announcement. */
221                         return;
222                 }
223
224                 Optional<Network> network = getNetwork(channelMessageReceived.connection());
225                 if (!network.isPresent()) {
226                         /* message for unknown connection? */
227                         return;
228                 }
229
230                 /* parse pack information. */
231                 Optional<Pack> pack = parsePack(message);
232                 if (!pack.isPresent()) {
233                         return;
234                 }
235
236                 Bot bot;
237                 synchronized (networkBots) {
238                         if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
239                                 bot = new Bot(network.get()).name(channelMessageReceived.source().nick().get());
240                                 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), bot);
241                                 eventBus.post(new BotAdded(bot));
242                         } else {
243                                 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
244                         }
245                 }
246
247                 /* add pack. */
248                 bot.addPack(pack.get());
249                 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
250         }
251
252         //
253         // PRIVATE METHODS
254         //
255
256         /**
257          * Searches all current connections for the given connection, returning the
258          * associated network.
259          *
260          * @param connection
261          *              The connection to get the network for
262          * @return The network belonging to the connection, or {@link
263          *         Optional#absent()}
264          */
265         private Optional<Network> getNetwork(Connection connection) {
266                 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
267                         if (networkConnectionEntry.getValue().equals(connection)) {
268                                 return Optional.of(networkConnectionEntry.getKey());
269                         }
270                 }
271                 return Optional.absent();
272         }
273
274         /**
275          * Parses {@link Pack} information from the given message.
276          *
277          * @param message
278          *              The message to parse pack information from
279          * @return The parsed pack, or {@link Optional#absent()} if the message could
280          *         not be parsed into a pack
281          */
282         private Optional<Pack> parsePack(String message) {
283                 int squareOpen = message.indexOf('[');
284                 int squareClose = message.indexOf(']', squareOpen);
285                 if ((squareOpen == -1) && (squareClose == -1)) {
286                         return Optional.absent();
287                 }
288                 String packSize = message.substring(squareOpen + 1, squareClose);
289                 String packName = message.substring(message.lastIndexOf(' ') + 1);
290                 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
291                 return Optional.of(new Pack(packIndex, packSize, packName));
292         }
293
294 }