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.Command.TO_NAME;
24 import java.io.BufferedReader;
25 import java.io.IOException;
26 import java.io.Reader;
27 import java.io.Writer;
28 import java.util.Collection;
29 import java.util.List;
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.Download;
40 import com.google.common.base.Joiner;
41 import com.google.common.base.Optional;
42 import com.google.common.collect.ImmutableList;
43 import com.google.common.collect.ImmutableSet;
44 import com.google.common.eventbus.Subscribe;
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 commands to process. */
55 private final Collection<Command> commands;
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) {
74 this.reader = new BufferedReader(reader);
77 /* initialize commands. */
78 ImmutableList.Builder<Command> commandBuilder = ImmutableList.builder();
79 commandBuilder.add(new ListDownloadsCommand(core));
80 commandBuilder.add(new SearchCommand(core));
81 commandBuilder.add(new DownloadCommand(core));
82 commandBuilder.add(new StatsCommand(core));
83 commandBuilder.add(new ListConnectionsCommand(core));
84 commandBuilder.add(new AbortDownloadCommand(core));
85 commandBuilder.add(new DisconnectCommand(core));
86 commands = commandBuilder.build();
90 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
94 protected void run() throws Exception {
97 net.pterodactylus.xdcc.ui.stdin.State state = new net.pterodactylus.xdcc.ui.stdin.State();
98 while ((line = reader.readLine()) != null) {
100 if (line.equals("")) {
103 String[] words = line.split(" +");
104 String commandName = words[0];
105 Collection<Command> eligibleCommands = findEligibleCommands(commandName);
106 if (eligibleCommands.isEmpty()) {
107 writeLine(String.format("Invalid command: %s, valid: %s.", commandName, Joiner.on(' ').join(from(commands).transform(TO_NAME))));
108 } else if (eligibleCommands.size() > 1) {
109 writeLine(String.format("Commands: %s.", Joiner.on(' ').join(from(eligibleCommands).transform(TO_NAME))));
111 Command command = eligibleCommands.iterator().next();
112 List<String> parameters = from(asList(words)).skip(1).toList();
113 state = command.execute(state, parameters, writer);
125 * Called when a download was started.
127 * @param downloadStarted
128 * The download started event
131 public void downloadStarted(DownloadStarted downloadStarted) {
132 Download download = downloadStarted.download();
134 writeLine(String.format("Download of %s (from %s, %s) has started.", download.pack().name(), download.bot().name(), download.bot().network().name()));
135 } catch (IOException ioe1) {
141 * Called when a download is finished.
143 * @param downloadFinished
144 * The download finished event
147 public void downloadFinished(DownloadFinished downloadFinished) {
148 Download download = downloadFinished.download();
150 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())));
151 } catch (IOException ioe1) {
157 * Called when a download fails.
159 * @param downloadFailed
160 * The download failed event
163 public void downloadFailed(DownloadFailed downloadFailed) {
164 Download download = downloadFailed.download();
166 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())));
167 } catch (IOException ioe1) {
173 * Displays the received message on the console.
175 * @param messageReceived
176 * The message received event
179 public void messageReceived(MessageReceived messageReceived) {
181 writeLine(String.format("Message from %s: %s", messageReceived.source(), MessageCleaner.getDefaultInstance().clean(messageReceived.message())));
182 } catch (IOException e) {
188 * Writes a generic message to the console.
190 * @param genericMessage
191 * The generic message event
194 public void genericMessage(GenericMessage genericMessage) {
196 writeLine(genericMessage.message());
197 } catch (IOException ioe1) {
206 private Collection<Command> findEligibleCommands(String name) {
207 ImmutableSet.Builder<Command> eligibleCommands = ImmutableSet.builder();
208 for (Command command : commands) {
209 if (command.getName().toLowerCase().startsWith(name.toLowerCase())) {
210 eligibleCommands.add(command);
212 for (String alias : command.getAliases()) {
213 if (alias.toLowerCase().startsWith(name.toLowerCase())) {
214 eligibleCommands.add(command);
218 return eligibleCommands.build();
222 * Writes the given line followed by an LF to the {@link #writer}.
226 * @throws IOException
227 * if an I/O error occurs
229 private void writeLine(String line) throws IOException {
230 writer.write(line + "\n");
235 * Converts large numbers into a human-friendly format, by showing SI prefixes
236 * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
239 * The number to convert
240 * @return The converted number
242 static String f(long number) {
243 if (number >= (1 << 30)) {
244 return String.format("%.1fG", number / (double) (1 << 30));
246 if (number >= (1 << 20)) {
247 return String.format("%.1fM", number / (double) (1 << 20));
249 if (number >= (1 << 10)) {
250 return String.format("%.1fK", number / (double) (1 << 10));
252 return String.format("%dB", number);
256 * Formats the given number of seconds into a more easily readable string.
259 * The number of seconds
260 * @return The formatted time, or “unknown” if the time is unknown
262 static String t(Optional<Long> seconds) {
263 if (!seconds.isPresent()) {
266 if (seconds.get() > 3600) {
267 return String.format("%02d:%02d:%02d", seconds.get() / 3600, (seconds.get() / 60) % 60, seconds.get() % 60);
269 return String.format("%02d:%02d", (seconds.get() / 60) % 60, seconds.get() % 60);