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