Add possibility to disconnect all connections at once.
[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.Collection;
25 import java.util.Collections;
26 import java.util.List;
27 import java.util.Set;
28
29 import net.pterodactylus.irc.Connection;
30 import net.pterodactylus.irc.DccReceiver;
31 import net.pterodactylus.irc.util.MessageCleaner;
32 import net.pterodactylus.xdcc.core.Core;
33 import net.pterodactylus.xdcc.core.event.DownloadFailed;
34 import net.pterodactylus.xdcc.core.event.DownloadFinished;
35 import net.pterodactylus.xdcc.core.event.DownloadStarted;
36 import net.pterodactylus.xdcc.core.event.GenericMessage;
37 import net.pterodactylus.xdcc.core.event.MessageReceived;
38 import net.pterodactylus.xdcc.data.Bot;
39 import net.pterodactylus.xdcc.data.Download;
40 import net.pterodactylus.xdcc.data.Pack;
41
42 import com.google.common.collect.Lists;
43 import com.google.common.collect.Sets;
44 import com.google.common.eventbus.Subscribe;
45 import com.google.common.primitives.Ints;
46 import com.google.common.util.concurrent.AbstractExecutionThreadService;
47
48 /**
49  * Command interface for arbitrary {@link Reader}s.
50  *
51  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
52  */
53 public class CommandReader extends AbstractExecutionThreadService {
54
55         /** The core being controlled. */
56         private final Core core;
57
58         /** The reader to read commands from. */
59         private final BufferedReader reader;
60
61         /** The writer to write the results to. */
62         private final Writer writer;
63
64         /**
65          * Creates a new command reader.
66          *
67          * @param core
68          *              The core being controlled
69          * @param reader
70          *              The reader to read commands from
71          * @param writer
72          *              The write to write results to
73          */
74         public CommandReader(Core core, Reader reader, Writer writer) {
75                 this.core = core;
76                 this.reader = new BufferedReader(reader);
77                 this.writer = writer;
78         }
79
80         //
81         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
82         //
83
84         @Override
85         protected void run() throws Exception {
86                 String lastLine = "";
87                 String line;
88                 final List<Result> lastResult = Lists.newArrayList();
89                 final List<Connection> lastConnections = Lists.newArrayList();
90                 while ((line = reader.readLine()) != null) {
91                         if (line.equals("")) {
92                                 line = lastLine;
93                         }
94                         String[] words = line.split(" +");
95                         if (words[0].equalsIgnoreCase("search")) {
96                                 lastResult.clear();
97                                 for (Bot bot : Lists.newArrayList(core.bots())) {
98                                         for (Pack pack : Lists.newArrayList(bot)) {
99                                                 boolean found = true;
100                                                 for (int wordIndex = 1; wordIndex < words.length; ++wordIndex) {
101                                                         if (words[wordIndex].startsWith("-") && pack.name().toLowerCase().contains(words[wordIndex].toLowerCase().substring(1))) {
102                                                                 found = false;
103                                                                 break;
104                                                         }
105                                                         if (!words[wordIndex].startsWith("-") && !pack.name().toLowerCase().contains(words[wordIndex].toLowerCase())) {
106                                                                 found = false;
107                                                                 break;
108                                                         }
109                                                 }
110                                                 if (found) {
111                                                         lastResult.add(new Result(bot, pack));
112                                                 }
113                                         }
114                                 }
115                                 Collections.sort(lastResult);
116                                 int counter = 0;
117                                 for (Result result : lastResult) {
118                                         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()));
119                                 }
120                                 writeLine("End of Search.");
121                         } else if (words[0].equalsIgnoreCase("dcc")) {
122                                 int counter = 0;
123                                 for (Download download : core.downloads()) {
124                                         DccReceiver dccReceiver = download.dccReceiver();
125                                         if (dccReceiver == null) {
126                                                 /* download has not even started. */
127                                                 writer.write(String.format("[%d] %s requested from %s (not started yet)\n", counter++, download.pack().name(), download.bot().name()));
128                                                 continue;
129                                         }
130                                         writer.write(String.format("[%d] %s from %s (%s, ", counter++, dccReceiver.filename(), download.bot().name(), f(dccReceiver.size())));
131                                         if (dccReceiver.isRunning()) {
132                                                 writer.write(String.format("%.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
133                                         } else {
134                                                 if (dccReceiver.progress() >= dccReceiver.size()) {
135                                                         writer.write(String.format("complete, %s", f(dccReceiver.overallRate())));
136                                                 } else {
137                                                         writer.write(String.format("aborted at %.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
138                                                 }
139                                         }
140                                         writer.write("/s)\n");
141                                 }
142                                 writeLine("End of DCCs.");
143                         } else if (words[0].equalsIgnoreCase("get")) {
144                                 Integer index = Ints.tryParse(words[1]);
145                                 if ((index != null) && (index < lastResult.size())) {
146                                         core.fetch(lastResult.get(index).bot(), lastResult.get(index).pack());
147                                 }
148                         } else if (words[0].equalsIgnoreCase("stats")) {
149                                 int configuredChannelsCount = core.channels().size();
150                                 int joinedChannelsCount = core.joinedChannels().size();
151                                 int extraChannelsCount = core.extraChannels().size();
152                                 Collection<Bot> bots = core.bots();
153                                 Set<String> packNames = Sets.newHashSet();
154                                 int packsCount = 0;
155                                 for (Bot bot : bots) {
156                                         packsCount += bot.packs().size();
157                                         for (Pack pack : bot) {
158                                                 packNames.add(pack.name());
159                                         }
160                                 }
161
162                                 writeLine(String.format("%d channels (%d joined, %d extra), %d bots offering %d packs (%d unique).", configuredChannelsCount, joinedChannelsCount, extraChannelsCount, bots.size(), packsCount, packNames.size()));
163                         } else if (words[0].equalsIgnoreCase("connections")) {
164                                 lastConnections.clear();
165                                 int counter = 0;
166                                 for (Connection connection : core.connections()) {
167                                         lastConnections.add(connection);
168                                         writer.write(String.format("[%d] %s:%d, %s/s\n", counter++, connection.hostname(), connection.port(), f(connection.getInputRate())));
169                                 }
170                                 writeLine("End of connections.");
171                         } else if (words[0].equalsIgnoreCase("disconnect")) {
172                                 if ((words.length == 1) || ("all".equals(words[1]))) {
173                                         for (Connection connection : lastConnections) {
174                                                 core.closeConnection(connection);
175                                         }
176                                 } else {
177                                         Integer index = Ints.tryParse(words[1]);
178                                         if ((index != null) && (index < lastConnections.size())) {
179                                                 core.closeConnection(lastConnections.get(index));
180                                         }
181                                 }
182                         }
183
184                         lastLine = line;
185                 }
186         }
187
188         //
189         // EVENT HANDLERS
190         //
191
192         /**
193          * Called when a download was started.
194          *
195          * @param downloadStarted
196          *              The download started event
197          */
198         @Subscribe
199         public void downloadStarted(DownloadStarted downloadStarted) {
200                 Download download = downloadStarted.download();
201                 try {
202                         writeLine(String.format("Download of %s (from %s, %s) has started.", download.pack().name(), download.bot().name(), download.bot().network().name()));
203                 } catch (IOException ioe1) {
204                         /* ignore. */
205                 }
206         }
207
208         /**
209          * Called when a download is finished.
210          *
211          * @param downloadFinished
212          *              The download finished event
213          */
214         @Subscribe
215         public void downloadFinished(DownloadFinished downloadFinished) {
216                 Download download = downloadFinished.download();
217                 try {
218                         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())));
219                 } catch (IOException ioe1) {
220                         /* ignore. */
221                 }
222         }
223
224         /**
225          * Called when a download fails.
226          *
227          * @param downloadFailed
228          *              The download failed event
229          */
230         @Subscribe
231         public void downloadFailed(DownloadFailed downloadFailed) {
232                 Download download = downloadFailed.download();
233                 try {
234                         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())));
235                 } catch (IOException ioe1) {
236                         /* ignore. */
237                 }
238         }
239
240         /**
241          * Displays the received message on the console.
242          *
243          * @param messageReceived
244          *              The message received event
245          */
246         @Subscribe
247         public void messageReceived(MessageReceived messageReceived) {
248                 try {
249                         writeLine(String.format("Message from %s: %s", messageReceived.source(), MessageCleaner.getDefaultInstance().clean(messageReceived.message())));
250                 } catch (IOException e) {
251                         /* ignore. */
252                 }
253         }
254
255         /**
256          * Writes a generic message to the console.
257          *
258          * @param genericMessage
259          *              The generic message event
260          */
261         @Subscribe
262         public void genericMessage(GenericMessage genericMessage) {
263                 try {
264                         writeLine(genericMessage.message());
265                 } catch (IOException ioe1) {
266                         /* ignore. */
267                 }
268         }
269
270         //
271         // PRIVATE METHODS
272         //
273
274         /**
275          * Writes the given line followed by an LF to the {@link #writer}.
276          *
277          * @param line
278          *              The line to write
279          * @throws IOException
280          *              if an I/O error occurs
281          */
282         private void writeLine(String line) throws IOException {
283                 writer.write(line + "\n");
284                 writer.flush();
285         }
286
287         /**
288          * Converts large numbers into a human-friendly format, by showing SI prefixes
289          * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
290          *
291          * @param number
292          *              The number to convert
293          * @return The converted number
294          */
295         private static String f(long number) {
296                 if (number >= (1 << 30)) {
297                         return String.format("%.1fG", number / (double) (1 << 30));
298                 }
299                 if (number >= (1 << 20)) {
300                         return String.format("%.1fM", number / (double) (1 << 20));
301                 }
302                 if (number >= (1 << 10)) {
303                         return String.format("%.1fK", number / (double) (1 << 10));
304                 }
305                 return String.format("%dB", number);
306         }
307
308         /** Container for result information. */
309         private static class Result implements Comparable<Result> {
310
311                 /** The bot carrying the pack. */
312                 private final Bot bot;
313
314                 /** The pack. */
315                 private final Pack pack;
316
317                 /**
318                  * Creates a new result.
319                  *
320                  * @param bot
321                  *              The bot carrying the pack
322                  * @param pack
323                  *              The pack
324                  */
325                 private Result(Bot bot, Pack pack) {
326                         this.bot = bot;
327                         this.pack = pack;
328                 }
329
330                 //
331                 // ACCESSORS
332                 //
333
334                 /**
335                  * Returns the bot carrying the pack.
336                  *
337                  * @return The bot carrying the pack
338                  */
339                 public Bot bot() {
340                         return bot;
341                 }
342
343                 /**
344                  * Returns the pack.
345                  *
346                  * @return The pack
347                  */
348                 public Pack pack() {
349                         return pack;
350                 }
351
352                 //
353                 // COMPARABLE METHODS
354                 //
355
356                 @Override
357                 public int compareTo(Result result) {
358                         return pack().name().compareToIgnoreCase(result.pack().name());
359                 }
360
361         }
362
363 }