f2e9ae299098d48a5e5cafb96d6daf3f2c33bdc1
[rhynodge.git] / src / main / java / net / pterodactylus / rhynodge / states / TorrentState.java
1 /*
2  * Rhynodge - TorrentState.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.rhynodge.states;
19
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;
27 import java.util.Set;
28
29 import javax.annotation.Nonnull;
30
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;
36
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;
45
46 import static com.google.common.collect.Ordering.from;
47 import static java.lang.String.format;
48
49 /**
50  * {@link State} that contains information about an arbitrary number of torrent
51  * files.
52  *
53  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
54  */
55 public class TorrentState extends AbstractState implements Iterable<TorrentFile> {
56
57         /** The torrent files. */
58         @JsonProperty
59         private List<TorrentFile> files = Lists.newArrayList();
60
61         private final Set<TorrentFile> newTorrentFiles = new HashSet<>();
62
63         /**
64          * Creates a new torrent state without torrent files.
65          */
66         public TorrentState() {
67                 this(Collections.<TorrentFile>emptySet());
68         }
69
70         /**
71          * Creates a new torrent state containing the given torrent files.
72          *
73          * @param torrentFiles
74          *            The torrent files
75          */
76         public TorrentState(Collection<TorrentFile> torrentFiles) {
77                 files.addAll(torrentFiles);
78         }
79
80         public TorrentState(Collection<TorrentFile> torrentFiles, Collection<TorrentFile> newTorrentFiles) {
81                 files.addAll(torrentFiles);
82                 this.newTorrentFiles.addAll(newTorrentFiles);
83         }
84
85         //
86         // ACCESSORS
87         //
88
89         @Override
90         public boolean isEmpty() {
91                 return files.isEmpty();
92         }
93
94         /**
95          * Returns all torrent files of this state.
96          *
97          * @return All torrent files of this state
98          */
99         public Collection<TorrentFile> torrentFiles() {
100                 return Collections.unmodifiableList(files);
101         }
102
103         /**
104          * Adds a torrent file to this state.
105          *
106          * @param torrentFile
107          *            The torrent file to add
108          * @return This state
109          */
110         public TorrentState addTorrentFile(TorrentFile torrentFile) {
111                 files.add(torrentFile);
112                 return this;
113         }
114
115         @Nonnull
116         @Override
117         protected String summary(Reaction reaction) {
118                 return format("Found %d new Torrent(s) for “%s!”", newTorrentFiles.size(), reaction.name());
119         }
120
121         @Nonnull
122         @Override
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');
132                         }
133                         if ((torrentFile.downloadUri() != null) && (torrentFile.downloadUri().length() > 0)) {
134                                 plainText.append('\t').append(torrentFile.downloadUri()).append('\n');
135                         }
136                         plainText.append('\n');
137                 }
138                 return plainText.toString();
139         }
140
141         @Nullable
142         @Override
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;\">");
162                         } else {
163                                 htmlBuilder.append("<tr>");
164                         }
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");
173                 }
174                 htmlBuilder.append("</tbody>\n");
175                 htmlBuilder.append("</table>\n");
176                 htmlBuilder.append("</body></html>\n");
177                 return htmlBuilder.toString();
178         }
179
180         /**
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
183          * first.
184          *
185          * @return An ordering for “new files first”
186          */
187         private Ordering<TorrentFile> sortNewFirst() {
188                 return from((TorrentFile leftTorrentFile, TorrentFile rightTorrentFile) -> {
189                         if (newTorrentFiles.contains(leftTorrentFile) && !newTorrentFiles.contains(rightTorrentFile)) {
190                                 return -1;
191                         }
192                         if (!newTorrentFiles.contains(leftTorrentFile) && newTorrentFiles.contains(rightTorrentFile)) {
193                                 return 1;
194                         }
195                         return 0;
196                 });
197         }
198
199         //
200         // ITERABLE METHODS
201         //
202
203         /**
204          * {@inheritDoc}
205          */
206         @Override
207         public Iterator<TorrentFile> iterator() {
208                 return files.iterator();
209         }
210
211         //
212         // OBJECT METHODS
213         //
214
215         /**
216          * {@inheritDoc}
217          */
218         @Override
219         public String toString() {
220                 return format("%s[files=%s]", getClass().getSimpleName(), files);
221         }
222
223         /**
224          * Container for torrent file data.
225          *
226          * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
227          */
228         public static class TorrentFile {
229
230                 /** The name of the file. */
231                 @JsonProperty
232                 private final String name;
233
234                 /** The size of the file. */
235                 @JsonProperty
236                 private final String size;
237
238                 /** The magnet URI of the file. */
239                 @JsonProperty
240                 private final String magnetUri;
241
242                 /** The download URI of the file. */
243                 @JsonProperty
244                 private final String downloadUri;
245
246                 /** The number of files in this torrent. */
247                 @JsonProperty
248                 private final int fileCount;
249
250                 /** The number of seeds connected to this torrent. */
251                 @JsonProperty
252                 private final int seedCount;
253
254                 /** The number of leechers connected to this torrent. */
255                 @JsonProperty
256                 private final int leechCount;
257
258                 /**
259                  * No-arg constructor for deserialization.
260                  */
261                 @SuppressWarnings("unused")
262                 private TorrentFile() {
263                         this(null, null, null, null, 0, 0, 0);
264                 }
265
266                 /**
267                  * Creates a new torrent file.
268                  *
269                  * @param name
270                  *            The name of the file
271                  * @param size
272                  *            The size of the file
273                  * @param magnetUri
274                  *            The magnet URI of the file
275                  * @param downloadUri
276                  *            The download URI of the file
277                  * @param fileCount
278                  *            The number of files
279                  * @param seedCount
280                  *            The number of connected seeds
281                  * @param leechCount
282                  *            The number of connected leechers
283                  */
284                 public TorrentFile(String name, String size, String magnetUri, String downloadUri, int fileCount, int seedCount, int leechCount) {
285                         this.name = name;
286                         this.size = size;
287                         this.magnetUri = magnetUri;
288                         this.downloadUri = downloadUri;
289                         this.fileCount = fileCount;
290                         this.seedCount = seedCount;
291                         this.leechCount = leechCount;
292                 }
293
294                 //
295                 // ACCESSORS
296                 //
297
298                 /**
299                  * Returns the name of the file.
300                  *
301                  * @return The name of the file
302                  */
303                 public String name() {
304                         return name;
305                 }
306
307                 /**
308                  * Returns the size of the file. The returned size may included
309                  * non-numeric information, such as units (e. g. “860.46 MB”).
310                  *
311                  * @return The size of the file
312                  */
313                 public String size() {
314                         return size;
315                 }
316
317                 /**
318                  * Returns the magnet URI of the file.
319                  *
320                  * @return The magnet URI of the file, or {@code null} if there is no
321                  *         magnet URI for this torrent file
322                  */
323                 public String magnetUri() {
324                         return magnetUri;
325                 }
326
327                 /**
328                  * Returns the download URI of the file.
329                  *
330                  * @return The download URI of the file, or {@code null} if there is no
331                  *         download URI for this torrent file
332                  */
333                 public String downloadUri() {
334                         return downloadUri;
335                 }
336
337                 /**
338                  * Returns the number of files in this torrent.
339                  *
340                  * @return The number of files in this torrent
341                  */
342                 public int fileCount() {
343                         return fileCount;
344                 }
345
346                 /**
347                  * Returns the number of seeds connected to this torrent.
348                  *
349                  * @return The number of connected seeds
350                  */
351                 public int seedCount() {
352                         return seedCount;
353                 }
354
355                 /**
356                  * Returns the number of leechers connected to this torrent.
357                  *
358                  * @return The number of connected leechers
359                  */
360                 public int leechCount() {
361                         return leechCount;
362                 }
363
364                 //
365                 // PRIVATE METHODS
366                 //
367
368                 /**
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.
374                  *
375                  * @return The generated ID
376                  */
377                 private String generateId() {
378                         if (magnetUri != null) {
379                                 return extractId(magnetUri).orElse(magnetUri);
380                         }
381                         return (downloadUri != null) ? downloadUri : name;
382                 }
383
384                 //
385                 // STATIC METHODS
386                 //
387
388                 /**
389                  * Tries to extract the “exact target” of a magnet URI.
390                  *
391                  * @param magnetUri
392                  *            The magnet URI to extract the “xt” from
393                  * @return The extracted ID, or {@code null} if no ID could be found
394                  */
395                 private static Optional<String> extractId(String magnetUri) {
396                         if ((magnetUri == null) || (magnetUri.length() < 8)) {
397                                 return Optional.empty();
398                         }
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());
403                                 }
404                         }
405                         return Optional.empty();
406                 }
407
408                 //
409                 // OBJECT METHODS
410                 //
411
412                 /**
413                  * {@inheritDoc}
414                  */
415                 @Override
416                 public int hashCode() {
417                         return (generateId() != null) ? generateId().hashCode() : 0;
418                 }
419
420                 /**
421                  * {@inheritDoc}
422                  */
423                 @Override
424                 public boolean equals(Object object) {
425                         if (!(object instanceof TorrentFile)) {
426                                 return false;
427                         }
428                         if (generateId() != null) {
429                                 return generateId().equals(((TorrentFile) object).generateId());
430                         }
431                         return false;
432                 }
433
434                 /**
435                  * {@inheritDoc}
436                  */
437                 @Override
438                 public String toString() {
439                         return format("%s(%s,%s,%s)", name(), size(), magnetUri(), downloadUri());
440                 }
441
442         }
443
444 }