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 * Returns all torrent files of this state.
97 * @return All torrent files of this state
99 public Collection<TorrentFile> torrentFiles() {
100 return Collections.unmodifiableList(files);
104 * Adds a torrent file to this state.
107 * The torrent file to add
110 public TorrentState addTorrentFile(TorrentFile torrentFile) {
111 files.add(torrentFile);
117 protected String summary(Reaction reaction) {
118 return format("Found %d new Torrent(s) for “%s!”", newTorrentFiles.size(), reaction.name());
123 protected String plainText() {
124 StringBuilder plainText = new StringBuilder();
125 plainText.append("New Torrents:\n\n");
126 for (TorrentFile torrentFile : newTorrentFiles) {
127 plainText.append(torrentFile.name()).append('\n');
128 plainText.append('\t').append(torrentFile.size()).append(" in ").append(torrentFile.fileCount()).append(" file(s)\n");
129 plainText.append('\t').append(torrentFile.seedCount()).append(" seed(s), ").append(torrentFile.leechCount()).append(" leecher(s)\n");
130 if ((torrentFile.magnetUri() != null) && (torrentFile.magnetUri().length() > 0)) {
131 plainText.append('\t').append(torrentFile.magnetUri()).append('\n');
133 if ((torrentFile.downloadUri() != null) && (torrentFile.downloadUri().length() > 0)) {
134 plainText.append('\t').append(torrentFile.downloadUri()).append('\n');
136 plainText.append('\n');
138 return plainText.toString();
143 protected String htmlText() {
144 StringBuilder htmlBuilder = new StringBuilder();
145 htmlBuilder.append("<html><body>\n");
146 htmlBuilder.append("<table>\n<caption>All Known Torrents</caption>\n");
147 htmlBuilder.append("<thead>\n");
148 htmlBuilder.append("<tr>");
149 htmlBuilder.append("<th>Filename</th>");
150 htmlBuilder.append("<th>Size</th>");
151 htmlBuilder.append("<th>File(s)</th>");
152 htmlBuilder.append("<th>Seeds</th>");
153 htmlBuilder.append("<th>Leechers</th>");
154 htmlBuilder.append("<th>Magnet</th>");
155 htmlBuilder.append("<th>Download</th>");
156 htmlBuilder.append("</tr>\n");
157 htmlBuilder.append("</thead>\n");
158 htmlBuilder.append("<tbody>\n");
159 for (TorrentFile torrentFile : sortNewFirst().sortedCopy(files)) {
160 if (newTorrentFiles.contains(torrentFile)) {
161 htmlBuilder.append("<tr style=\"color: #008000; font-weight: bold;\">");
163 htmlBuilder.append("<tr>");
165 htmlBuilder.append("<td>").append(StringEscapeUtils.escapeHtml4(torrentFile.name())).append("</td>");
166 htmlBuilder.append("<td>").append(StringEscapeUtils.escapeHtml4(torrentFile.size())).append("</td>");
167 htmlBuilder.append("<td>").append(torrentFile.fileCount()).append("</td>");
168 htmlBuilder.append("<td>").append(torrentFile.seedCount()).append("</td>");
169 htmlBuilder.append("<td>").append(torrentFile.leechCount()).append("</td>");
170 htmlBuilder.append("<td><a href=\"").append(StringEscapeUtils.escapeHtml4(torrentFile.magnetUri())).append("\">Link</a></td>");
171 htmlBuilder.append("<td><a href=\"").append(StringEscapeUtils.escapeHtml4(torrentFile.downloadUri())).append("\">Link</a></td>");
172 htmlBuilder.append("</tr>\n");
174 htmlBuilder.append("</tbody>\n");
175 htmlBuilder.append("</table>\n");
176 htmlBuilder.append("</body></html>\n");
177 return htmlBuilder.toString();
181 * Returns an ordering that sorts torrent files by whether they are new
182 * (according to {@link #files}) or not. New files will be sorted
185 * @return An ordering for “new files first”
187 private Ordering<TorrentFile> sortNewFirst() {
188 return from((TorrentFile leftTorrentFile, TorrentFile rightTorrentFile) -> {
189 if (newTorrentFiles.contains(leftTorrentFile) && !newTorrentFiles.contains(rightTorrentFile)) {
192 if (!newTorrentFiles.contains(leftTorrentFile) && newTorrentFiles.contains(rightTorrentFile)) {
207 public Iterator<TorrentFile> iterator() {
208 return files.iterator();
219 public String toString() {
220 return format("%s[files=%s]", getClass().getSimpleName(), files);
224 * Container for torrent file data.
226 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
228 public static class TorrentFile {
230 /** The name of the file. */
232 private final String name;
234 /** The size of the file. */
236 private final String size;
238 /** The magnet URI of the file. */
240 private final String magnetUri;
242 /** The download URI of the file. */
244 private final String downloadUri;
246 /** The number of files in this torrent. */
248 private final int fileCount;
250 /** The number of seeds connected to this torrent. */
252 private final int seedCount;
254 /** The number of leechers connected to this torrent. */
256 private final int leechCount;
259 * No-arg constructor for deserialization.
261 @SuppressWarnings("unused")
262 private TorrentFile() {
263 this(null, null, null, null, 0, 0, 0);
267 * Creates a new torrent file.
270 * The name of the file
272 * The size of the file
274 * The magnet URI of the file
276 * The download URI of the file
278 * The number of files
280 * The number of connected seeds
282 * The number of connected leechers
284 public TorrentFile(String name, String size, String magnetUri, String downloadUri, int fileCount, int seedCount, int leechCount) {
287 this.magnetUri = magnetUri;
288 this.downloadUri = downloadUri;
289 this.fileCount = fileCount;
290 this.seedCount = seedCount;
291 this.leechCount = leechCount;
299 * Returns the name of the file.
301 * @return The name of the file
303 public String name() {
308 * Returns the size of the file. The returned size may included
309 * non-numeric information, such as units (e. g. “860.46 MB”).
311 * @return The size of the file
313 public String size() {
318 * Returns the magnet URI of the file.
320 * @return The magnet URI of the file, or {@code null} if there is no
321 * magnet URI for this torrent file
323 public String magnetUri() {
328 * Returns the download URI of the file.
330 * @return The download URI of the file, or {@code null} if there is no
331 * download URI for this torrent file
333 public String downloadUri() {
338 * Returns the number of files in this torrent.
340 * @return The number of files in this torrent
342 public int fileCount() {
347 * Returns the number of seeds connected to this torrent.
349 * @return The number of connected seeds
351 public int seedCount() {
356 * Returns the number of leechers connected to this torrent.
358 * @return The number of connected leechers
360 public int leechCount() {
369 * Generates an ID for this file. If a {@link #magnetUri} is set, an ID
370 * is {@link #extractId(String) extracted} from it. Otherwise the magnet
371 * URI is used. If the {@link #magnetUri} is not set, the
372 * {@link #downloadUri} is used. If that is not set either, the name of
373 * the file is returned.
375 * @return The generated ID
377 private String generateId() {
378 if (magnetUri != null) {
379 return extractId(magnetUri).orElse(magnetUri);
381 return (downloadUri != null) ? downloadUri : name;
389 * Tries to extract the “exact target” of a magnet URI.
392 * The magnet URI to extract the “xt” from
393 * @return The extracted ID, or {@code null} if no ID could be found
395 private static Optional<String> extractId(String magnetUri) {
396 if ((magnetUri == null) || (magnetUri.length() < 8)) {
397 return Optional.empty();
399 List<NameValuePair> parameters = URLEncodedUtils.parse(magnetUri.substring("magnet:?".length()), StandardCharsets.UTF_8);
400 for (NameValuePair parameter : parameters) {
401 if (parameter.getName().equals("xt")) {
402 return Optional.of(parameter.getValue().toLowerCase());
405 return Optional.empty();
416 public int hashCode() {
417 return (generateId() != null) ? generateId().hashCode() : 0;
424 public boolean equals(Object object) {
425 if (!(object instanceof TorrentFile)) {
428 if (generateId() != null) {
429 return generateId().equals(((TorrentFile) object).generateId());
438 public String toString() {
439 return format("%s(%s,%s,%s)", name(), size(), magnetUri(), downloadUri());