Show whether a download has already started.
[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 (Download download : core.downloads()) {
122                                         DccReceiver dccReceiver = download.dccReceiver();
123                                         if (dccReceiver == null) {
124                                                 /* download has not even started. */
125                                                 writer.write(String.format("[%d] %s requested from %s (not started yet)\n", counter++, download.pack().name(), download.bot().name()));
126                                                 continue;
127                                         }
128                                         writer.write(String.format("[%d] %s from %s (%s, ", counter++, dccReceiver.filename(), download.bot().name(), f(dccReceiver.size())));
129                                         if (dccReceiver.isRunning()) {
130                                                 writer.write(String.format("%.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
131                                         } else {
132                                                 if (dccReceiver.progress() >= dccReceiver.size()) {
133                                                         writer.write(String.format("complete, %s", f(dccReceiver.overallRate())));
134                                                 } else {
135                                                         writer.write(String.format("aborted at %.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
136                                                 }
137                                         }
138                                         writer.write("/s)\n");
139                                 }
140                                 writeLine("End of DCCs.");
141                         } else if (words[0].equalsIgnoreCase("get")) {
142                                 Integer index = Ints.tryParse(words[1]);
143                                 if ((index != null) && (index < lastResult.size())) {
144                                         core.fetch(lastResult.get(index).bot(), lastResult.get(index).pack());
145                                 }
146                         } else if (words[0].equalsIgnoreCase("stats")) {
147                                 int configuredChannelsCount = core.channels().size();
148                                 int joinedChannelsCount = core.joinedChannels().size();
149                                 int extraChannelsCount = core.extraChannels().size();
150                                 Collection<Bot> bots = core.bots();
151                                 Set<String> packNames = Sets.newHashSet();
152                                 int packsCount = 0;
153                                 for (Bot bot : bots) {
154                                         packsCount += bot.packs().size();
155                                         for (Pack pack : bot) {
156                                                 packNames.add(pack.name());
157                                         }
158                                 }
159
160                                 writeLine(String.format("%d channels (%d joined, %d extra), %d bots offering %d packs (%d unique).", configuredChannelsCount, joinedChannelsCount, extraChannelsCount, bots.size(), packsCount, packNames.size()));
161                         }
162
163                         lastLine = line;
164                 }
165         }
166
167         //
168         // EVENT HANDLERS
169         //
170
171         /**
172          * Called when a download was started.
173          *
174          * @param downloadStarted
175          *              The download started event
176          */
177         @Subscribe
178         public void downloadStarted(DownloadStarted downloadStarted) {
179                 Download download = downloadStarted.download();
180                 try {
181                         writeLine(String.format("Download of %s (from %s, %s) has started.", download.pack().name(), download.bot().name(), download.bot().network().name()));
182                 } catch (IOException ioe1) {
183                         /* ignore. */
184                 }
185         }
186
187         /**
188          * Called when a download is finished.
189          *
190          * @param downloadFinished
191          *              The download finished event
192          */
193         @Subscribe
194         public void downloadFinished(DownloadFinished downloadFinished) {
195                 Download download = downloadFinished.download();
196                 try {
197                         writeLine(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())));
198                 } catch (IOException ioe1) {
199                         /* ignore. */
200                 }
201         }
202
203         /**
204          * Called when a download fails.
205          *
206          * @param downloadFailed
207          *              The download failed event
208          */
209         @Subscribe
210         public void downloadFailed(DownloadFailed downloadFailed) {
211                 Download download = downloadFailed.download();
212                 try {
213                         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())));
214                 } catch (IOException ioe1) {
215                         /* ignore. */
216                 }
217         }
218
219         /**
220          * Displays the received message on the console.
221          *
222          * @param messageReceived
223          *              The message received event
224          */
225         @Subscribe
226         public void messageReceived(MessageReceived messageReceived) {
227                 try {
228                         writeLine(String.format("Message from %s: %s", messageReceived.source(), MessageCleaner.getDefaultInstance().clean(messageReceived.message())));
229                 } catch (IOException e) {
230                         /* ignore. */
231                 }
232         }
233
234         /**
235          * Writes a generic message to the console.
236          *
237          * @param genericMessage
238          *              The generic message event
239          */
240         @Subscribe
241         public void genericMessage(GenericMessage genericMessage) {
242                 try {
243                         writeLine(genericMessage.message());
244                 } catch (IOException ioe1) {
245                         /* ignore. */
246                 }
247         }
248
249         //
250         // PRIVATE METHODS
251         //
252
253         /**
254          * Writes the given line followed by an LF to the {@link #writer}.
255          *
256          * @param line
257          *              The line to write
258          * @throws IOException
259          *              if an I/O error occurs
260          */
261         private void writeLine(String line) throws IOException {
262                 writer.write(line + "\n");
263                 writer.flush();
264         }
265
266         /**
267          * Converts large numbers into a human-friendly format, by showing SI prefixes
268          * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
269          *
270          * @param number
271          *              The number to convert
272          * @return The converted number
273          */
274         private static String f(long number) {
275                 if (number >= (1 << 30)) {
276                         return String.format("%.1fG", number / (double) (1 << 30));
277                 }
278                 if (number >= (1 << 20)) {
279                         return String.format("%.1fM", number / (double) (1 << 20));
280                 }
281                 if (number >= (1 << 10)) {
282                         return String.format("%.1fK", number / (double) (1 << 10));
283                 }
284                 return String.format("%dB", number);
285         }
286
287         /** Container for result information. */
288         private static class Result implements Comparable<Result> {
289
290                 /** The bot carrying the pack. */
291                 private final Bot bot;
292
293                 /** The pack. */
294                 private final Pack pack;
295
296                 /**
297                  * Creates a new result.
298                  *
299                  * @param bot
300                  *              The bot carrying the pack
301                  * @param pack
302                  *              The pack
303                  */
304                 private Result(Bot bot, Pack pack) {
305                         this.bot = bot;
306                         this.pack = pack;
307                 }
308
309                 //
310                 // ACCESSORS
311                 //
312
313                 /**
314                  * Returns the bot carrying the pack.
315                  *
316                  * @return The bot carrying the pack
317                  */
318                 public Bot bot() {
319                         return bot;
320                 }
321
322                 /**
323                  * Returns the pack.
324                  *
325                  * @return The pack
326                  */
327                 public Pack pack() {
328                         return pack;
329                 }
330
331                 //
332                 // COMPARABLE METHODS
333                 //
334
335                 @Override
336                 public int compareTo(Result result) {
337                         return pack().name().compareToIgnoreCase(result.pack().name());
338                 }
339
340         }
341
342 }