Add current state of core.
[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.event.ChannelMessageReceived;
32 import net.pterodactylus.irc.event.ConnectionEstablished;
33 import net.pterodactylus.irc.util.MessageCleaner;
34 import net.pterodactylus.irc.util.RandomNickname;
35 import net.pterodactylus.xdcc.data.Bot;
36 import net.pterodactylus.xdcc.data.Channel;
37 import net.pterodactylus.xdcc.data.Network;
38 import net.pterodactylus.xdcc.data.Pack;
39 import net.pterodactylus.xdcc.data.Server;
40
41 import com.beust.jcommander.internal.Maps;
42 import com.beust.jcommander.internal.Sets;
43 import com.google.common.base.Optional;
44 import com.google.common.collect.HashBasedTable;
45 import com.google.common.collect.Lists;
46 import com.google.common.collect.Table;
47 import com.google.common.eventbus.EventBus;
48 import com.google.common.eventbus.Subscribe;
49 import com.google.common.util.concurrent.AbstractIdleService;
50 import com.google.inject.Inject;
51
52 /**
53  * The core of XDCC Downloader.
54  *
55  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
56  */
57 public class Core extends AbstractIdleService {
58
59         /** The logger. */
60         private static final Logger logger = Logger.getLogger(Core.class.getName());
61
62         /** The event bus. */
63         private final EventBus eventBus;
64
65         /** The channels that should be monitored. */
66         private final Collection<Channel> channels = Sets.newHashSet();
67
68         /** The current network connections. */
69         private final Map<Network, Connection> networkConnections = Collections.synchronizedMap(Maps.<Network, Connection>newHashMap());
70
71         /** The currently known bots. */
72         private final Table<Network, String, Bot> networkBots = HashBasedTable.create();
73
74         /**
75          * Creates a new core.
76          *
77          * @param eventBus
78          *              The event bus
79          */
80         @Inject
81         public Core(EventBus eventBus) {
82                 this.eventBus = eventBus;
83         }
84
85         //
86         // ACTIONS
87         //
88
89         /**
90          * Adds a channel to monitor.
91          *
92          * @param channel
93          *              The channel to monitor
94          */
95         public void addChannel(Channel channel) {
96                 channels.add(channel);
97         }
98
99         //
100         // ABSTRACTIDLESERVICE METHODS
101         //
102
103         @Override
104         protected void startUp() {
105                 for (Channel channel : channels) {
106                         logger.info(String.format("Connecting to Channel %s on Network %s…", channel.name(), channel.network().name()));
107                         if (!networkConnections.containsKey(channel.network())) {
108                                 /* select a random server. */
109                                 List<Server> servers = Lists.newArrayList(channel.network().servers());
110                                 Server server = servers.get((int) (Math.random() * servers.size()));
111                                 Connection connection = new ConnectionBuilder(eventBus).connect(server.hostname()).port(server.unencryptedPorts().iterator().next()).build();
112                                 connection.username(RandomNickname.get()).realName(RandomNickname.get());
113                                 networkConnections.put(channel.network(), connection);
114                                 connection.start();
115                         }
116                 }
117         }
118
119         @Override
120         protected void shutDown() {
121         }
122
123         //
124         // EVENT HANDLERS
125         //
126
127         /**
128          * If a connection to a network has been established, the channels associated
129          * with this network are joined.
130          *
131          * @param connectionEstablished
132          *              The connection established event
133          */
134         @Subscribe
135         public void connectionEstablished(ConnectionEstablished connectionEstablished) {
136
137                 /* get network for connection. */
138                 Optional<Network> network = getNetwork(connectionEstablished.connection());
139
140                 /* found network? */
141                 if (!network.isPresent()) {
142                         return;
143                 }
144
145                 /* join all channels on this network. */
146                 for (Channel channel : channels) {
147                         if (channel.network().equals(network)) {
148                                 try {
149                                         connectionEstablished.connection().joinChannel(channel.name());
150                                 } catch (IOException ioe1) {
151                                         logger.log(Level.WARNING, String.format("Could not join %s on %s!", channel.name(), network.get().name()), ioe1);
152                                 }
153                         }
154                 }
155         }
156
157         /**
158          * If a message on a channel is received, it is parsed for pack information
159          * with is then added to a bot.
160          *
161          * @param channelMessageReceived
162          *              The channel message received event
163          */
164         @Subscribe
165         public void channelMessageReceived(ChannelMessageReceived channelMessageReceived) {
166                 String message = MessageCleaner.getDefaultInstance().clean(channelMessageReceived.message());
167                 if (!message.startsWith("#")) {
168                         /* most probably not a pack announcement. */
169                         return;
170                 }
171
172                 Optional<Network> network = getNetwork(channelMessageReceived.connection());
173                 if (!network.isPresent()) {
174                         /* message for unknown connection? */
175                         return;
176                 }
177
178                 Bot bot;
179                 synchronized (networkBots) {
180                         if (!networkBots.contains(network.get(), channelMessageReceived.source().nick().get())) {
181                                 networkBots.put(network.get(), channelMessageReceived.source().nick().get(), new Bot(network.get()).name(channelMessageReceived.source().nick().get()));
182                         }
183                         bot = networkBots.get(network.get(), channelMessageReceived.source().nick().get());
184                 }
185
186                 /* parse pack information. */
187                 Optional<Pack> pack = parsePack(message);
188                 if (!pack.isPresent()) {
189                         return;
190                 }
191
192                 /* add pack. */
193                 bot.addPack(pack.get());
194                 logger.fine(String.format("Bot %s now has %d packs.", bot, bot.packs().size()));
195         }
196
197         //
198         // PRIVATE METHODS
199         //
200
201         /**
202          * Searches all current connections for the given connection, returning the
203          * associated network.
204          *
205          * @param connection
206          *              The connection to get the network for
207          * @return The network belonging to the connection, or {@link
208          *         Optional#absent()}
209          */
210         private Optional<Network> getNetwork(Connection connection) {
211                 for (Entry<Network, Connection> networkConnectionEntry : networkConnections.entrySet()) {
212                         if (networkConnectionEntry.getValue().equals(connection)) {
213                                 return Optional.of(networkConnectionEntry.getKey());
214                         }
215                 }
216                 return Optional.absent();
217         }
218
219         /**
220          * Parses {@link Pack} information from the given message.
221          *
222          * @param message
223          *              The message to parse pack information from
224          * @return The parsed pack, or {@link Optional#absent()} if the message could
225          *         not be parsed into a pack
226          */
227         private Optional<Pack> parsePack(String message) {
228                 int squareOpen = message.indexOf('[');
229                 int squareClose = message.indexOf(']', squareOpen);
230                 if ((squareOpen == -1) && (squareClose == -1)) {
231                         return Optional.absent();
232                 }
233                 String packSize = message.substring(squareOpen + 1, squareClose);
234                 String packName = message.substring(message.lastIndexOf(' ') + 1);
235                 String packIndex = message.substring(0, message.indexOf(' ')).substring(1);
236                 return Optional.of(new Pack(packIndex, packSize, packName));
237         }
238
239 }