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