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.DccReceiver;
30 import net.pterodactylus.irc.util.MessageCleaner;
31 import net.pterodactylus.xdcc.core.Core;
32 import net.pterodactylus.xdcc.core.event.DownloadFailed;
33 import net.pterodactylus.xdcc.core.event.DownloadFinished;
34 import net.pterodactylus.xdcc.core.event.DownloadStarted;
35 import net.pterodactylus.xdcc.core.event.GenericMessage;
36 import net.pterodactylus.xdcc.core.event.MessageReceived;
37 import net.pterodactylus.xdcc.data.Bot;
38 import net.pterodactylus.xdcc.data.Download;
39 import net.pterodactylus.xdcc.data.Pack;
41 import com.google.common.collect.Lists;
42 import com.google.common.collect.Sets;
43 import com.google.common.eventbus.Subscribe;
44 import com.google.common.primitives.Ints;
45 import com.google.common.util.concurrent.AbstractExecutionThreadService;
48 * Command interface for arbitrary {@link Reader}s.
50 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
52 public class CommandReader extends AbstractExecutionThreadService {
54 /** The core being controlled. */
55 private final Core core;
57 /** The reader to read commands from. */
58 private final BufferedReader reader;
60 /** The writer to write the results to. */
61 private final Writer writer;
64 * Creates a new command reader.
67 * The core being controlled
69 * The reader to read commands from
71 * The write to write results to
73 public CommandReader(Core core, Reader reader, Writer writer) {
75 this.reader = new BufferedReader(reader);
80 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
84 protected void run() throws Exception {
87 final List<Result> lastResult = Lists.newArrayList();
88 while ((line = reader.readLine()) != null) {
89 if (line.equals("")) {
92 String[] words = line.split(" +");
93 if (words[0].equalsIgnoreCase("search")) {
95 for (Bot bot : core.bots()) {
96 for (Pack pack : bot) {
98 for (int wordIndex = 1; wordIndex < words.length; ++wordIndex) {
99 if (words[wordIndex].startsWith("-") && pack.name().toLowerCase().contains(words[wordIndex].toLowerCase().substring(1))) {
103 if (!words[wordIndex].startsWith("-") && !pack.name().toLowerCase().contains(words[wordIndex].toLowerCase())) {
109 lastResult.add(new Result(bot, pack));
113 Collections.sort(lastResult);
115 for (Result result : lastResult) {
116 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()));
118 writeLine("End of Search.");
119 } else if (words[0].equalsIgnoreCase("dcc")) {
121 for (Download download : core.downloads()) {
122 DccReceiver dccReceiver = download.dccReceiver();
123 if (dccReceiver == null) {
124 /* download has not even started. */
125 writer.write(String.format("[%d] %s requested from %s (not started yet)\n", counter++, download.pack().name(), download.bot().name()));
128 writer.write(String.format("[%d] %s from %s (%s, ", counter++, dccReceiver.filename(), download.bot().name(), f(dccReceiver.size())));
129 if (dccReceiver.isRunning()) {
130 writer.write(String.format("%.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
132 if (dccReceiver.progress() >= dccReceiver.size()) {
133 writer.write(String.format("complete, %s", f(dccReceiver.overallRate())));
135 writer.write(String.format("aborted at %.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
138 writer.write("/s)\n");
140 writeLine("End of DCCs.");
141 } else if (words[0].equalsIgnoreCase("get")) {
142 Integer index = Ints.tryParse(words[1]);
143 if ((index != null) && (index < lastResult.size())) {
144 core.fetch(lastResult.get(index).bot(), lastResult.get(index).pack());
146 } else if (words[0].equalsIgnoreCase("stats")) {
147 int configuredChannelsCount = core.channels().size();
148 int joinedChannelsCount = core.joinedChannels().size();
149 int extraChannelsCount = core.extraChannels().size();
150 Collection<Bot> bots = core.bots();
151 Set<String> packNames = Sets.newHashSet();
153 for (Bot bot : bots) {
154 packsCount += bot.packs().size();
155 for (Pack pack : bot) {
156 packNames.add(pack.name());
160 writeLine(String.format("%d channels (%d joined, %d extra), %d bots offering %d packs (%d unique).", configuredChannelsCount, joinedChannelsCount, extraChannelsCount, bots.size(), packsCount, packNames.size()));
172 * Called when a download was started.
174 * @param downloadStarted
175 * The download started event
178 public void downloadStarted(DownloadStarted downloadStarted) {
179 Download download = downloadStarted.download();
181 writeLine(String.format("Download of %s (from %s, %s) has started.", download.pack().name(), download.bot().name(), download.bot().network().name()));
182 } catch (IOException ioe1) {
188 * Called when a download is finished.
190 * @param downloadFinished
191 * The download finished event
194 public void downloadFinished(DownloadFinished downloadFinished) {
195 Download download = downloadFinished.download();
197 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())));
198 } catch (IOException ioe1) {
204 * Called when a download fails.
206 * @param downloadFailed
207 * The download failed event
210 public void downloadFailed(DownloadFailed downloadFailed) {
211 Download download = downloadFailed.download();
213 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())));
214 } catch (IOException ioe1) {
220 * Displays the received message on the console.
222 * @param messageReceived
223 * The message received event
226 public void messageReceived(MessageReceived messageReceived) {
228 writeLine(String.format("Message from %s: %s", messageReceived.source(), MessageCleaner.getDefaultInstance().clean(messageReceived.message())));
229 } catch (IOException e) {
235 * Writes a generic message to the console.
237 * @param genericMessage
238 * The generic message event
241 public void genericMessage(GenericMessage genericMessage) {
243 writeLine(genericMessage.message());
244 } catch (IOException ioe1) {
254 * Writes the given line followed by an LF to the {@link #writer}.
258 * @throws IOException
259 * if an I/O error occurs
261 private void writeLine(String line) throws IOException {
262 writer.write(line + "\n");
267 * Converts large numbers into a human-friendly format, by showing SI prefixes
268 * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
271 * The number to convert
272 * @return The converted number
274 private static String f(long number) {
275 if (number >= (1 << 30)) {
276 return String.format("%.1fG", number / (double) (1 << 30));
278 if (number >= (1 << 20)) {
279 return String.format("%.1fM", number / (double) (1 << 20));
281 if (number >= (1 << 10)) {
282 return String.format("%.1fK", number / (double) (1 << 10));
284 return String.format("%dB", number);
287 /** Container for result information. */
288 private static class Result implements Comparable<Result> {
290 /** The bot carrying the pack. */
291 private final Bot bot;
294 private final Pack pack;
297 * Creates a new result.
300 * The bot carrying the pack
304 private Result(Bot bot, Pack pack) {
314 * Returns the bot carrying the pack.
316 * @return The bot carrying the pack
332 // COMPARABLE METHODS
336 public int compareTo(Result result) {
337 return pack().name().compareToIgnoreCase(result.pack().name());