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.Lists;
47 import com.google.common.collect.Sets;
48 import com.google.common.eventbus.Subscribe;
49 import com.google.common.primitives.Ints;
50 import com.google.common.util.concurrent.AbstractExecutionThreadService;
53 * Command interface for arbitrary {@link Reader}s.
55 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
57 public class CommandReader extends AbstractExecutionThreadService {
59 /** The core being controlled. */
60 private final Core core;
62 /** The reader to read commands from. */
63 private final BufferedReader reader;
65 /** The writer to write the results to. */
66 private final Writer writer;
69 * Creates a new command reader.
72 * The core being controlled
74 * The reader to read commands from
76 * The write to write results to
78 public CommandReader(Core core, Reader reader, Writer writer) {
80 this.reader = new BufferedReader(reader);
85 // ABSTRACTEXECUTIONTHREADSERVICE METHODS
89 protected void run() throws Exception {
92 final List<Result> lastResult = Lists.newArrayList();
93 final List<Connection> lastConnections = Lists.newArrayList();
94 while ((line = reader.readLine()) != null) {
95 if (line.equals("")) {
98 String[] words = line.split(" +");
99 if (words[0].equalsIgnoreCase("search")) {
101 for (Bot bot : Lists.newArrayList(core.bots())) {
102 for (Pack pack : Lists.newArrayList(bot)) {
103 boolean found = true;
104 for (int wordIndex = 1; wordIndex < words.length; ++wordIndex) {
105 if (words[wordIndex].startsWith("-") && pack.name().toLowerCase().contains(words[wordIndex].toLowerCase().substring(1))) {
109 if (!words[wordIndex].startsWith("-") && !pack.name().toLowerCase().contains(words[wordIndex].toLowerCase())) {
115 lastResult.add(new Result(bot, pack));
119 Collections.sort(lastResult);
121 for (Result result : lastResult) {
122 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 writeLine("End of Search.");
125 } else if (words[0].equalsIgnoreCase("dcc")) {
127 for (Download download : core.downloads()) {
128 DccReceiver dccReceiver = download.dccReceiver();
129 if (dccReceiver == null) {
130 /* download has not even started. */
131 writer.write(String.format("[%d] %s requested from %s (not started yet)\n", counter++, download.pack().name(), download.bot().name()));
134 writer.write(String.format("[%d] %s from %s (%s, ", counter++, dccReceiver.filename(), download.bot().name(), f(dccReceiver.size())));
135 if (dccReceiver.isRunning()) {
136 writer.write(String.format("%.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
138 if (dccReceiver.progress() >= dccReceiver.size()) {
139 writer.write(String.format("complete, %s", f(dccReceiver.overallRate())));
141 writer.write(String.format("aborted at %.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
144 writer.write("/s)\n");
146 writeLine("End of DCCs.");
147 } else if (words[0].equalsIgnoreCase("get")) {
148 Integer index = Ints.tryParse(words[1]);
149 if ((index != null) && (index < lastResult.size())) {
150 core.fetch(lastResult.get(index).bot(), lastResult.get(index).pack());
152 } else if (words[0].equalsIgnoreCase("stats")) {
153 int configuredChannelsCount = core.channels().size();
154 int joinedChannelsCount = core.joinedChannels().size();
155 int extraChannelsCount = core.extraChannels().size();
156 Collection<Bot> bots = core.bots();
157 Set<String> packNames = Sets.newHashSet();
159 for (Bot bot : bots) {
160 packsCount += bot.packs().size();
161 for (Pack pack : bot) {
162 packNames.add(pack.name());
166 writeLine(String.format("%d channels (%d joined, %d extra), %d bots offering %d packs (%d unique).", configuredChannelsCount, joinedChannelsCount, extraChannelsCount, bots.size(), packsCount, packNames.size()));
167 } else if (words[0].equalsIgnoreCase("connections")) {
168 lastConnections.clear();
170 for (Connection connection : core.connections()) {
171 lastConnections.add(connection);
172 writer.write(String.format("[%d] %s:%d, %s/s\n", counter++, connection.hostname(), connection.port(), f(connection.getInputRate())));
174 writeLine("End of connections.");
175 } else if (words[0].equalsIgnoreCase("disconnect")) {
176 if ((words.length == 1) || ("all".equals(words[1]))) {
177 for (Connection connection : lastConnections) {
178 core.closeConnection(connection);
181 Integer index = Ints.tryParse(words[1]);
182 if ((index != null) && (index < lastConnections.size())) {
183 core.closeConnection(lastConnections.get(index));
197 * Called when a download was started.
199 * @param downloadStarted
200 * The download started event
203 public void downloadStarted(DownloadStarted downloadStarted) {
204 Download download = downloadStarted.download();
206 writeLine(String.format("Download of %s (from %s, %s) has started.", download.pack().name(), download.bot().name(), download.bot().network().name()));
207 } catch (IOException ioe1) {
213 * Called when a download is finished.
215 * @param downloadFinished
216 * The download finished event
219 public void downloadFinished(DownloadFinished downloadFinished) {
220 Download download = downloadFinished.download();
222 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())));
223 } catch (IOException ioe1) {
229 * Called when a download fails.
231 * @param downloadFailed
232 * The download failed event
235 public void downloadFailed(DownloadFailed downloadFailed) {
236 Download download = downloadFailed.download();
238 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())));
239 } catch (IOException ioe1) {
245 * Displays the received message on the console.
247 * @param messageReceived
248 * The message received event
251 public void messageReceived(MessageReceived messageReceived) {
253 writeLine(String.format("Message from %s: %s", messageReceived.source(), MessageCleaner.getDefaultInstance().clean(messageReceived.message())));
254 } catch (IOException e) {
260 * Writes a generic message to the console.
262 * @param genericMessage
263 * The generic message event
266 public void genericMessage(GenericMessage genericMessage) {
268 writeLine(genericMessage.message());
269 } catch (IOException ioe1) {
279 * Writes the given line followed by an LF to the {@link #writer}.
283 * @throws IOException
284 * if an I/O error occurs
286 private void writeLine(String line) throws IOException {
287 writer.write(line + "\n");
292 * Converts large numbers into a human-friendly format, by showing SI prefixes
293 * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
296 * The number to convert
297 * @return The converted number
299 private static String f(long number) {
300 if (number >= (1 << 30)) {
301 return String.format("%.1fG", number / (double) (1 << 30));
303 if (number >= (1 << 20)) {
304 return String.format("%.1fM", number / (double) (1 << 20));
306 if (number >= (1 << 10)) {
307 return String.format("%.1fK", number / (double) (1 << 10));
309 return String.format("%dB", number);
312 /** Container for result information. */
313 private static class Result implements Comparable<Result> {
315 /** {@link Predicate} that matches {@link Result}s that contain an archive. */
316 private static final Predicate<Result> isArchive = new Predicate<Result>() {
318 /** All suffixes that are recognized as archives. */
319 private final List<String> archiveSuffixes = Arrays.asList("rar", "tar", "zip", "tar.gz", "tar.bz2", "tar.lzma", "7z");
322 public boolean apply(Result result) {
323 for (String suffix : archiveSuffixes) {
324 if (result.pack().name().toLowerCase().endsWith(suffix)) {
333 * {@link Comparator} for {@link Result}s that sorts archives (as per {@link
334 * #isArchive} to the back of the list.
336 private static final Comparator<Result> packArchiveComparator = new Comparator<Result>() {
338 public int compare(Result leftResult, Result rightResult) {
339 if (isArchive.apply(leftResult) && !isArchive.apply(rightResult)) {
342 if (!isArchive.apply(leftResult) && isArchive.apply(rightResult)) {
350 * {@link Comparator} for bot nicknames. It comprises different strategies:
351 * one name pattern is preferred (and thus listed first), one pattern is
352 * disliked (and thus listed last), the rest is sorted alphabetically.
354 private static final Comparator<String> botNameComparator = new Comparator<String>() {
356 /** Regular expression pattern for preferred names. */
357 private final Pattern preferredNames = Pattern.compile("(?i)[^\\w]EUR?[^\\w]");
359 /** Regular expression pattern for disliked names. */
360 private final Pattern dislikedNames = Pattern.compile("(?i)[^\\w]USA?[^\\w]");
363 public int compare(String leftBotName, String rightBotName) {
364 /* preferred names to the front! */
365 if (preferredNames.matcher(leftBotName).find() && !preferredNames.matcher(rightBotName).find()) {
368 if (preferredNames.matcher(rightBotName).find() && !preferredNames.matcher(leftBotName).find()) {
371 /* disliked names to the back. */
372 if (dislikedNames.matcher(leftBotName).find() && !dislikedNames.matcher(rightBotName).find()) {
375 if (dislikedNames.matcher(rightBotName).find() && !dislikedNames.matcher(leftBotName).find()) {
378 /* rest is sorted by name. */
379 return leftBotName.compareToIgnoreCase(rightBotName);
383 /** The bot carrying the pack. */
384 private final Bot bot;
387 private final Pack pack;
390 * Creates a new result.
393 * The bot carrying the pack
397 private Result(Bot bot, Pack pack) {
407 * Returns the bot carrying the pack.
409 * @return The bot carrying the pack
425 // COMPARABLE METHODS
429 public int compareTo(Result result) {
430 if (isArchive.apply(this) && !isArchive.apply(result)) {
433 if (!isArchive.apply(this) && isArchive.apply(result)) {
436 /* sort by bot name. */
437 return botNameComparator.compare(bot().name(), result.bot().name());