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