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