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