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 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;
30 import java.util.regex.Pattern;
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;
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;
54 * Command interface for arbitrary {@link Reader}s.
56 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
58 public class CommandReader extends AbstractExecutionThreadService {
60 /** The core being controlled. */
61 private final Core core;
63 /** The reader to read commands from. */
64 private final BufferedReader reader;
66 /** The writer to write the results to. */
67 private final Writer writer;
70 * Creates a new command reader.
73 * The core being controlled
75 * The reader to read commands from
77 * The write to write results to
79 public CommandReader(Core core, Reader reader, Writer writer) {
81 this.reader = new BufferedReader(reader);
86 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
90 protected void run() throws Exception {
93 final List<Result> lastResult = Lists.newArrayList();
94 final List<Connection> lastConnections = Lists.newArrayList();
95 while ((line = reader.readLine()) != null) {
96 if (line.equals("")) {
99 String[] words = line.split(" +");
100 if (words[0].equalsIgnoreCase("search")) {
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))) {
110 if (!words[wordIndex].startsWith("-") && !pack.name().toLowerCase().contains(words[wordIndex].toLowerCase())) {
116 lastResult.add(new Result(bot, pack));
120 Collections.sort(lastResult);
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()));
125 writeLine("End of Search.");
126 } else if (words[0].equalsIgnoreCase("dcc")) {
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()));
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())));
139 if (dccReceiver.progress() >= dccReceiver.size()) {
140 writer.write(String.format("complete, %s", f(dccReceiver.overallRate())));
142 writer.write(String.format("aborted at %.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
145 writer.write("/s)\n");
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());
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();
160 for (Bot bot : bots) {
161 packsCount += bot.packs().size();
162 for (Pack pack : bot) {
163 packNames.add(pack.name());
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();
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())));
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);
182 Integer index = Ints.tryParse(words[1]);
183 if ((index != null) && (index < lastConnections.size())) {
184 core.closeConnection(lastConnections.get(index));
198 * Called when a download was started.
200 * @param downloadStarted
201 * The download started event
204 public void downloadStarted(DownloadStarted downloadStarted) {
205 Download download = downloadStarted.download();
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) {
214 * Called when a download is finished.
216 * @param downloadFinished
217 * The download finished event
220 public void downloadFinished(DownloadFinished downloadFinished) {
221 Download download = downloadFinished.download();
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) {
230 * Called when a download fails.
232 * @param downloadFailed
233 * The download failed event
236 public void downloadFailed(DownloadFailed downloadFailed) {
237 Download download = downloadFailed.download();
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) {
246 * Displays the received message on the console.
248 * @param messageReceived
249 * The message received event
252 public void messageReceived(MessageReceived messageReceived) {
254 writeLine(String.format("Message from %s: %s", messageReceived.source(), MessageCleaner.getDefaultInstance().clean(messageReceived.message())));
255 } catch (IOException e) {
261 * Writes a generic message to the console.
263 * @param genericMessage
264 * The generic message event
267 public void genericMessage(GenericMessage genericMessage) {
269 writeLine(genericMessage.message());
270 } catch (IOException ioe1) {
280 * Writes the given line followed by an LF to the {@link #writer}.
284 * @throws IOException
285 * if an I/O error occurs
287 private void writeLine(String line) throws IOException {
288 writer.write(line + "\n");
293 * Converts large numbers into a human-friendly format, by showing SI prefixes
294 * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
297 * The number to convert
298 * @return The converted number
300 private static String f(long number) {
301 if (number >= (1 << 30)) {
302 return String.format("%.1fG", number / (double) (1 << 30));
304 if (number >= (1 << 20)) {
305 return String.format("%.1fM", number / (double) (1 << 20));
307 if (number >= (1 << 10)) {
308 return String.format("%.1fK", number / (double) (1 << 10));
310 return String.format("%dB", number);
313 /** Container for result information. */
314 private static class Result implements Comparable<Result> {
316 /** {@link Predicate} that matches {@link Result}s that contain an archive. */
317 private static final Predicate<Result> isArchive = new Predicate<Result>() {
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");
323 public boolean apply(Result result) {
324 for (String suffix : archiveSuffixes) {
325 if (result.pack().name().toLowerCase().endsWith(suffix)) {
334 * {@link Comparator} for {@link Result}s that sorts archives (as per {@link
335 * #isArchive} to the back of the list.
337 private static final Comparator<Result> packArchiveComparator = new Comparator<Result>() {
339 public int compare(Result leftResult, Result rightResult) {
340 if (isArchive.apply(leftResult) && !isArchive.apply(rightResult)) {
343 if (!isArchive.apply(leftResult) && isArchive.apply(rightResult)) {
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.
355 private static final Comparator<Result> botNameComparator = new Comparator<Result>() {
357 /** Regular expression pattern for preferred names. */
358 private final Pattern preferredNames = Pattern.compile("(?i)[^\\w]EUR?[^\\w]");
360 /** Regular expression pattern for disliked names. */
361 private final Pattern dislikedNames = Pattern.compile("(?i)[^\\w]USA?[^\\w]");
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()) {
371 if (preferredNames.matcher(rightBotName).find() && !preferredNames.matcher(leftBotName).find()) {
374 /* disliked names to the back. */
375 if (dislikedNames.matcher(leftBotName).find() && !dislikedNames.matcher(rightBotName).find()) {
378 if (dislikedNames.matcher(rightBotName).find() && !dislikedNames.matcher(leftBotName).find()) {
386 * {@link Comparator} for {@link Result}s that sorts them by the name of the
389 private static final Comparator<Result> packNameComparator = new Comparator<Result>() {
391 public int compare(Result leftResult, Result rightResult) {
392 return leftResult.pack().name().compareToIgnoreCase(rightResult.pack().name());
396 /** The bot carrying the pack. */
397 private final Bot bot;
400 private final Pack pack;
403 * Creates a new result.
406 * The bot carrying the pack
410 private Result(Bot bot, Pack pack) {
420 * Returns the bot carrying the pack.
422 * @return The bot carrying the pack
438 // COMPARABLE METHODS
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();