Add comparator that uses the “isArchive” predicate.
[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.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;
51
52 /**
53  * Command interface for arbitrary {@link Reader}s.
54  *
55  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
56  */
57 public class CommandReader extends AbstractExecutionThreadService {
58
59         /** The core being controlled. */
60         private final Core core;
61
62         /** The reader to read commands from. */
63         private final BufferedReader reader;
64
65         /** The writer to write the results to. */
66         private final Writer writer;
67
68         /**
69          * Creates a new command reader.
70          *
71          * @param core
72          *              The core being controlled
73          * @param reader
74          *              The reader to read commands from
75          * @param writer
76          *              The write to write results to
77          */
78         public CommandReader(Core core, Reader reader, Writer writer) {
79                 this.core = core;
80                 this.reader = new BufferedReader(reader);
81                 this.writer = writer;
82         }
83
84         //
85         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
86         //
87
88         @Override
89         protected void run() throws Exception {
90                 String lastLine = "";
91                 String line;
92                 final List<Result> lastResult = Lists.newArrayList();
93                 final List<Connection> lastConnections = Lists.newArrayList();
94                 while ((line = reader.readLine()) != null) {
95                         if (line.equals("")) {
96                                 line = lastLine;
97                         }
98                         String[] words = line.split(" +");
99                         if (words[0].equalsIgnoreCase("search")) {
100                                 lastResult.clear();
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))) {
106                                                                 found = false;
107                                                                 break;
108                                                         }
109                                                         if (!words[wordIndex].startsWith("-") && !pack.name().toLowerCase().contains(words[wordIndex].toLowerCase())) {
110                                                                 found = false;
111                                                                 break;
112                                                         }
113                                                 }
114                                                 if (found) {
115                                                         lastResult.add(new Result(bot, pack));
116                                                 }
117                                         }
118                                 }
119                                 Collections.sort(lastResult);
120                                 int counter = 0;
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()));
123                                 }
124                                 writeLine("End of Search.");
125                         } else if (words[0].equalsIgnoreCase("dcc")) {
126                                 int counter = 0;
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()));
132                                                 continue;
133                                         }
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())));
137                                         } else {
138                                                 if (dccReceiver.progress() >= dccReceiver.size()) {
139                                                         writer.write(String.format("complete, %s", f(dccReceiver.overallRate())));
140                                                 } else {
141                                                         writer.write(String.format("aborted at %.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
142                                                 }
143                                         }
144                                         writer.write("/s)\n");
145                                 }
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());
151                                 }
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();
158                                 int packsCount = 0;
159                                 for (Bot bot : bots) {
160                                         packsCount += bot.packs().size();
161                                         for (Pack pack : bot) {
162                                                 packNames.add(pack.name());
163                                         }
164                                 }
165
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();
169                                 int counter = 0;
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())));
173                                 }
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);
179                                         }
180                                 } else {
181                                         Integer index = Ints.tryParse(words[1]);
182                                         if ((index != null) && (index < lastConnections.size())) {
183                                                 core.closeConnection(lastConnections.get(index));
184                                         }
185                                 }
186                         }
187
188                         lastLine = line;
189                 }
190         }
191
192         //
193         // EVENT HANDLERS
194         //
195
196         /**
197          * Called when a download was started.
198          *
199          * @param downloadStarted
200          *              The download started event
201          */
202         @Subscribe
203         public void downloadStarted(DownloadStarted downloadStarted) {
204                 Download download = downloadStarted.download();
205                 try {
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) {
208                         /* ignore. */
209                 }
210         }
211
212         /**
213          * Called when a download is finished.
214          *
215          * @param downloadFinished
216          *              The download finished event
217          */
218         @Subscribe
219         public void downloadFinished(DownloadFinished downloadFinished) {
220                 Download download = downloadFinished.download();
221                 try {
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) {
224                         /* ignore. */
225                 }
226         }
227
228         /**
229          * Called when a download fails.
230          *
231          * @param downloadFailed
232          *              The download failed event
233          */
234         @Subscribe
235         public void downloadFailed(DownloadFailed downloadFailed) {
236                 Download download = downloadFailed.download();
237                 try {
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) {
240                         /* ignore. */
241                 }
242         }
243
244         /**
245          * Displays the received message on the console.
246          *
247          * @param messageReceived
248          *              The message received event
249          */
250         @Subscribe
251         public void messageReceived(MessageReceived messageReceived) {
252                 try {
253                         writeLine(String.format("Message from %s: %s", messageReceived.source(), MessageCleaner.getDefaultInstance().clean(messageReceived.message())));
254                 } catch (IOException e) {
255                         /* ignore. */
256                 }
257         }
258
259         /**
260          * Writes a generic message to the console.
261          *
262          * @param genericMessage
263          *              The generic message event
264          */
265         @Subscribe
266         public void genericMessage(GenericMessage genericMessage) {
267                 try {
268                         writeLine(genericMessage.message());
269                 } catch (IOException ioe1) {
270                         /* ignore. */
271                 }
272         }
273
274         //
275         // PRIVATE METHODS
276         //
277
278         /**
279          * Writes the given line followed by an LF to the {@link #writer}.
280          *
281          * @param line
282          *              The line to write
283          * @throws IOException
284          *              if an I/O error occurs
285          */
286         private void writeLine(String line) throws IOException {
287                 writer.write(line + "\n");
288                 writer.flush();
289         }
290
291         /**
292          * Converts large numbers into a human-friendly format, by showing SI prefixes
293          * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
294          *
295          * @param number
296          *              The number to convert
297          * @return The converted number
298          */
299         private static String f(long number) {
300                 if (number >= (1 << 30)) {
301                         return String.format("%.1fG", number / (double) (1 << 30));
302                 }
303                 if (number >= (1 << 20)) {
304                         return String.format("%.1fM", number / (double) (1 << 20));
305                 }
306                 if (number >= (1 << 10)) {
307                         return String.format("%.1fK", number / (double) (1 << 10));
308                 }
309                 return String.format("%dB", number);
310         }
311
312         /** Container for result information. */
313         private static class Result implements Comparable<Result> {
314
315                 /** {@link Predicate} that matches {@link Result}s that contain an archive. */
316                 private static final Predicate<Result> isArchive = new Predicate<Result>() {
317
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");
320
321                         @Override
322                         public boolean apply(Result result) {
323                                 for (String suffix : archiveSuffixes) {
324                                         if (result.pack().name().toLowerCase().endsWith(suffix)) {
325                                                 return true;
326                                         }
327                                 }
328                                 return false;
329                         }
330                 };
331
332                 /**
333                  * {@link Comparator} for {@link Result}s that sorts archives (as per {@link
334                  * #isArchive} to the back of the list.
335                  */
336                 private static final Comparator<Result> packArchiveComparator = new Comparator<Result>() {
337                         @Override
338                         public int compare(Result leftResult, Result rightResult) {
339                                 if (isArchive.apply(leftResult) && !isArchive.apply(rightResult)) {
340                                         return 1;
341                                 }
342                                 if (!isArchive.apply(leftResult) && isArchive.apply(rightResult)) {
343                                         return -1;
344                                 }
345                                 return 0;
346                         }
347                 };
348
349                 /**
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.
353                  */
354                 private static final Comparator<String> botNameComparator = new Comparator<String>() {
355
356                         /** Regular expression pattern for preferred names. */
357                         private final Pattern preferredNames = Pattern.compile("(?i)[^\\w]EUR?[^\\w]");
358
359                         /** Regular expression pattern for disliked names. */
360                         private final Pattern dislikedNames = Pattern.compile("(?i)[^\\w]USA?[^\\w]");
361
362                         @Override
363                         public int compare(String leftBotName, String rightBotName) {
364                                 /* preferred names to the front! */
365                                 if (preferredNames.matcher(leftBotName).find() && !preferredNames.matcher(rightBotName).find()) {
366                                         return -1;
367                                 }
368                                 if (preferredNames.matcher(rightBotName).find() && !preferredNames.matcher(leftBotName).find()) {
369                                         return 1;
370                                 }
371                                 /* disliked names to the back. */
372                                 if (dislikedNames.matcher(leftBotName).find() && !dislikedNames.matcher(rightBotName).find()) {
373                                         return 1;
374                                 }
375                                 if (dislikedNames.matcher(rightBotName).find() && !dislikedNames.matcher(leftBotName).find()) {
376                                         return -1;
377                                 }
378                                 /* rest is sorted by name. */
379                                 return leftBotName.compareToIgnoreCase(rightBotName);
380                         }
381                 };
382
383                 /** The bot carrying the pack. */
384                 private final Bot bot;
385
386                 /** The pack. */
387                 private final Pack pack;
388
389                 /**
390                  * Creates a new result.
391                  *
392                  * @param bot
393                  *              The bot carrying the pack
394                  * @param pack
395                  *              The pack
396                  */
397                 private Result(Bot bot, Pack pack) {
398                         this.bot = bot;
399                         this.pack = pack;
400                 }
401
402                 //
403                 // ACCESSORS
404                 //
405
406                 /**
407                  * Returns the bot carrying the pack.
408                  *
409                  * @return The bot carrying the pack
410                  */
411                 public Bot bot() {
412                         return bot;
413                 }
414
415                 /**
416                  * Returns the pack.
417                  *
418                  * @return The pack
419                  */
420                 public Pack pack() {
421                         return pack;
422                 }
423
424                 //
425                 // COMPARABLE METHODS
426                 //
427
428                 @Override
429                 public int compareTo(Result result) {
430                         if (isArchive.apply(this) && !isArchive.apply(result)) {
431                                 return 1;
432                         }
433                         if (!isArchive.apply(this) && isArchive.apply(result)) {
434                                 return -1;
435                         }
436                         /* sort by bot name. */
437                         return botNameComparator.compare(bot().name(), result.bot().name());
438                 }
439
440         }
441
442 }