b77ac2cc72279b9e3e6f1ab391cb73435437e3dd
[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                                         writer.write(String.format("[%d] %s (%s) from %s (#%s) on %s\n", counter++, result.pack().name(), result.pack().size(), result.bot().name(), result.pack().id(), result.bot().network().name()));
114                                 }
115                                 writer.write("End of Search.\n");
116                         } else if (words[0].equalsIgnoreCase("dcc")) {
117                                 int counter = 0;
118                                 for (DccReceiver dccReceiver : core.dccReceivers()) {
119                                         writer.write(String.format("[%d] %s (%s, ", counter++, dccReceiver.filename(), dccReceiver.size()));
120                                         if (dccReceiver.isRunning()) {
121                                                 writer.write(String.format("%.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
122                                         } else {
123                                                 if (dccReceiver.progress() >= dccReceiver.size()) {
124                                                         writer.write(String.format("complete, %s", f(dccReceiver.overallRate())));
125                                                 } else {
126                                                         writer.write(String.format("aborted at %.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
127                                                 }
128                                         }
129                                         writer.write("/s)\n");
130                                 }
131                                 writer.write("End of DCCs.\n");
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                                 writer.write(String.format("%d channels (%d joined, %d extra), %d bots offering %d packs (%d unique).\n", configuredChannelsCount, joinedChannelsCount, extraChannelsCount, bots.size(), packsCount, packNames.size()));
152                         }
153
154                         lastLine = line;
155                         writer.flush();
156                 }
157         }
158
159         //
160         // EVENT HANDLERS
161         //
162
163         /**
164          * Called when a download was started.
165          *
166          * @param downloadStarted
167          *              The download started event
168          */
169         @Subscribe
170         public void downloadStarted(DownloadStarted downloadStarted) {
171                 Download download = downloadStarted.download();
172                 try {
173                         writer.write(String.format("Download of %s (from %s, %s) has started.\n", download.filename(), download.bot().name(), download.bot().network().name()));
174                         writer.flush();
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                         writer.write(String.format("Download of %s (from %s, %s) has finished, at %s/s.\n", download.filename(), download.bot().name(), download.bot().network().name(), f(download.dccReceiver().overallRate())));
191                         writer.flush();
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                         writer.write(String.format("Download of %s (from %s, %s) has failed at %.1f%% and %s/s.\n", download.filename(), download.bot().name(), download.bot().network().name(), download.dccReceiver().progress() * 100.0 / download.dccReceiver().size(), f(download.dccReceiver().overallRate())));
208                         writer.flush();
209                 } catch (IOException ioe1) {
210                         /* ignore. */
211                 }
212         }
213
214         //
215         // PRIVATE METHODS
216         //
217
218         /**
219          * Converts large numbers into a human-friendly format, by showing SI prefixes
220          * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
221          *
222          * @param number
223          *              The number to convert
224          * @return The converted number
225          */
226         private static String f(long number) {
227                 if (number >= (1 << 30)) {
228                         return String.format("%.1fG", number / (double) (1 << 30));
229                 }
230                 if (number >= (1 << 20)) {
231                         return String.format("%.1fM", number / (double) (1 << 20));
232                 }
233                 if (number >= (1 << 10)) {
234                         return String.format("%.1fK", number / (double) (1 << 10));
235                 }
236                 return String.format("%dB", number);
237         }
238
239         /** Container for result information. */
240         private static class Result implements Comparable<Result> {
241
242                 /** The bot carrying the pack. */
243                 private final Bot bot;
244
245                 /** The pack. */
246                 private final Pack pack;
247
248                 /**
249                  * Creates a new result.
250                  *
251                  * @param bot
252                  *              The bot carrying the pack
253                  * @param pack
254                  *              The pack
255                  */
256                 private Result(Bot bot, Pack pack) {
257                         this.bot = bot;
258                         this.pack = pack;
259                 }
260
261                 //
262                 // ACCESSORS
263                 //
264
265                 /**
266                  * Returns the bot carrying the pack.
267                  *
268                  * @return The bot carrying the pack
269                  */
270                 public Bot bot() {
271                         return bot;
272                 }
273
274                 /**
275                  * Returns the pack.
276                  *
277                  * @return The pack
278                  */
279                 public Pack pack() {
280                         return pack;
281                 }
282
283                 //
284                 // COMPARABLE METHODS
285                 //
286
287                 @Override
288                 public int compareTo(Result result) {
289                         return pack().name().compareToIgnoreCase(result.pack().name());
290                 }
291
292         }
293
294 }