2 * Rhynodge - TorrentState.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.rhynodge.states;
20 import java.nio.charset.StandardCharsets;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.HashSet;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Optional;
29 import javax.annotation.Nonnull;
31 import net.pterodactylus.rhynodge.Reaction;
32 import net.pterodactylus.rhynodge.State;
33 import net.pterodactylus.rhynodge.output.DefaultOutput;
34 import net.pterodactylus.rhynodge.output.Output;
35 import net.pterodactylus.rhynodge.states.TorrentState.TorrentFile;
37 import com.fasterxml.jackson.annotation.JsonProperty;
38 import com.google.common.collect.Lists;
39 import com.google.common.collect.Ordering;
40 import org.apache.commons.lang3.StringEscapeUtils;
41 import org.apache.http.NameValuePair;
42 import org.apache.http.client.utils.URLEncodedUtils;
43 import org.jetbrains.annotations.NotNull;
44 import org.jetbrains.annotations.Nullable;
46 import static com.google.common.collect.Ordering.from;
47 import static java.lang.String.format;
50 * {@link State} that contains information about an arbitrary number of torrent
53 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
55 public class TorrentState extends AbstractState implements Iterable<TorrentFile> {
57 /** The torrent files. */
59 private List<TorrentFile> files = Lists.newArrayList();
61 private final Set<TorrentFile> newTorrentFiles = new HashSet<>();
64 * Creates a new torrent state without torrent files.
66 public TorrentState() {
67 this(Collections.<TorrentFile>emptySet());
71 * Creates a new torrent state containing the given torrent files.
76 public TorrentState(Collection<TorrentFile> torrentFiles) {
77 files.addAll(torrentFiles);
80 public TorrentState(Collection<TorrentFile> torrentFiles, Collection<TorrentFile> newTorrentFiles) {
81 files.addAll(torrentFiles);
82 this.newTorrentFiles.addAll(newTorrentFiles);
90 public boolean isEmpty() {
91 return files.isEmpty();
95 public boolean triggered() {
96 return !newTorrentFiles.isEmpty();
100 * Returns all torrent files of this state.
102 * @return All torrent files of this state
104 public Collection<TorrentFile> torrentFiles() {
105 return Collections.unmodifiableList(files);
109 * Adds a torrent file to this state.
112 * The torrent file to add
115 public TorrentState addTorrentFile(TorrentFile torrentFile) {
116 files.add(torrentFile);
122 protected String summary(Reaction reaction) {
123 return format("Found %d new Torrent(s) for “%s!”", newTorrentFiles.size(), reaction.name());
128 protected String plainText() {
129 StringBuilder plainText = new StringBuilder();
130 plainText.append("New Torrents:\n\n");
131 for (TorrentFile torrentFile : newTorrentFiles) {
132 plainText.append(torrentFile.name()).append('\n');
133 plainText.append('\t').append(torrentFile.size()).append(" in ").append(torrentFile.fileCount()).append(" file(s)\n");
134 plainText.append('\t').append(torrentFile.seedCount()).append(" seed(s), ").append(torrentFile.leechCount()).append(" leecher(s)\n");
135 if ((torrentFile.magnetUri() != null) && (torrentFile.magnetUri().length() > 0)) {
136 plainText.append('\t').append(torrentFile.magnetUri()).append('\n');
138 if ((torrentFile.downloadUri() != null) && (torrentFile.downloadUri().length() > 0)) {
139 plainText.append('\t').append(torrentFile.downloadUri()).append('\n');
141 plainText.append('\n');
143 return plainText.toString();
148 protected String htmlText() {
149 StringBuilder htmlBuilder = new StringBuilder();
150 htmlBuilder.append("<html><body>\n");
151 htmlBuilder.append("<table>\n<caption>All Known Torrents</caption>\n");
152 htmlBuilder.append("<thead>\n");
153 htmlBuilder.append("<tr>");
154 htmlBuilder.append("<th>Filename</th>");
155 htmlBuilder.append("<th>Size</th>");
156 htmlBuilder.append("<th>File(s)</th>");
157 htmlBuilder.append("<th>Seeds</th>");
158 htmlBuilder.append("<th>Leechers</th>");
159 htmlBuilder.append("<th>Magnet</th>");
160 htmlBuilder.append("<th>Download</th>");
161 htmlBuilder.append("</tr>\n");
162 htmlBuilder.append("</thead>\n");
163 htmlBuilder.append("<tbody>\n");
164 for (TorrentFile torrentFile : sortNewFirst().sortedCopy(files)) {
165 if (newTorrentFiles.contains(torrentFile)) {
166 htmlBuilder.append("<tr style=\"color: #008000; font-weight: bold;\">");
168 htmlBuilder.append("<tr>");
170 htmlBuilder.append("<td>").append(StringEscapeUtils.escapeHtml4(torrentFile.name())).append("</td>");
171 htmlBuilder.append("<td>").append(StringEscapeUtils.escapeHtml4(torrentFile.size())).append("</td>");
172 htmlBuilder.append("<td>").append(torrentFile.fileCount()).append("</td>");
173 htmlBuilder.append("<td>").append(torrentFile.seedCount()).append("</td>");
174 htmlBuilder.append("<td>").append(torrentFile.leechCount()).append("</td>");
175 htmlBuilder.append("<td><a href=\"").append(StringEscapeUtils.escapeHtml4(torrentFile.magnetUri())).append("\">Link</a></td>");
176 htmlBuilder.append("<td><a href=\"").append(StringEscapeUtils.escapeHtml4(torrentFile.downloadUri())).append("\">Link</a></td>");
177 htmlBuilder.append("</tr>\n");
179 htmlBuilder.append("</tbody>\n");
180 htmlBuilder.append("</table>\n");
181 htmlBuilder.append("</body></html>\n");
182 return htmlBuilder.toString();
186 * Returns an ordering that sorts torrent files by whether they are new
187 * (according to {@link #files}) or not. New files will be sorted
190 * @return An ordering for “new files first”
192 private Ordering<TorrentFile> sortNewFirst() {
193 return from((TorrentFile leftTorrentFile, TorrentFile rightTorrentFile) -> {
194 if (newTorrentFiles.contains(leftTorrentFile) && !newTorrentFiles.contains(rightTorrentFile)) {
197 if (!newTorrentFiles.contains(leftTorrentFile) && newTorrentFiles.contains(rightTorrentFile)) {
212 public Iterator<TorrentFile> iterator() {
213 return files.iterator();
224 public String toString() {
225 return format("%s[files=%s]", getClass().getSimpleName(), files);
229 * Container for torrent file data.
231 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
233 public static class TorrentFile {
235 /** The name of the file. */
237 private final String name;
239 /** The size of the file. */
241 private final String size;
243 /** The magnet URI of the file. */
245 private final String magnetUri;
247 /** The download URI of the file. */
249 private final String downloadUri;
251 /** The number of files in this torrent. */
253 private final int fileCount;
255 /** The number of seeds connected to this torrent. */
257 private final int seedCount;
259 /** The number of leechers connected to this torrent. */
261 private final int leechCount;
264 * No-arg constructor for deserialization.
266 @SuppressWarnings("unused")
267 private TorrentFile() {
268 this(null, null, null, null, 0, 0, 0);
272 * Creates a new torrent file.
275 * The name of the file
277 * The size of the file
279 * The magnet URI of the file
281 * The download URI of the file
283 * The number of files
285 * The number of connected seeds
287 * The number of connected leechers
289 public TorrentFile(String name, String size, String magnetUri, String downloadUri, int fileCount, int seedCount, int leechCount) {
292 this.magnetUri = magnetUri;
293 this.downloadUri = downloadUri;
294 this.fileCount = fileCount;
295 this.seedCount = seedCount;
296 this.leechCount = leechCount;
304 * Returns the name of the file.
306 * @return The name of the file
308 public String name() {
313 * Returns the size of the file. The returned size may included
314 * non-numeric information, such as units (e. g. “860.46 MB”).
316 * @return The size of the file
318 public String size() {
323 * Returns the magnet URI of the file.
325 * @return The magnet URI of the file, or {@code null} if there is no
326 * magnet URI for this torrent file
328 public String magnetUri() {
333 * Returns the download URI of the file.
335 * @return The download URI of the file, or {@code null} if there is no
336 * download URI for this torrent file
338 public String downloadUri() {
343 * Returns the number of files in this torrent.
345 * @return The number of files in this torrent
347 public int fileCount() {
352 * Returns the number of seeds connected to this torrent.
354 * @return The number of connected seeds
356 public int seedCount() {
361 * Returns the number of leechers connected to this torrent.
363 * @return The number of connected leechers
365 public int leechCount() {
374 * Generates an ID for this file. If a {@link #magnetUri} is set, an ID
375 * is {@link #extractId(String) extracted} from it. Otherwise the magnet
376 * URI is used. If the {@link #magnetUri} is not set, the
377 * {@link #downloadUri} is used. If that is not set either, the name of
378 * the file is returned.
380 * @return The generated ID
382 private String generateId() {
383 if (magnetUri != null) {
384 return extractId(magnetUri).orElse(magnetUri);
386 return (downloadUri != null) ? downloadUri : name;
394 * Tries to extract the “exact target” of a magnet URI.
397 * The magnet URI to extract the “xt” from
398 * @return The extracted ID, or {@code null} if no ID could be found
400 private static Optional<String> extractId(String magnetUri) {
401 if ((magnetUri == null) || (magnetUri.length() < 8)) {
402 return Optional.empty();
404 List<NameValuePair> parameters = URLEncodedUtils.parse(magnetUri.substring("magnet:?".length()), StandardCharsets.UTF_8);
405 for (NameValuePair parameter : parameters) {
406 if (parameter.getName().equals("xt")) {
407 return Optional.of(parameter.getValue().toLowerCase());
410 return Optional.empty();
421 public int hashCode() {
422 return (generateId() != null) ? generateId().hashCode() : 0;
429 public boolean equals(Object object) {
430 if (!(object instanceof TorrentFile)) {
433 if (generateId() != null) {
434 return generateId().equals(((TorrentFile) object).generateId());
443 public String toString() {
444 return format("%s(%s,%s,%s)", name(), size(), magnetUri(), downloadUri());