Make copies of lists before iterating.
[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                                 Integer index = Ints.tryParse(words[1]);
173                                 if ((index != null) && (index < lastConnections.size())) {
174                                         core.closeConnection(lastConnections.get(index));
175                                 }
176                         }
177
178                         lastLine = line;
179                 }
180         }
181
182         //
183         // EVENT HANDLERS
184         //
185
186         /**
187          * Called when a download was started.
188          *
189          * @param downloadStarted
190          *              The download started event
191          */
192         @Subscribe
193         public void downloadStarted(DownloadStarted downloadStarted) {
194                 Download download = downloadStarted.download();
195                 try {
196                         writeLine(String.format("Download of %s (from %s, %s) has started.", download.pack().name(), download.bot().name(), download.bot().network().name()));
197                 } catch (IOException ioe1) {
198                         /* ignore. */
199                 }
200         }
201
202         /**
203          * Called when a download is finished.
204          *
205          * @param downloadFinished
206          *              The download finished event
207          */
208         @Subscribe
209         public void downloadFinished(DownloadFinished downloadFinished) {
210                 Download download = downloadFinished.download();
211                 try {
212                         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())));
213                 } catch (IOException ioe1) {
214                         /* ignore. */
215                 }
216         }
217
218         /**
219          * Called when a download fails.
220          *
221          * @param downloadFailed
222          *              The download failed event
223          */
224         @Subscribe
225         public void downloadFailed(DownloadFailed downloadFailed) {
226                 Download download = downloadFailed.download();
227                 try {
228                         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())));
229                 } catch (IOException ioe1) {
230                         /* ignore. */
231                 }
232         }
233
234         /**
235          * Displays the received message on the console.
236          *
237          * @param messageReceived
238          *              The message received event
239          */
240         @Subscribe
241         public void messageReceived(MessageReceived messageReceived) {
242                 try {
243                         writeLine(String.format("Message from %s: %s", messageReceived.source(), MessageCleaner.getDefaultInstance().clean(messageReceived.message())));
244                 } catch (IOException e) {
245                         /* ignore. */
246                 }
247         }
248
249         /**
250          * Writes a generic message to the console.
251          *
252          * @param genericMessage
253          *              The generic message event
254          */
255         @Subscribe
256         public void genericMessage(GenericMessage genericMessage) {
257                 try {
258                         writeLine(genericMessage.message());
259                 } catch (IOException ioe1) {
260                         /* ignore. */
261                 }
262         }
263
264         //
265         // PRIVATE METHODS
266         //
267
268         /**
269          * Writes the given line followed by an LF to the {@link #writer}.
270          *
271          * @param line
272          *              The line to write
273          * @throws IOException
274          *              if an I/O error occurs
275          */
276         private void writeLine(String line) throws IOException {
277                 writer.write(line + "\n");
278                 writer.flush();
279         }
280
281         /**
282          * Converts large numbers into a human-friendly format, by showing SI prefixes
283          * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
284          *
285          * @param number
286          *              The number to convert
287          * @return The converted number
288          */
289         private static String f(long number) {
290                 if (number >= (1 << 30)) {
291                         return String.format("%.1fG", number / (double) (1 << 30));
292                 }
293                 if (number >= (1 << 20)) {
294                         return String.format("%.1fM", number / (double) (1 << 20));
295                 }
296                 if (number >= (1 << 10)) {
297                         return String.format("%.1fK", number / (double) (1 << 10));
298                 }
299                 return String.format("%dB", number);
300         }
301
302         /** Container for result information. */
303         private static class Result implements Comparable<Result> {
304
305                 /** The bot carrying the pack. */
306                 private final Bot bot;
307
308                 /** The pack. */
309                 private final Pack pack;
310
311                 /**
312                  * Creates a new result.
313                  *
314                  * @param bot
315                  *              The bot carrying the pack
316                  * @param pack
317                  *              The pack
318                  */
319                 private Result(Bot bot, Pack pack) {
320                         this.bot = bot;
321                         this.pack = pack;
322                 }
323
324                 //
325                 // ACCESSORS
326                 //
327
328                 /**
329                  * Returns the bot carrying the pack.
330                  *
331                  * @return The bot carrying the pack
332                  */
333                 public Bot bot() {
334                         return bot;
335                 }
336
337                 /**
338                  * Returns the pack.
339                  *
340                  * @return The pack
341                  */
342                 public Pack pack() {
343                         return pack;
344                 }
345
346                 //
347                 // COMPARABLE METHODS
348                 //
349
350                 @Override
351                 public int compareTo(Result result) {
352                         return pack().name().compareToIgnoreCase(result.pack().name());
353                 }
354
355         }
356
357 }