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