2 * XdccDownloader - CommandReader.java - Copyright © 2013 David Roden
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.
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.
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/>.
18 package net.pterodactylus.xdcc.ui.stdin;
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;
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;
34 import java.util.regex.Pattern;
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;
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;
60 * Command interface for arbitrary {@link Reader}s.
62 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
64 public class CommandReader extends AbstractExecutionThreadService {
66 /** The core being controlled. */
67 private final Core core;
69 /** The reader to read commands from. */
70 private final BufferedReader reader;
72 /** The writer to write the results to. */
73 private final Writer writer;
76 * Creates a new command reader.
79 * The core being controlled
81 * The reader to read commands from
83 * The write to write results to
85 public CommandReader(Core core, Reader reader, Writer writer) {
87 this.reader = new BufferedReader(reader);
92 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
96 protected void run() throws Exception {
99 State state = new State();
100 while ((line = reader.readLine()) != null) {
101 if (line.equals("")) {
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))) {
115 if (!words[wordIndex].startsWith("-") && !pack.name().toLowerCase().contains(words[wordIndex].toLowerCase())) {
121 lastResult.add(new Result(bot, pack));
125 Collections.sort(lastResult);
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()));
130 writeLine("End of Search.");
131 state = state.setLastResults(lastResult);
132 } else if (words[0].equalsIgnoreCase("dcc")) {
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()));
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)));
146 if (dccReceiver.progress() >= dccReceiver.size()) {
147 writer.write(String.format("complete, %s/s", f(dccReceiver.overallRate())));
149 writer.write(String.format("aborted at %.1f%%, %s/s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
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());
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());
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();
173 for (Bot bot : bots) {
174 packsCount += bot.packs().size();
175 for (Pack pack : bot) {
176 packNames.add(pack.name());
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();
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())));
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);
196 Integer index = Ints.tryParse(words[1]);
197 if ((index != null) && (index < state.getLastConnections().size())) {
198 core.closeConnection(state.getLastConnections().get(index));
212 * Called when a download was started.
214 * @param downloadStarted
215 * The download started event
218 public void downloadStarted(DownloadStarted downloadStarted) {
219 Download download = downloadStarted.download();
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) {
228 * Called when a download is finished.
230 * @param downloadFinished
231 * The download finished event
234 public void downloadFinished(DownloadFinished downloadFinished) {
235 Download download = downloadFinished.download();
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) {
244 * Called when a download fails.
246 * @param downloadFailed
247 * The download failed event
250 public void downloadFailed(DownloadFailed downloadFailed) {
251 Download download = downloadFailed.download();
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) {
260 * Displays the received message on the console.
262 * @param messageReceived
263 * The message received event
266 public void messageReceived(MessageReceived messageReceived) {
268 writeLine(String.format("Message from %s: %s", messageReceived.source(), MessageCleaner.getDefaultInstance().clean(messageReceived.message())));
269 } catch (IOException e) {
275 * Writes a generic message to the console.
277 * @param genericMessage
278 * The generic message event
281 public void genericMessage(GenericMessage genericMessage) {
283 writeLine(genericMessage.message());
284 } catch (IOException ioe1) {
294 * Writes the given line followed by an LF to the {@link #writer}.
298 * @throws IOException
299 * if an I/O error occurs
301 private void writeLine(String line) throws IOException {
302 writer.write(line + "\n");
307 * Converts large numbers into a human-friendly format, by showing SI prefixes
308 * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
311 * The number to convert
312 * @return The converted number
314 private static String f(long number) {
315 if (number >= (1 << 30)) {
316 return String.format("%.1fG", number / (double) (1 << 30));
318 if (number >= (1 << 20)) {
319 return String.format("%.1fM", number / (double) (1 << 20));
321 if (number >= (1 << 10)) {
322 return String.format("%.1fK", number / (double) (1 << 10));
324 return String.format("%dB", number);
328 * Returns the estimated time left for the given transfer.
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
335 private static String getTimeLeft(DccReceiver dccReceiver) {
336 if ((dccReceiver.size() == -1) || (dccReceiver.currentRate() == 0)) {
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);
343 return String.format("%02d:%02d", (secondsLeft / 60) % 60, secondsLeft % 60);
346 /** Container for result information. */
347 private static class Result implements Comparable<Result> {
349 /** {@link Predicate} that matches {@link Result}s that contain an archive. */
350 private static final Predicate<Result> isArchive = new Predicate<Result>() {
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");
356 public boolean apply(Result result) {
357 for (String suffix : archiveSuffixes) {
358 if (result.pack().name().toLowerCase().endsWith(suffix)) {
367 * {@link Comparator} for {@link Result}s that sorts archives (as per {@link
368 * #isArchive} to the back of the list.
370 private static final Comparator<Result> packArchiveComparator = new Comparator<Result>() {
372 public int compare(Result leftResult, Result rightResult) {
373 if (isArchive.apply(leftResult) && !isArchive.apply(rightResult)) {
376 if (!isArchive.apply(leftResult) && isArchive.apply(rightResult)) {
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.
388 private static final Comparator<Result> botNameComparator = new Comparator<Result>() {
390 /** Regular expression pattern for preferred names. */
391 private final Pattern preferredNames = Pattern.compile("(?i)[^\\w]EUR?[^\\w]");
393 /** Regular expression pattern for disliked names. */
394 private final Pattern dislikedNames = Pattern.compile("(?i)[^\\w]USA?[^\\w]");
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()) {
404 if (preferredNames.matcher(rightBotName).find() && !preferredNames.matcher(leftBotName).find()) {
407 /* disliked names to the back. */
408 if (dislikedNames.matcher(leftBotName).find() && !dislikedNames.matcher(rightBotName).find()) {
411 if (dislikedNames.matcher(rightBotName).find() && !dislikedNames.matcher(leftBotName).find()) {
419 * {@link Comparator} for {@link Result}s that sorts them by the name of the
422 private static final Comparator<Result> packNameComparator = new Comparator<Result>() {
424 public int compare(Result leftResult, Result rightResult) {
425 return leftResult.pack().name().compareToIgnoreCase(rightResult.pack().name());
429 /** The bot carrying the pack. */
430 private final Bot bot;
433 private final Pack pack;
436 * Creates a new result.
439 * The bot carrying the pack
443 private Result(Bot bot, Pack pack) {
453 * Returns the bot carrying the pack.
455 * @return The bot carrying the pack
471 // COMPARABLE METHODS
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();
485 * Container for the current state of the command reader.
487 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
489 private static class State {
491 /** The last connections displayed. */
492 private final List<Connection> lastConnections;
494 /** The last results displayed. */
495 private final List<Result> lastResults;
497 /** The last downloads displayed. */
498 private final List<Download> lastDownloads;
500 /** Creates a new empty state. */
502 this(Lists.<Connection>newArrayList(), Lists.<Result>newArrayList(), Lists.<Download>newArrayList());
506 * Creates a new state.
508 * @param lastConnections
509 * The last connections
512 * @param lastDownloads
515 private State(List<Connection> lastConnections, List<Result> lastResults, List<Download> lastDownloads) {
516 this.lastConnections = lastConnections;
517 this.lastResults = lastResults;
518 this.lastDownloads = lastDownloads;
526 * Returns the last connections displayed.
528 * @return The last connections displayed
530 public List<Connection> getLastConnections() {
531 return lastConnections;
535 * Returns the last results displayed.
537 * @return The last results displayed
539 public List<Result> getLastResults() {
544 * Returns the last downloads displayed.
546 * @return The last downloads displayed
548 public List<Download> getLastDownloads() {
549 return lastDownloads;
557 * Returns a new state with the given last connections and the last downloads
558 * and results of this state.
560 * @param lastConnections
561 * The new last connections displayed
562 * @return The new state
564 public State setLastConnections(List<Connection> lastConnections) {
565 return new State(lastConnections, lastResults, lastDownloads);
569 * Returns a new state with the given last results and the last downloads and
570 * connections of this state.
573 * The new last results displayed
574 * @return The new state
576 public State setLastResults(List<Result> lastResults) {
577 return new State(lastConnections, lastResults, lastDownloads);
581 * Returns a new state with the given last downloads and the last connections
582 * and results of this state.
584 * @param lastDownloads
585 * The new last downloads displayed
586 * @return The new state
588 public State setLastDownloads(List<Download> lastDownloads) {
589 return new State(lastConnections, lastResults, lastDownloads);