Write generic messages to the console.
[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 java.io.BufferedReader;
21 import java.io.IOException;
22 import java.io.Reader;
23 import java.io.Writer;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.Set;
28
29 import net.pterodactylus.irc.DccReceiver;
30 import net.pterodactylus.irc.util.MessageCleaner;
31 import net.pterodactylus.xdcc.core.Core;
32 import net.pterodactylus.xdcc.core.event.DownloadFailed;
33 import net.pterodactylus.xdcc.core.event.DownloadFinished;
34 import net.pterodactylus.xdcc.core.event.DownloadStarted;
35 import net.pterodactylus.xdcc.core.event.GenericMessage;
36 import net.pterodactylus.xdcc.core.event.MessageReceived;
37 import net.pterodactylus.xdcc.data.Bot;
38 import net.pterodactylus.xdcc.data.Download;
39 import net.pterodactylus.xdcc.data.Pack;
40
41 import com.google.common.collect.Lists;
42 import com.google.common.collect.Sets;
43 import com.google.common.eventbus.Subscribe;
44 import com.google.common.primitives.Ints;
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 core being controlled. */
55         private final Core core;
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.core = core;
75                 this.reader = new BufferedReader(reader);
76                 this.writer = writer;
77         }
78
79         //
80         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
81         //
82
83         @Override
84         protected void run() throws Exception {
85                 String lastLine = "";
86                 String line;
87                 final List<Result> lastResult = Lists.newArrayList();
88                 while ((line = reader.readLine()) != null) {
89                         if (line.equals("")) {
90                                 line = lastLine;
91                         }
92                         String[] words = line.split(" +");
93                         if (words[0].equalsIgnoreCase("search")) {
94                                 lastResult.clear();
95                                 for (Bot bot : core.bots()) {
96                                         for (Pack pack : bot) {
97                                                 boolean found = true;
98                                                 for (int wordIndex = 1; wordIndex < words.length; ++wordIndex) {
99                                                         if (words[wordIndex].startsWith("-") && pack.name().toLowerCase().contains(words[wordIndex].toLowerCase().substring(1))) {
100                                                                 found = false;
101                                                                 break;
102                                                         }
103                                                         if (!words[wordIndex].startsWith("-") && !pack.name().toLowerCase().contains(words[wordIndex].toLowerCase())) {
104                                                                 found = false;
105                                                                 break;
106                                                         }
107                                                 }
108                                                 if (found) {
109                                                         lastResult.add(new Result(bot, pack));
110                                                 }
111                                         }
112                                 }
113                                 Collections.sort(lastResult);
114                                 int counter = 0;
115                                 for (Result result : lastResult) {
116                                         writeLine(String.format("[%d] %s (%s) from %s (#%s) on %s", counter++, result.pack().name(), result.pack().size(), result.bot().name(), result.pack().id(), result.bot().network().name()));
117                                 }
118                                 writeLine("End of Search.");
119                         } else if (words[0].equalsIgnoreCase("dcc")) {
120                                 int counter = 0;
121                                 for (DccReceiver dccReceiver : core.dccReceivers()) {
122                                         write(String.format("[%d] %s (%s, ", counter++, dccReceiver.filename(), dccReceiver.size()));
123                                         if (dccReceiver.isRunning()) {
124                                                 write(String.format("%.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
125                                         } else {
126                                                 if (dccReceiver.progress() >= dccReceiver.size()) {
127                                                         write(String.format("complete, %s", f(dccReceiver.overallRate())));
128                                                 } else {
129                                                         write(String.format("aborted at %.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
130                                                 }
131                                         }
132                                         write("/s)\n");
133                                 }
134                                 writeLine("End of DCCs.");
135                         } else if (words[0].equalsIgnoreCase("get")) {
136                                 Integer index = Ints.tryParse(words[1]);
137                                 if ((index != null) && (index < lastResult.size())) {
138                                         core.fetch(lastResult.get(index).bot(), lastResult.get(index).pack());
139                                 }
140                         } else if (words[0].equalsIgnoreCase("stats")) {
141                                 int configuredChannelsCount = core.channels().size();
142                                 int joinedChannelsCount = core.joinedChannels().size();
143                                 int extraChannelsCount = core.extraChannels().size();
144                                 Collection<Bot> bots = core.bots();
145                                 Set<String> packNames = Sets.newHashSet();
146                                 int packsCount = 0;
147                                 for (Bot bot : bots) {
148                                         packsCount += bot.packs().size();
149                                         for (Pack pack : bot) {
150                                                 packNames.add(pack.name());
151                                         }
152                                 }
153
154                                 writeLine(String.format("%d channels (%d joined, %d extra), %d bots offering %d packs (%d unique).", configuredChannelsCount, joinedChannelsCount, extraChannelsCount, bots.size(), packsCount, packNames.size()));
155                         }
156
157                         lastLine = line;
158                 }
159         }
160
161         //
162         // EVENT HANDLERS
163         //
164
165         /**
166          * Called when a download was started.
167          *
168          * @param downloadStarted
169          *              The download started event
170          */
171         @Subscribe
172         public void downloadStarted(DownloadStarted downloadStarted) {
173                 Download download = downloadStarted.download();
174                 try {
175                         writeLine(String.format("Download of %s (from %s, %s) has started.", download.filename(), download.bot().name(), download.bot().network().name()));
176                 } catch (IOException ioe1) {
177                         /* ignore. */
178                 }
179         }
180
181         /**
182          * Called when a download is finished.
183          *
184          * @param downloadFinished
185          *              The download finished event
186          */
187         @Subscribe
188         public void downloadFinished(DownloadFinished downloadFinished) {
189                 Download download = downloadFinished.download();
190                 try {
191                         writeLine(String.format("Download of %s (from %s, %s) has finished, at %s/s.", download.filename(), download.bot().name(), download.bot().network().name(), f(download.dccReceiver().overallRate())));
192                 } catch (IOException ioe1) {
193                         /* ignore. */
194                 }
195         }
196
197         /**
198          * Called when a download fails.
199          *
200          * @param downloadFailed
201          *              The download failed event
202          */
203         @Subscribe
204         public void downloadFailed(DownloadFailed downloadFailed) {
205                 Download download = downloadFailed.download();
206                 try {
207                         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())));
208                 } catch (IOException ioe1) {
209                         /* ignore. */
210                 }
211         }
212
213         /**
214          * Displays the received message on the console.
215          *
216          * @param messageReceived
217          *              The message received event
218          */
219         @Subscribe
220         public void messageReceived(MessageReceived messageReceived) {
221                 try {
222                         writeLine(String.format("Message from %s: %s", messageReceived.source(), MessageCleaner.getDefaultInstance().clean(messageReceived.message())));
223                 } catch (IOException e) {
224                         /* ignore. */
225                 }
226         }
227
228         /**
229          * Writes a generic message to the console.
230          *
231          * @param genericMessage
232          *              The generic message event
233          */
234         @Subscribe
235         public void genericMessage(GenericMessage genericMessage) {
236                 try {
237                         writeLine(genericMessage.message());
238                 } catch (IOException ioe1) {
239                         /* ignore. */
240                 }
241         }
242
243         //
244         // PRIVATE METHODS
245         //
246
247         /**
248          * Writes the given text to the {@link #writer}.
249          *
250          * @param text
251          *              The text to write
252          * @throws IOException
253          *              if an I/O error occurs
254          */
255         private void write(String text) throws IOException {
256                 writer.write(text);
257                 writer.flush();
258         }
259
260         /**
261          * Writes the given line followed by an LF to the {@link #writer}.
262          *
263          * @param line
264          *              The line to write
265          * @throws IOException
266          *              if an I/O error occurs
267          */
268         private void writeLine(String line) throws IOException {
269                 writer.write(line + "\n");
270                 writer.flush();
271         }
272
273         /**
274          * Converts large numbers into a human-friendly format, by showing SI prefixes
275          * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
276          *
277          * @param number
278          *              The number to convert
279          * @return The converted number
280          */
281         private static String f(long number) {
282                 if (number >= (1 << 30)) {
283                         return String.format("%.1fG", number / (double) (1 << 30));
284                 }
285                 if (number >= (1 << 20)) {
286                         return String.format("%.1fM", number / (double) (1 << 20));
287                 }
288                 if (number >= (1 << 10)) {
289                         return String.format("%.1fK", number / (double) (1 << 10));
290                 }
291                 return String.format("%dB", number);
292         }
293
294         /** Container for result information. */
295         private static class Result implements Comparable<Result> {
296
297                 /** The bot carrying the pack. */
298                 private final Bot bot;
299
300                 /** The pack. */
301                 private final Pack pack;
302
303                 /**
304                  * Creates a new result.
305                  *
306                  * @param bot
307                  *              The bot carrying the pack
308                  * @param pack
309                  *              The pack
310                  */
311                 private Result(Bot bot, Pack pack) {
312                         this.bot = bot;
313                         this.pack = pack;
314                 }
315
316                 //
317                 // ACCESSORS
318                 //
319
320                 /**
321                  * Returns the bot carrying the pack.
322                  *
323                  * @return The bot carrying the pack
324                  */
325                 public Bot bot() {
326                         return bot;
327                 }
328
329                 /**
330                  * Returns the pack.
331                  *
332                  * @return The pack
333                  */
334                 public Pack pack() {
335                         return pack;
336                 }
337
338                 //
339                 // COMPARABLE METHODS
340                 //
341
342                 @Override
343                 public int compareTo(Result result) {
344                         return pack().name().compareToIgnoreCase(result.pack().name());
345                 }
346
347         }
348
349 }