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 static com.google.common.collect.FluentIterable.from;
21 import static java.util.Arrays.asList;
22 import static net.pterodactylus.xdcc.ui.stdin.Ansi.bold;
23 import static net.pterodactylus.xdcc.ui.stdin.Ansi.green;
24 import static net.pterodactylus.xdcc.ui.stdin.Ansi.red;
25 import static net.pterodactylus.xdcc.ui.stdin.Command.TO_NAME;
27 import java.io.BufferedReader;
28 import java.io.IOException;
29 import java.io.Reader;
30 import java.io.Writer;
31 import java.util.Collection;
32 import java.util.List;
34 import net.pterodactylus.irc.util.MessageCleaner;
35 import net.pterodactylus.xdcc.core.Core;
36 import net.pterodactylus.xdcc.core.event.DownloadFailed;
37 import net.pterodactylus.xdcc.core.event.DownloadFinished;
38 import net.pterodactylus.xdcc.core.event.DownloadStarted;
39 import net.pterodactylus.xdcc.core.event.GenericMessage;
40 import net.pterodactylus.xdcc.core.event.MessageReceived;
41 import net.pterodactylus.xdcc.data.Download;
43 import com.google.common.base.Joiner;
44 import com.google.common.base.Optional;
45 import com.google.common.collect.ImmutableList;
46 import com.google.common.collect.ImmutableSet;
47 import com.google.common.eventbus.Subscribe;
48 import com.google.common.util.concurrent.AbstractExecutionThreadService;
51 * Command interface for arbitrary {@link Reader}s.
53 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
55 public class CommandReader extends AbstractExecutionThreadService {
57 /** The commands to process. */
58 private final Collection<Command> commands;
60 /** The reader to read commands from. */
61 private final BufferedReader reader;
63 /** The writer to write the results to. */
64 private final Writer writer;
65 private final DownloadFailures downloadFailures;
68 * Creates a new command reader.
71 * The core being controlled
73 * The reader to read commands from
75 * The write to write results to
77 public CommandReader(Core core, Reader reader, Writer writer, DownloadFailures downloadFailures) {
78 this.reader = new BufferedReader(reader);
80 this.downloadFailures = downloadFailures;
82 /* initialize commands. */
83 ImmutableList.Builder<Command> commandBuilder = ImmutableList.builder();
84 commandBuilder.add(new ListDownloadsCommand(core));
85 commandBuilder.add(new SearchCommand(core));
86 commandBuilder.add(new DownloadCommand(core));
87 commandBuilder.add(new StatsCommand(core));
88 commandBuilder.add(new ListConnectionsCommand(core));
89 commandBuilder.add(new AbortDownloadCommand(core));
90 commandBuilder.add(new DisconnectCommand(core));
91 commandBuilder.add(new FailedDownloadsCommand(downloadFailures));
92 commandBuilder.add(new RestartCommand(core, downloadFailures));
93 commandBuilder.add(new ResearchCommand(core));
94 commands = commandBuilder.build();
98 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
102 protected void run() throws Exception {
103 String lastLine = "";
105 net.pterodactylus.xdcc.ui.stdin.State state = new net.pterodactylus.xdcc.ui.stdin.State();
106 while ((line = reader.readLine()) != null) {
108 if (line.equals("")) {
111 String[] words = line.split(" +");
112 String commandName = words[0];
113 Collection<Command> eligibleCommands = findEligibleCommands(commandName);
114 if (eligibleCommands.isEmpty()) {
115 writeLine(String.format("Invalid command: %s, valid: %s.", commandName, Joiner.on(' ').join(from(commands).transform(TO_NAME))));
116 } else if (eligibleCommands.size() > 1) {
117 writeLine(String.format("Commands: %s.", Joiner.on(' ').join(from(eligibleCommands).transform(TO_NAME))));
119 Command command = eligibleCommands.iterator().next();
120 List<String> parameters = from(asList(words)).skip(1).toList();
121 state = command.execute(state, parameters, writer);
133 * Called when a download was started.
135 * @param downloadStarted
136 * The download started event
139 public void downloadStarted(DownloadStarted downloadStarted) {
140 Download download = downloadStarted.download();
142 writeLine(String.format("Download of %s (from %s, %s) has started.", bold(download.pack().name()), download.bot().name(), download.bot().network().name()));
143 } catch (IOException ioe1) {
149 * Called when a download is finished.
151 * @param downloadFinished
152 * The download finished event
155 public void downloadFinished(DownloadFinished downloadFinished) {
156 Download download = downloadFinished.download();
158 writeLine(green(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()))));
159 } catch (IOException ioe1) {
165 * Called when a download fails.
167 * @param downloadFailed
168 * The download failed event
171 public void downloadFailed(DownloadFailed downloadFailed) {
172 Download download = downloadFailed.download();
173 downloadFailures.addFailedDownload(download, System.currentTimeMillis());
175 writeLine(red(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()))));
176 } catch (IOException ioe1) {
182 * Displays the received message on the console.
184 * @param messageReceived
185 * The message received event
188 public void messageReceived(MessageReceived messageReceived) {
190 writeLine(String.format("Message from %s: %s", messageReceived.source(), MessageCleaner.getDefaultInstance().clean(messageReceived.message())));
191 } catch (IOException e) {
197 * Writes a generic message to the console.
199 * @param genericMessage
200 * The generic message event
203 public void genericMessage(GenericMessage genericMessage) {
205 writeLine(genericMessage.message());
206 } catch (IOException ioe1) {
215 private Collection<Command> findEligibleCommands(String name) {
216 ImmutableSet.Builder<Command> eligibleCommands = ImmutableSet.builder();
217 for (Command command : commands) {
218 if (command.getName().toLowerCase().startsWith(name.toLowerCase())) {
219 eligibleCommands.add(command);
221 for (String alias : command.getAliases()) {
222 if (alias.toLowerCase().startsWith(name.toLowerCase())) {
223 eligibleCommands.add(command);
227 return eligibleCommands.build();
231 * Writes the given line followed by an LF to the {@link #writer}.
235 * @throws IOException
236 * if an I/O error occurs
238 private void writeLine(String line) throws IOException {
239 writer.write(line + "\n");
244 * Converts large numbers into a human-friendly format, by showing SI prefixes
245 * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
248 * The number to convert
249 * @return The converted number
251 static String f(long number) {
252 if (number >= (1 << 30)) {
253 return String.format("%.1fG", number / (double) (1 << 30));
255 if (number >= (1 << 20)) {
256 return String.format("%.1fM", number / (double) (1 << 20));
258 if (number >= (1 << 10)) {
259 return String.format("%.1fK", number / (double) (1 << 10));
261 return String.format("%dB", number);
265 * Formats the given number of seconds into a more easily readable string.
268 * The number of seconds
269 * @return The formatted time, or “unknown” if the time is unknown
271 static String t(Optional<Long> seconds) {
272 if (!seconds.isPresent()) {
275 if (seconds.get() > 3600) {
276 return String.format("%02d:%02d:%02d", seconds.get() / 3600, (seconds.get() / 60) % 60, seconds.get() % 60);
278 return String.format("%02d:%02d", (seconds.get() / 60) % 60, seconds.get() % 60);