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