Notify the user when a download starts or finishes.
[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.DccReceiver;
30 import net.pterodactylus.xdcc.core.Core;
31 import net.pterodactylus.xdcc.core.event.DownloadFinished;
32 import net.pterodactylus.xdcc.core.event.DownloadStarted;
33 import net.pterodactylus.xdcc.data.Bot;
34 import net.pterodactylus.xdcc.data.Download;
35 import net.pterodactylus.xdcc.data.Pack;
36
37 import com.google.common.collect.Lists;
38 import com.google.common.collect.Sets;
39 import com.google.common.eventbus.Subscribe;
40 import com.google.common.primitives.Ints;
41 import com.google.common.util.concurrent.AbstractExecutionThreadService;
42
43 /**
44  * Command interface for arbitrary {@link Reader}s.
45  *
46  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
47  */
48 public class CommandReader extends AbstractExecutionThreadService {
49
50         /** The core being controlled. */
51         private final Core core;
52
53         /** The reader to read commands from. */
54         private final BufferedReader reader;
55
56         /** The writer to write the results to. */
57         private final Writer writer;
58
59         /**
60          * Creates a new command reader.
61          *
62          * @param core
63          *              The core being controlled
64          * @param reader
65          *              The reader to read commands from
66          * @param writer
67          *              The write to write results to
68          */
69         public CommandReader(Core core, Reader reader, Writer writer) {
70                 this.core = core;
71                 this.reader = new BufferedReader(reader);
72                 this.writer = writer;
73         }
74
75         //
76         // ABSTRACTEXECUTIONTHREADSERVICE METHODS
77         //
78
79         @Override
80         protected void run() throws Exception {
81                 String lastLine = "";
82                 String line;
83                 final List<Result> lastResult = Lists.newArrayList();
84                 while ((line = reader.readLine()) != null) {
85                         if (line.equals("")) {
86                                 line = lastLine;
87                         }
88                         String[] words = line.split(" +");
89                         if (words[0].equalsIgnoreCase("search")) {
90                                 lastResult.clear();
91                                 for (Bot bot : core.bots()) {
92                                         for (Pack pack : bot) {
93                                                 boolean found = true;
94                                                 for (int wordIndex = 1; wordIndex < words.length; ++wordIndex) {
95                                                         if (words[wordIndex].startsWith("-") && pack.name().toLowerCase().contains(words[wordIndex].toLowerCase().substring(1))) {
96                                                                 found = false;
97                                                                 break;
98                                                         }
99                                                         if (!words[wordIndex].startsWith("-") && !pack.name().toLowerCase().contains(words[wordIndex].toLowerCase())) {
100                                                                 found = false;
101                                                                 break;
102                                                         }
103                                                 }
104                                                 if (found) {
105                                                         lastResult.add(new Result(bot, pack));
106                                                 }
107                                         }
108                                 }
109                                 Collections.sort(lastResult);
110                                 int counter = 0;
111                                 for (Result result : lastResult) {
112                                         writer.write(String.format("[%d] %s (%s) from %s (#%s) on %s\n", counter++, result.pack().name(), result.pack().size(), result.bot().name(), result.pack().id(), result.bot().network().name()));
113                                 }
114                                 writer.write("End of Search.\n");
115                         } else if (words[0].equalsIgnoreCase("dcc")) {
116                                 int counter = 0;
117                                 for (DccReceiver dccReceiver : core.dccReceivers()) {
118                                         writer.write(String.format("[%d] %s (%s, ", counter++, dccReceiver.filename(), dccReceiver.size()));
119                                         if (dccReceiver.isRunning()) {
120                                                 writer.write(String.format("%.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
121                                         } else {
122                                                 if (dccReceiver.progress() >= dccReceiver.size()) {
123                                                         writer.write(String.format("complete, %s", f(dccReceiver.overallRate())));
124                                                 } else {
125                                                         writer.write(String.format("aborted at %.1f%%, %s", dccReceiver.progress() * 100.0 / dccReceiver.size(), f(dccReceiver.currentRate())));
126                                                 }
127                                         }
128                                         writer.write("/s)\n");
129                                 }
130                                 writer.write("End of DCCs.\n");
131                         } else if (words[0].equalsIgnoreCase("get")) {
132                                 Integer index = Ints.tryParse(words[1]);
133                                 if ((index != null) && (index < lastResult.size())) {
134                                         core.fetch(lastResult.get(index).bot(), lastResult.get(index).pack());
135                                 }
136                         } else if (words[0].equalsIgnoreCase("stats")) {
137                                 int configuredChannelsCount = core.channels().size();
138                                 int joinedChannelsCount = core.joinedChannels().size();
139                                 int extraChannelsCount = core.extraChannels().size();
140                                 Collection<Bot> bots = core.bots();
141                                 Set<String> packNames = Sets.newHashSet();
142                                 int packsCount = 0;
143                                 for (Bot bot : bots) {
144                                         packsCount += bot.packs().size();
145                                         for (Pack pack : bot) {
146                                                 packNames.add(pack.name());
147                                         }
148                                 }
149
150                                 writer.write(String.format("%d channels (%d joined, %d extra), %d bots offering %d packs (%d unique).\n", configuredChannelsCount, joinedChannelsCount, extraChannelsCount, bots.size(), packsCount, packNames.size()));
151                         }
152
153                         lastLine = line;
154                         writer.flush();
155                 }
156         }
157
158         //
159         // EVENT HANDLERS
160         //
161
162         /**
163          * Called when a download was started.
164          *
165          * @param downloadStarted
166          *              The download started event
167          */
168         @Subscribe
169         public void downloadStarted(DownloadStarted downloadStarted) {
170                 Download download = downloadStarted.download();
171                 try {
172                         writer.write(String.format("Download of %s (from %s, %s) has started.\n", download.filename(), download.bot().name(), download.bot().network().name()));
173                         writer.flush();
174                 } catch (IOException ioe1) {
175                         /* ignore. */
176                 }
177         }
178
179         /**
180          * Called when a download is finished.
181          *
182          * @param downloadFinished
183          *              The download finished event
184          */
185         @Subscribe
186         public void downloadFinished(DownloadFinished downloadFinished) {
187                 Download download = downloadFinished.download();
188                 try {
189                         writer.write(String.format("Download of %s (from %s, %s) has finished, at %s/s.\n", download.filename(), download.bot().name(), download.bot().network().name(), download.dccReceiver().overallRate()));
190                         writer.flush();
191                 } catch (IOException ioe1) {
192                         /* ignore. */
193                 }
194         }
195
196         //
197         // PRIVATE METHODS
198         //
199
200         /**
201          * Converts large numbers into a human-friendly format, by showing SI prefixes
202          * for ×1024 (K), ×1048576 (M), and ×1073741824 (G).
203          *
204          * @param number
205          *              The number to convert
206          * @return The converted number
207          */
208         private static String f(long number) {
209                 if (number >= (1 << 30)) {
210                         return String.format("%.1fG", number / (double) (1 << 30));
211                 }
212                 if (number >= (1 << 20)) {
213                         return String.format("%.1fM", number / (double) (1 << 20));
214                 }
215                 if (number >= (1 << 10)) {
216                         return String.format("%.1fK", number / (double) (1 << 10));
217                 }
218                 return String.format("%dB", number);
219         }
220
221         /** Container for result information. */
222         private static class Result implements Comparable<Result> {
223
224                 /** The bot carrying the pack. */
225                 private final Bot bot;
226
227                 /** The pack. */
228                 private final Pack pack;
229
230                 /**
231                  * Creates a new result.
232                  *
233                  * @param bot
234                  *              The bot carrying the pack
235                  * @param pack
236                  *              The pack
237                  */
238                 private Result(Bot bot, Pack pack) {
239                         this.bot = bot;
240                         this.pack = pack;
241                 }
242
243                 //
244                 // ACCESSORS
245                 //
246
247                 /**
248                  * Returns the bot carrying the pack.
249                  *
250                  * @return The bot carrying the pack
251                  */
252                 public Bot bot() {
253                         return bot;
254                 }
255
256                 /**
257                  * Returns the pack.
258                  *
259                  * @return The pack
260                  */
261                 public Pack pack() {
262                         return pack;
263                 }
264
265                 //
266                 // COMPARABLE METHODS
267                 //
268
269                 @Override
270                 public int compareTo(Result result) {
271                         return pack().name().compareToIgnoreCase(result.pack().name());
272                 }
273
274         }
275
276 }