9cd2a12cc4b18d89ae07e6ee0da7cb14ddcfa80f
[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.Arrays;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Comparator;
28 import java.util.List;
29 import java.util.Set;
30 import java.util.regex.Pattern;
31
32 import net.pterodactylus.irc.Connection;
33 import net.pterodactylus.irc.DccReceiver;
34 import net.pterodactylus.irc.util.MessageCleaner;
35 import net.pterodactylus.xdcc.core.Core;
36 import net.pterodactylus.xdcc.core.event.DownloadFailed;
37 import net.pterodactylus.xdcc.core.event.DownloadFinished;
38 import net.pterodactylus.xdcc.core.event.DownloadStarted;
39 import net.pterodactylus.xdcc.core.event.GenericMessage;
40 import net.pterodactylus.xdcc.core.event.MessageReceived;
41 import net.pterodactylus.xdcc.data.Bot;
42 import net.pterodactylus.xdcc.data.Download;
43 import net.pterodactylus.xdcc.data.Pack;
44
45 import com.google.common.base.Predicate;
46 import com.google.common.collect.ComparisonChain;
47 import com.google.common.collect.Lists;
48 import com.google.common.collect.Sets;
49 import com.google.common.eventbus.Subscribe;
50 import com.google.common.primitives.Ints;
51 import com.google.common.util.concurrent.AbstractExecutionThreadService;
52
53 /**
54  * Command interface for arbitrary {@link Reader}s.
55  *
56  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
57  */
58 public class CommandReader extends AbstractExecutionThreadService {
59
60         /** The core being controlled. */
61         private final Core core;
62
63         /** The reader to read commands from. */
64         private final BufferedReader reader;
65
66         /** The writer to write the results to. */
67         private final Writer writer;
68
69         /**
70          * Creates a new command reader.
71          *
72          * @param core
73          *              The core being controlled
74          * @param reader
75          *              The reader to read commands from
76          * @param writer
77          *              The write to write results to
78          */
79         public CommandReader(Core core, Reader reader, Writer writer) {
80                 this.core = core;
81                 this.reader = new BufferedReader(reader);
82                 this.writer = writer;
83         }
84
85         //
86         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
87         //
88
89         @Override
90         protected void run() throws Exception {
91                 String lastLine = "";
92                 String line;
93                 final List<Result> lastResult = Lists.newArrayList();
94                 final List<Connection> lastConnections = Lists.newArrayList();
95                 while ((line = reader.readLine()) != null) {
96                         if (line.equals("")) {
97                                 line = lastLine;
98                         }
99                         String[] words = line.split(" +");
100                         if (words[0].equalsIgnoreCase("search")) {
101                                 lastResult.clear();
102                                 for (Bot bot : Lists.newArrayList(core.bots())) {
103                                         for (Pack pack : Lists.newArrayList(bot)) {
104                                                 boolean found = true;
105                                                 for (int wordIndex = 1; wordIndex < words.length; ++wordIndex) {
106                                                         if (words[wordIndex].startsWith("-") && pack.name().toLowerCase().contains(words[wordIndex].toLowerCase().substring(1))) {
107                                                                 found = false;
108                                                                 break;
109                                                         }
110                                                         if (!words[wordIndex].startsWith("-") && !pack.name().toLowerCase().contains(words[wordIndex].toLowerCase())) {
111                                                                 found = false;
112                                                                 break;
113                                                         }
114                                                 }
115                                                 if (found) {
116                                                         lastResult.add(new Result(bot, pack));
117                                                 }
118                                         }
119                                 }
120                                 Collections.sort(lastResult);
121                                 int counter = 0;
122                                 for (Result result : lastResult) {
123                                         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()));
124                                 }
125                                 writeLine("End of Search.");
126                         } else if (words[0].equalsIgnoreCase("dcc")) {
127                                 int counter = 0;
128                                 for (Download download : core.downloads()) {
129                                         DccReceiver dccReceiver = download.dccReceiver();
130                                         if (dccReceiver == null) {
131                                                 /* download has not even started. */
132                                                 writer.write(String.format("[%d] %s requested from %s (not started yet)\n", counter++, download.pack().name(), download.bot().name()));
133                                                 continue;
134                                         }
135                                         writer.write(String.format("[%d] %s from %s (%s, ", counter++, dccReceiver.filename(), download.bot().name(), f(dccReceiver.size())));
136                                         if (dccReceiver.isRunning()) {
137                                                 writer.write(String.format("%.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
138                                         } else {
139                                                 if (dccReceiver.progress() >= dccReceiver.size()) {
140                                                         writer.write(String.format("complete, %s", f(dccReceiver.overallRate())));
141                                                 } else {
142                                                         writer.write(String.format("aborted at %.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
143                                                 }
144                                         }
145                                         writer.write("/s)\n");
146                                 }
147                                 writeLine("End of DCCs.");
148                         } else if (words[0].equalsIgnoreCase("get")) {
149                                 Integer index = Ints.tryParse(words[1]);
150                                 if ((index != null) && (index < lastResult.size())) {
151                                         core.fetch(lastResult.get(index).bot(), lastResult.get(index).pack());
152                                 }
153                         } else if (words[0].equalsIgnoreCase("stats")) {
154                                 int configuredChannelsCount = core.channels().size();
155                                 int joinedChannelsCount = core.joinedChannels().size();
156                                 int extraChannelsCount = core.extraChannels().size();
157                                 Collection<Bot> bots = core.bots();
158                                 Set<String> packNames = Sets.newHashSet();
159                                 int packsCount = 0;
160                                 for (Bot bot : bots) {
161                                         packsCount += bot.packs().size();
162                                         for (Pack pack : bot) {
163                                                 packNames.add(pack.name());
164                                         }
165                                 }
166
167                                 writeLine(String.format("%d channels (%d joined, %d extra), %d bots offering %d packs (%d unique).", configuredChannelsCount, joinedChannelsCount, extraChannelsCount, bots.size(), packsCount, packNames.size()));
168                         } else if (words[0].equalsIgnoreCase("connections")) {
169                                 lastConnections.clear();
170                                 int counter = 0;
171                                 for (Connection connection : core.connections()) {
172                                         lastConnections.add(connection);
173                                         writer.write(String.format("[%d] %s:%d, %s/s\n", counter++, connection.hostname(), connection.port(), f(connection.getInputRate())));
174                                 }
175                                 writeLine("End of connections.");
176                         } else if (words[0].equalsIgnoreCase("disconnect")) {
177                                 if ((words.length == 1) || ("all".equals(words[1]))) {
178                                         for (Connection connection : lastConnections) {
179                                                 core.closeConnection(connection);
180                                         }
181                                 } else {
182                                         Integer index = Ints.tryParse(words[1]);
183                                         if ((index != null) && (index < lastConnections.size())) {
184                                                 core.closeConnection(lastConnections.get(index));
185                                         }
186                                 }
187                         }
188
189                         lastLine = line;
190                 }
191         }
192
193         //
194         // EVENT HANDLERS
195         //
196
197         /**
198          * Called when a download was started.
199          *
200          * @param downloadStarted
201          *              The download started event
202          */
203         @Subscribe
204         public void downloadStarted(DownloadStarted downloadStarted) {
205                 Download download = downloadStarted.download();
206                 try {
207                         writeLine(String.format("Download of %s (from %s, %s) has started.", download.pack().name(), download.bot().name(), download.bot().network().name()));
208                 } catch (IOException ioe1) {
209                         /* ignore. */
210                 }
211         }
212
213         /**
214          * Called when a download is finished.
215          *
216          * @param downloadFinished
217          *              The download finished event
218          */
219         @Subscribe
220         public void downloadFinished(DownloadFinished downloadFinished) {
221                 Download download = downloadFinished.download();
222                 try {
223                         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())));
224                 } catch (IOException ioe1) {
225                         /* ignore. */
226                 }
227         }
228
229         /**
230          * Called when a download fails.
231          *
232          * @param downloadFailed
233          *              The download failed event
234          */
235         @Subscribe
236         public void downloadFailed(DownloadFailed downloadFailed) {
237                 Download download = downloadFailed.download();
238                 try {
239                         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())));
240                 } catch (IOException ioe1) {
241                         /* ignore. */
242                 }
243         }
244
245         /**
246          * Displays the received message on the console.
247          *
248          * @param messageReceived
249          *              The message received event
250          */
251         @Subscribe
252         public void messageReceived(MessageReceived messageReceived) {
253                 try {
254                         writeLine(String.format("Message from %s: %s", messageReceived.source(), MessageCleaner.getDefaultInstance().clean(messageReceived.message())));
255                 } catch (IOException e) {
256                         /* ignore. */
257                 }
258         }
259
260         /**
261          * Writes a generic message to the console.
262          *
263          * @param genericMessage
264          *              The generic message event
265          */
266         @Subscribe
267         public void genericMessage(GenericMessage genericMessage) {
268                 try {
269                         writeLine(genericMessage.message());
270                 } catch (IOException ioe1) {
271                         /* ignore. */
272                 }
273         }
274
275         //
276         // PRIVATE METHODS
277         //
278
279         /**
280          * Writes the given line followed by an LF to the {@link #writer}.
281          *
282          * @param line
283          *              The line to write
284          * @throws IOException
285          *              if an I/O error occurs
286          */
287         private void writeLine(String line) throws IOException {
288                 writer.write(line + "\n");
289                 writer.flush();
290         }
291
292         /**
293          * Converts large numbers into a human-friendly format, by showing SI prefixes
294          * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
295          *
296          * @param number
297          *              The number to convert
298          * @return The converted number
299          */
300         private static String f(long number) {
301                 if (number >= (1 << 30)) {
302                         return String.format("%.1fG", number / (double) (1 << 30));
303                 }
304                 if (number >= (1 << 20)) {
305                         return String.format("%.1fM", number / (double) (1 << 20));
306                 }
307                 if (number >= (1 << 10)) {
308                         return String.format("%.1fK", number / (double) (1 << 10));
309                 }
310                 return String.format("%dB", number);
311         }
312
313         /** Container for result information. */
314         private static class Result implements Comparable<Result> {
315
316                 /** {@link Predicate} that matches {@link Result}s that contain an archive. */
317                 private static final Predicate<Result> isArchive = new Predicate<Result>() {
318
319                         /** All suffixes that are recognized as archives. */
320                         private final List<String> archiveSuffixes = Arrays.asList("rar", "tar", "zip", "tar.gz", "tar.bz2", "tar.lzma", "7z");
321
322                         @Override
323                         public boolean apply(Result result) {
324                                 for (String suffix : archiveSuffixes) {
325                                         if (result.pack().name().toLowerCase().endsWith(suffix)) {
326                                                 return true;
327                                         }
328                                 }
329                                 return false;
330                         }
331                 };
332
333                 /**
334                  * {@link Comparator} for {@link Result}s that sorts archives (as per {@link
335                  * #isArchive} to the back of the list.
336                  */
337                 private static final Comparator<Result> packArchiveComparator = new Comparator<Result>() {
338                         @Override
339                         public int compare(Result leftResult, Result rightResult) {
340                                 if (isArchive.apply(leftResult) && !isArchive.apply(rightResult)) {
341                                         return 1;
342                                 }
343                                 if (!isArchive.apply(leftResult) && isArchive.apply(rightResult)) {
344                                         return -1;
345                                 }
346                                 return 0;
347                         }
348                 };
349
350                 /**
351                  * {@link Comparator} for bot nicknames. It comprises different strategies:
352                  * one name pattern is preferred (and thus listed first), one pattern is
353                  * disliked (and thus listed last), the rest is sorted alphabetically.
354                  */
355                 private static final Comparator<Result> botNameComparator = new Comparator<Result>() {
356
357                         /** Regular expression pattern for preferred names. */
358                         private final Pattern preferredNames = Pattern.compile("(?i)[^\\w]EUR?[^\\w]");
359
360                         /** Regular expression pattern for disliked names. */
361                         private final Pattern dislikedNames = Pattern.compile("(?i)[^\\w]USA?[^\\w]");
362
363                         @Override
364                         public int compare(Result leftResult, Result rightResult) {
365                                 String leftBotName = leftResult.bot().name();
366                                 String rightBotName = rightResult.bot().name();
367                                 /* preferred names to the front! */
368                                 if (preferredNames.matcher(leftBotName).find() && !preferredNames.matcher(rightBotName).find()) {
369                                         return -1;
370                                 }
371                                 if (preferredNames.matcher(rightBotName).find() && !preferredNames.matcher(leftBotName).find()) {
372                                         return 1;
373                                 }
374                                 /* disliked names to the back. */
375                                 if (dislikedNames.matcher(leftBotName).find() && !dislikedNames.matcher(rightBotName).find()) {
376                                         return 1;
377                                 }
378                                 if (dislikedNames.matcher(rightBotName).find() && !dislikedNames.matcher(leftBotName).find()) {
379                                         return -1;
380                                 }
381                                 return 0;
382                         }
383                 };
384
385                 /**
386                  * {@link Comparator} for {@link Result}s that sorts them by the name of the
387                  * {@link Pack}.
388                  */
389                 private static final Comparator<Result> packNameComparator = new Comparator<Result>() {
390                         @Override
391                         public int compare(Result leftResult, Result rightResult) {
392                                 return leftResult.pack().name().compareToIgnoreCase(rightResult.pack().name());
393                         }
394                 };
395
396                 /** The bot carrying the pack. */
397                 private final Bot bot;
398
399                 /** The pack. */
400                 private final Pack pack;
401
402                 /**
403                  * Creates a new result.
404                  *
405                  * @param bot
406                  *              The bot carrying the pack
407                  * @param pack
408                  *              The pack
409                  */
410                 private Result(Bot bot, Pack pack) {
411                         this.bot = bot;
412                         this.pack = pack;
413                 }
414
415                 //
416                 // ACCESSORS
417                 //
418
419                 /**
420                  * Returns the bot carrying the pack.
421                  *
422                  * @return The bot carrying the pack
423                  */
424                 public Bot bot() {
425                         return bot;
426                 }
427
428                 /**
429                  * Returns the pack.
430                  *
431                  * @return The pack
432                  */
433                 public Pack pack() {
434                         return pack;
435                 }
436
437                 //
438                 // COMPARABLE METHODS
439                 //
440
441                 @Override
442                 public int compareTo(Result result) {
443                         return ComparisonChain.start()
444                                         .compare(this, result, packArchiveComparator)
445                                         .compare(this, result, botNameComparator)
446                                         .compare(this, result, packNameComparator).result();
447                 }
448
449         }
450
451 }