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