2 * XdccDownloader - CommandReader.java - Copyright © 2013 David Roden
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.
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.
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/>.
18 package net.pterodactylus.xdcc.ui.stdin;
20 import java.io.BufferedReader;
21 import java.io.IOException;
22 import java.io.Reader;
23 import java.io.Writer;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.List;
29 import net.pterodactylus.irc.Connection;
30 import net.pterodactylus.irc.DccReceiver;
31 import net.pterodactylus.irc.util.MessageCleaner;
32 import net.pterodactylus.xdcc.core.Core;
33 import net.pterodactylus.xdcc.core.event.DownloadFailed;
34 import net.pterodactylus.xdcc.core.event.DownloadFinished;
35 import net.pterodactylus.xdcc.core.event.DownloadStarted;
36 import net.pterodactylus.xdcc.core.event.GenericMessage;
37 import net.pterodactylus.xdcc.core.event.MessageReceived;
38 import net.pterodactylus.xdcc.data.Bot;
39 import net.pterodactylus.xdcc.data.Download;
40 import net.pterodactylus.xdcc.data.Pack;
42 import com.google.common.collect.Lists;
43 import com.google.common.collect.Sets;
44 import com.google.common.eventbus.Subscribe;
45 import com.google.common.primitives.Ints;
46 import com.google.common.util.concurrent.AbstractExecutionThreadService;
49 * Command interface for arbitrary {@link Reader}s.
51 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
53 public class CommandReader extends AbstractExecutionThreadService {
55 /** The core being controlled. */
56 private final Core core;
58 /** The reader to read commands from. */
59 private final BufferedReader reader;
61 /** The writer to write the results to. */
62 private final Writer writer;
65 * Creates a new command reader.
68 * The core being controlled
70 * The reader to read commands from
72 * The write to write results to
74 public CommandReader(Core core, Reader reader, Writer writer) {
76 this.reader = new BufferedReader(reader);
81 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
85 protected void run() throws Exception {
88 final List<Result> lastResult = Lists.newArrayList();
89 final List<Connection> lastConnections = Lists.newArrayList();
90 while ((line = reader.readLine()) != null) {
91 if (line.equals("")) {
94 String[] words = line.split(" +");
95 if (words[0].equalsIgnoreCase("search")) {
97 for (Bot bot : core.bots()) {
98 for (Pack pack : bot) {
100 for (int wordIndex = 1; wordIndex < words.length; ++wordIndex) {
101 if (words[wordIndex].startsWith("-") && pack.name().toLowerCase().contains(words[wordIndex].toLowerCase().substring(1))) {
105 if (!words[wordIndex].startsWith("-") && !pack.name().toLowerCase().contains(words[wordIndex].toLowerCase())) {
111 lastResult.add(new Result(bot, pack));
115 Collections.sort(lastResult);
117 for (Result result : lastResult) {
118 writeLine(String.format("[%d] %s (%s) from %s (#%s) on %s", counter++, result.pack().name(), result.pack().size(), result.bot().name(), result.pack().id(), result.bot().network().name()));
120 writeLine("End of Search.");
121 } else if (words[0].equalsIgnoreCase("dcc")) {
123 for (Download download : core.downloads()) {
124 DccReceiver dccReceiver = download.dccReceiver();
125 if (dccReceiver == null) {
126 /* download has not even started. */
127 writer.write(String.format("[%d] %s requested from %s (not started yet)\n", counter++, download.pack().name(), download.bot().name()));
130 writer.write(String.format("[%d] %s from %s (%s, ", counter++, dccReceiver.filename(), download.bot().name(), f(dccReceiver.size())));
131 if (dccReceiver.isRunning()) {
132 writer.write(String.format("%.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
134 if (dccReceiver.progress() >= dccReceiver.size()) {
135 writer.write(String.format("complete, %s", f(dccReceiver.overallRate())));
137 writer.write(String.format("aborted at %.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
140 writer.write("/s)\n");
142 writeLine("End of DCCs.");
143 } else if (words[0].equalsIgnoreCase("get")) {
144 Integer index = Ints.tryParse(words[1]);
145 if ((index != null) && (index < lastResult.size())) {
146 core.fetch(lastResult.get(index).bot(), lastResult.get(index).pack());
148 } else if (words[0].equalsIgnoreCase("stats")) {
149 int configuredChannelsCount = core.channels().size();
150 int joinedChannelsCount = core.joinedChannels().size();
151 int extraChannelsCount = core.extraChannels().size();
152 Collection<Bot> bots = core.bots();
153 Set<String> packNames = Sets.newHashSet();
155 for (Bot bot : bots) {
156 packsCount += bot.packs().size();
157 for (Pack pack : bot) {
158 packNames.add(pack.name());
162 writeLine(String.format("%d channels (%d joined, %d extra), %d bots offering %d packs (%d unique).", configuredChannelsCount, joinedChannelsCount, extraChannelsCount, bots.size(), packsCount, packNames.size()));
163 } else if (words[0].equalsIgnoreCase("connections")) {
164 lastConnections.clear();
166 for (Connection connection : core.connections()) {
167 lastConnections.add(connection);
168 writer.write(String.format("[%d] %s:%d, %s/s\n", counter++, connection.hostname(), connection.port(), f(connection.getInputRate())));
170 writeLine("End of connections.");
171 } else if (words[0].equalsIgnoreCase("disconnect")) {
172 Integer index = Ints.tryParse(words[1]);
173 if ((index != null) && (index < lastConnections.size())) {
174 core.closeConnection(lastConnections.get(index));
187 * Called when a download was started.
189 * @param downloadStarted
190 * The download started event
193 public void downloadStarted(DownloadStarted downloadStarted) {
194 Download download = downloadStarted.download();
196 writeLine(String.format("Download of %s (from %s, %s) has started.", download.pack().name(), download.bot().name(), download.bot().network().name()));
197 } catch (IOException ioe1) {
203 * Called when a download is finished.
205 * @param downloadFinished
206 * The download finished event
209 public void downloadFinished(DownloadFinished downloadFinished) {
210 Download download = downloadFinished.download();
212 writeLine(String.format("Download of %s (from %s, %s) has finished, at %s/s.", download.pack().name(), download.bot().name(), download.bot().network().name(), f(download.dccReceiver().overallRate())));
213 } catch (IOException ioe1) {
219 * Called when a download fails.
221 * @param downloadFailed
222 * The download failed event
225 public void downloadFailed(DownloadFailed downloadFailed) {
226 Download download = downloadFailed.download();
228 writeLine(String.format("Download of %s (from %s, %s) has failed at %.1f%% and %s/s.", download.filename(), download.bot().name(), download.bot().network().name(), download.dccReceiver().progress() * 100.0 / download.dccReceiver().size(), f(download.dccReceiver().overallRate())));
229 } catch (IOException ioe1) {
235 * Displays the received message on the console.
237 * @param messageReceived
238 * The message received event
241 public void messageReceived(MessageReceived messageReceived) {
243 writeLine(String.format("Message from %s: %s", messageReceived.source(), MessageCleaner.getDefaultInstance().clean(messageReceived.message())));
244 } catch (IOException e) {
250 * Writes a generic message to the console.
252 * @param genericMessage
253 * The generic message event
256 public void genericMessage(GenericMessage genericMessage) {
258 writeLine(genericMessage.message());
259 } catch (IOException ioe1) {
269 * Writes the given line followed by an LF to the {@link #writer}.
273 * @throws IOException
274 * if an I/O error occurs
276 private void writeLine(String line) throws IOException {
277 writer.write(line + "\n");
282 * Converts large numbers into a human-friendly format, by showing SI prefixes
283 * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
286 * The number to convert
287 * @return The converted number
289 private static String f(long number) {
290 if (number >= (1 << 30)) {
291 return String.format("%.1fG", number / (double) (1 << 30));
293 if (number >= (1 << 20)) {
294 return String.format("%.1fM", number / (double) (1 << 20));
296 if (number >= (1 << 10)) {
297 return String.format("%.1fK", number / (double) (1 << 10));
299 return String.format("%dB", number);
302 /** Container for result information. */
303 private static class Result implements Comparable<Result> {
305 /** The bot carrying the pack. */
306 private final Bot bot;
309 private final Pack pack;
312 * Creates a new result.
315 * The bot carrying the pack
319 private Result(Bot bot, Pack pack) {
329 * Returns the bot carrying the pack.
331 * @return The bot carrying the pack
347 // COMPARABLE METHODS
351 public int compareTo(Result result) {
352 return pack().name().compareToIgnoreCase(result.pack().name());