381c519948e10b130fd0bb29bf221e2fc9e4cbd3
[xudocci.git] / src / main / java / net / pterodactylus / xdcc / ui / stdin / CommandReader.java
1 /*
2  * XdccDownloader - CommandReader.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.ui.stdin;
19
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;
26
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;
33
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;
42
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;
49
50 /**
51  * Command interface for arbitrary {@link Reader}s.
52  *
53  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
54  */
55 public class CommandReader extends AbstractExecutionThreadService {
56
57         /** The commands to process. */
58         private final Collection<Command> commands;
59
60         /** The reader to read commands from. */
61         private final BufferedReader reader;
62
63         /** The writer to write the results to. */
64         private final Writer writer;
65
66         /**
67          * Creates a new command reader.
68          *
69          * @param core
70          *              The core being controlled
71          * @param reader
72          *              The reader to read commands from
73          * @param writer
74          *              The write to write results to
75          */
76         public CommandReader(Core core, Reader reader, Writer writer) {
77                 this.reader = new BufferedReader(reader);
78                 this.writer = writer;
79
80                 /* initialize commands. */
81                 ImmutableList.Builder<Command> commandBuilder = ImmutableList.builder();
82                 commandBuilder.add(new ListDownloadsCommand(core));
83                 commandBuilder.add(new SearchCommand(core));
84                 commandBuilder.add(new DownloadCommand(core));
85                 commandBuilder.add(new StatsCommand(core));
86                 commandBuilder.add(new ListConnectionsCommand(core));
87                 commandBuilder.add(new AbortDownloadCommand(core));
88                 commandBuilder.add(new DisconnectCommand(core));
89                 commands = commandBuilder.build();
90         }
91
92         //
93         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
94         //
95
96         @Override
97         protected void run() throws Exception {
98                 String lastLine = "";
99                 String line;
100                 net.pterodactylus.xdcc.ui.stdin.State state = new net.pterodactylus.xdcc.ui.stdin.State();
101                 while ((line = reader.readLine()) != null) {
102                         line = line.trim();
103                         if (line.equals("")) {
104                                 line = lastLine;
105                         }
106                         String[] words = line.split(" +");
107                         String commandName = words[0];
108                         Collection<Command> eligibleCommands = findEligibleCommands(commandName);
109                         if (eligibleCommands.isEmpty()) {
110                                 writeLine(String.format("Invalid command: %s, valid: %s.", commandName, Joiner.on(' ').join(from(commands).transform(TO_NAME))));
111                         } else if (eligibleCommands.size() > 1) {
112                                 writeLine(String.format("Commands: %s.", Joiner.on(' ').join(from(eligibleCommands).transform(TO_NAME))));
113                         } else {
114                                 Command command = eligibleCommands.iterator().next();
115                                 List<String> parameters = from(asList(words)).skip(1).toList();
116                                 state = command.execute(state, parameters, writer);
117                         }
118
119                         lastLine = line;
120                 }
121         }
122
123         //
124         // EVENT HANDLERS
125         //
126
127         /**
128          * Called when a download was started.
129          *
130          * @param downloadStarted
131          *              The download started event
132          */
133         @Subscribe
134         public void downloadStarted(DownloadStarted downloadStarted) {
135                 Download download = downloadStarted.download();
136                 try {
137                         writeLine(String.format("Download of %s (from %s, %s) has started.", bold(download.pack().name()), download.bot().name(), download.bot().network().name()));
138                 } catch (IOException ioe1) {
139                         /* ignore. */
140                 }
141         }
142
143         /**
144          * Called when a download is finished.
145          *
146          * @param downloadFinished
147          *              The download finished event
148          */
149         @Subscribe
150         public void downloadFinished(DownloadFinished downloadFinished) {
151                 Download download = downloadFinished.download();
152                 try {
153                         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()))));
154                 } catch (IOException ioe1) {
155                         /* ignore. */
156                 }
157         }
158
159         /**
160          * Called when a download fails.
161          *
162          * @param downloadFailed
163          *              The download failed event
164          */
165         @Subscribe
166         public void downloadFailed(DownloadFailed downloadFailed) {
167                 Download download = downloadFailed.download();
168                 try {
169                         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()))));
170                 } catch (IOException ioe1) {
171                         /* ignore. */
172                 }
173         }
174
175         /**
176          * Displays the received message on the console.
177          *
178          * @param messageReceived
179          *              The message received event
180          */
181         @Subscribe
182         public void messageReceived(MessageReceived messageReceived) {
183                 try {
184                         writeLine(String.format("Message from %s: %s", messageReceived.source(), MessageCleaner.getDefaultInstance().clean(messageReceived.message())));
185                 } catch (IOException e) {
186                         /* ignore. */
187                 }
188         }
189
190         /**
191          * Writes a generic message to the console.
192          *
193          * @param genericMessage
194          *              The generic message event
195          */
196         @Subscribe
197         public void genericMessage(GenericMessage genericMessage) {
198                 try {
199                         writeLine(genericMessage.message());
200                 } catch (IOException ioe1) {
201                         /* ignore. */
202                 }
203         }
204
205         //
206         // PRIVATE METHODS
207         //
208
209         private Collection<Command> findEligibleCommands(String name) {
210                 ImmutableSet.Builder<Command> eligibleCommands = ImmutableSet.builder();
211                 for (Command command : commands) {
212                         if (command.getName().toLowerCase().startsWith(name.toLowerCase())) {
213                                 eligibleCommands.add(command);
214                         }
215                         for (String alias : command.getAliases()) {
216                                 if (alias.toLowerCase().startsWith(name.toLowerCase())) {
217                                         eligibleCommands.add(command);
218                                 }
219                         }
220                 }
221                 return eligibleCommands.build();
222         }
223
224         /**
225          * Writes the given line followed by an LF to the {@link #writer}.
226          *
227          * @param line
228          *              The line to write
229          * @throws IOException
230          *              if an I/O error occurs
231          */
232         private void writeLine(String line) throws IOException {
233                 writer.write(line + "\n");
234                 writer.flush();
235         }
236
237         /**
238          * Converts large numbers into a human-friendly format, by showing SI prefixes
239          * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
240          *
241          * @param number
242          *              The number to convert
243          * @return The converted number
244          */
245         static String f(long number) {
246                 if (number >= (1 << 30)) {
247                         return String.format("%.1fG", number / (double) (1 << 30));
248                 }
249                 if (number >= (1 << 20)) {
250                         return String.format("%.1fM", number / (double) (1 << 20));
251                 }
252                 if (number >= (1 << 10)) {
253                         return String.format("%.1fK", number / (double) (1 << 10));
254                 }
255                 return String.format("%dB", number);
256         }
257
258         /**
259          * Formats the given number of seconds into a more easily readable string.
260          *
261          * @param seconds
262          *              The number of seconds
263          * @return The formatted time, or “unknown” if the time is unknown
264          */
265         static String t(Optional<Long> seconds) {
266                 if (!seconds.isPresent()) {
267                         return "unknown";
268                 }
269                 if (seconds.get() > 3600) {
270                         return String.format("%02d:%02d:%02d", seconds.get() / 3600, (seconds.get() / 60) % 60, seconds.get() % 60);
271                 }
272                 return String.format("%02d:%02d", (seconds.get() / 60) % 60, seconds.get() % 60);
273         }
274
275 }