Add events for DCC downloads.
[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 channels that are joined but not configured. */
82         private final Collection<Channel> extraChannels = Sets.newHashSet();
83
84         /** The current network connections. */
85         private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
86
87         /** The currently known bots. */
88         private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
89
90         /** The current DCC receivers. */
91         private final Collection<DccReceiver> dccReceivers = Sets.newHashSet();
92
93         /**
94          * Creates a new core.
95          *
96          * @param eventBus
97          *              The event bus
98          */
99         @Inject
100         public Core(EventBus eventBus) {
101                 this.eventBus = eventBus;
102         }
103
104         //
105         // ACCESSORS
106         //
107
108         /**
109          * Returns all configured channels. Due to various circumstances, configured
110          * channels might not actually be joined.
111          *
112          * @return All configured channels
113          */
114         public Collection<Channel> channels() {
115                 return ImmutableSet.copyOf(channels);
116         }
117
118         /**
119          * Returns all currently joined channels.
120          *
121          * @return All currently joined channels
122          */
123         public Collection<Channel> joinedChannels() {
124                 return ImmutableSet.copyOf(joinedChannels);
125         }
126
127         /**
128          * Returns all currently joined channels that are not configured.
129          *
130          * @return All currently joined but not configured channels
131          */
132         public Collection<Channel> extraChannels() {
133                 return ImmutableSet.copyOf(extraChannels);
134         }
135
136         /**
137          * Returns all currently known bots.
138          *
139          * @return All currently known bots
140          */
141         public Collection<Bot> bots() {
142                 return networkBots.values();
143         }
144
145         /**
146          * Returns the currently active DCC receivers.
147          *
148          * @return The currently active DCC receivers
149          */
150         public Collection<DccReceiver> dccReceivers() {
151                 return dccReceivers;
152         }
153
154         //
155         // ACTIONS
156         //
157
158         /**
159          * Adds a channel to monitor.
160          *
161          * @param channel
162          *              The channel to monitor
163          */
164         public void addChannel(Channel channel) {
165                 channels.add(channel);
166         }
167
168         /**
169          * Fetches the given pack from the given bot.
170          *
171          * @param bot
172          *              The bot to fetch the pack from
173          * @param pack
174          *              The pack to fetch
175          */
176         public void fetch(Bot bot, Pack pack) {
177                 Connection connection = networkConnections.get(bot.network());
178                 if (connection == null) {
179                         return;
180                 }
181
182                 try {
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);
186                 }
187         }
188
189         //
190         // ABSTRACTIDLESERVICE METHODS
191         //
192
193         @Override
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);
204                                 connection.start();
205                         }
206                 }
207
208                 /* notify listeners. */
209                 eventBus.post(new CoreStarted(this));
210         }
211
212         @Override
213         protected void shutDown() {
214         }
215
216         //
217         // EVENT HANDLERS
218         //
219
220         /**
221          * If a connection to a network has been established, the channels associated
222          * with this network are joined.
223          *
224          * @param connectionEstablished
225          *              The connection established event
226          */
227         @Subscribe
228         public void connectionEstablished(ConnectionEstablished connectionEstablished) {
229
230                 /* get network for connection. */
231                 Optional<Network> network = getNetwork(connectionEstablished.connection());
232
233                 /* found network? */
234                 if (!network.isPresent()) {
235                         return;
236                 }
237
238                 /* join all channels on this network. */
239                 for (Channel channel : channels) {
240                         if (channel.network().equals(network.get())) {
241                                 try {
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);
245                                 }
246                         }
247                 }
248         }
249
250         /**
251          * Shows a message when a channel was joined by us.
252          *
253          * @param channelJoined
254          *              The channel joined event
255          */
256         @Subscribe
257         public void channelJoined(ChannelJoined channelJoined) {
258                 if (channelJoined.connection().isSource(channelJoined.client())) {
259                         Optional<Network> network = getNetwork(channelJoined.connection());
260                         if (!network.isPresent()) {
261                                 return;
262                         }
263
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()));
269                                 return;
270                         }
271
272                         joinedChannels.add(channel.get());
273                         logger.info(String.format("Joined Channel %s on %s.", channelJoined.channel(), network.get().name()));
274                 }
275         }
276
277         /**
278          * If a message on a channel is received, it is parsed for pack information
279          * with is then added to a bot.
280          *
281          * @param channelMessageReceived
282          *              The channel message received event
283          */
284         @Subscribe
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. */
289                         return;
290                 }
291
292                 Optional<Network> network = getNetwork(channelMessageReceived.connection());
293                 if (!network.isPresent()) {
294                         /* message for unknown connection? */
295                         return;
296                 }
297
298                 /* parse pack information. */
299                 Optional<Pack> pack = parsePack(message);
300                 if (!pack.isPresent()) {
301                         return;
302                 }
303
304                 Bot bot;
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));
310                         } else {
311                                 bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
312                         }
313                 }
314
315                 /* add pack. */
316                 bot.addPack(pack.get());
317                 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
318         }
319
320         /**
321          * Starts a DCC download.
322          *
323          * @param dccSendReceived
324          *              The DCC SEND event
325          */
326         @Subscribe
327         public void dccSendReceived(DccSendReceived dccSendReceived) {
328                 logger.info(String.format("Starting download of %s.", dccSendReceived.filename()));
329                 try {
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);
333                         dccReceiver.start();
334                 } catch (FileNotFoundException fnfe1) {
335                         logger.log(Level.WARNING, "Could not open file for download!", fnfe1);
336                 }
337         }
338
339         //
340         // PRIVATE METHODS
341         //
342
343         /**
344          * Searches all current connections for the given connection, returning the
345          * associated network.
346          *
347          * @param connection
348          *              The connection to get the network for
349          * @return The network belonging to the connection, or {@link
350          *         Optional#absent()}
351          */
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());
356                         }
357                 }
358                 return Optional.absent();
359         }
360
361         /**
362          * Returns the configured channel for the given network and name.
363          *
364          * @param network
365          *              The network the channel is located on
366          * @param channelName
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
370          */
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);
375                         }
376                 }
377                 return Optional.absent();
378         }
379
380         /**
381          * Parses {@link Pack} information from the given message.
382          *
383          * @param 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
387          */
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();
393                 }
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));
398         }
399
400 }