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