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