Store new torrents.
[rhynodge.git] / src / main / java / net / pterodactylus / rhynodge / triggers / NewEpisodeTrigger.java
1 /*
2  * Rhynodge - NewEpisodeTrigger.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.triggers;
19
20 import static com.google.common.base.Preconditions.checkState;
21
22 import java.util.Collection;
23 import java.util.Map;
24 import java.util.Map.Entry;
25
26 import net.pterodactylus.rhynodge.Reaction;
27 import net.pterodactylus.rhynodge.State;
28 import net.pterodactylus.rhynodge.Trigger;
29 import net.pterodactylus.rhynodge.output.DefaultOutput;
30 import net.pterodactylus.rhynodge.output.Output;
31 import net.pterodactylus.rhynodge.states.EpisodeState;
32 import net.pterodactylus.rhynodge.states.EpisodeState.Episode;
33 import net.pterodactylus.rhynodge.states.TorrentState.TorrentFile;
34
35 import org.apache.commons.lang3.StringEscapeUtils;
36
37 import com.google.common.base.Function;
38 import com.google.common.collect.FluentIterable;
39 import com.google.common.collect.ImmutableMap;
40 import com.google.common.collect.Lists;
41 import com.google.common.collect.Maps;
42 import com.google.common.collect.Ordering;
43 import com.google.common.collect.Sets;
44
45 /**
46  * {@link Trigger} implementation that compares two {@link EpisodeState}s for
47  * new and changed {@link Episode}s.
48  *
49  * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
50  */
51 public class NewEpisodeTrigger implements Trigger {
52
53         /** All episodes. */
54         private final Collection<Episode> allEpisodes = Sets.newHashSet();
55
56         /** All new episodes. */
57         private final Collection<Episode> newEpisodes = Sets.newHashSet();
58
59         /** All changed episodes. */
60         private final Collection<Episode> changedEpisodes = Sets.newHashSet();
61
62         /** All new torrent files. */
63         private final Collection<TorrentFile> newTorrentFiles = Sets.newHashSet();
64
65         //
66         // TRIGGER METHODS
67         //
68
69         /**
70          * {@inheritDocs}
71          */
72         @Override
73         public State mergeStates(State previousState, State currentState) {
74                 checkState(currentState instanceof EpisodeState, "currentState is not a EpisodeState but a %s", currentState.getClass().getName());
75                 checkState(previousState instanceof EpisodeState, "previousState is not a EpisodeState but a %s", currentState.getClass().getName());
76                 newEpisodes.clear();
77                 changedEpisodes.clear();
78                 this.allEpisodes.clear();
79                 newTorrentFiles.clear();
80                 Map<Episode, Episode> allEpisodes = Maps.newHashMap(FluentIterable.from(((EpisodeState) previousState).episodes()).toMap(new Function<Episode, Episode>() {
81
82                         @Override
83                         public Episode apply(Episode episode) {
84                                 return episode;
85                         }
86                 }));
87                 for (Episode episode : ((EpisodeState) currentState).episodes()) {
88                         if (!allEpisodes.containsKey(episode)) {
89                                 allEpisodes.put(episode, episode);
90                                 newEpisodes.add(episode);
91                         }
92                         for (TorrentFile torrentFile : Lists.newArrayList(episode.torrentFiles())) {
93                                 int oldSize = allEpisodes.get(episode).torrentFiles().size();
94                                 allEpisodes.get(episode).addTorrentFile(torrentFile);
95                                 int newSize = allEpisodes.get(episode).torrentFiles().size();
96                                 if (oldSize != newSize) {
97                                         newTorrentFiles.add(torrentFile);
98                                 }
99                                 if (!newEpisodes.contains(episode) && (oldSize != newSize)) {
100                                         changedEpisodes.add(episode);
101                                 }
102                         }
103                 }
104                 this.allEpisodes.addAll(allEpisodes.values());
105                 return new EpisodeState(this.allEpisodes);
106         }
107
108         /**
109          * {@inheritDoc}
110          */
111         @Override
112         public boolean triggers() {
113                 return !newEpisodes.isEmpty() || !changedEpisodes.isEmpty();
114         }
115
116         /**
117          * {@inheritDoc}
118          */
119         @Override
120         public Output output(Reaction reaction) {
121                 String summary;
122                 if (!newEpisodes.isEmpty()) {
123                         if (!changedEpisodes.isEmpty()) {
124                                 summary = String.format("%d new and %d changed Torrent(s) for “%s!”", newEpisodes.size(), changedEpisodes.size(), reaction.name());
125                         } else {
126                                 summary = String.format("%d new Torrent(s) for “%s!”", newEpisodes.size(), reaction.name());
127                         }
128                 } else {
129                         summary = String.format("%d changed Torrent(s) for “%s!”", changedEpisodes.size(), reaction.name());
130                 }
131                 DefaultOutput output = new DefaultOutput(summary);
132                 output.addText("text/plain", generatePlainText(reaction, newEpisodes, changedEpisodes, allEpisodes));
133                 output.addText("text/html", generateHtmlText(reaction, newEpisodes, changedEpisodes, allEpisodes));
134                 return output;
135         }
136
137         //
138         // STATIC METHODS
139         //
140
141         /**
142          * Generates the plain text trigger output.
143          *
144          * @param reaction
145          *            The reaction that was triggered
146          * @param newEpisodes
147          *            The new episodes
148          * @param changedEpisodes
149          *            The changed episodes
150          * @param allEpisodes
151          *            All episodes
152          * @return The plain text output
153          */
154         private static String generatePlainText(Reaction reaction, Collection<Episode> newEpisodes, Collection<Episode> changedEpisodes, Collection<Episode> allEpisodes) {
155                 StringBuilder stringBuilder = new StringBuilder();
156                 if (!newEpisodes.isEmpty()) {
157                         stringBuilder.append(reaction.name()).append(" - New Episodes\n\n");
158                         for (Episode episode : newEpisodes) {
159                                 stringBuilder.append("- ").append(episode.identifier()).append("\n");
160                                 for (TorrentFile torrentFile : episode) {
161                                         stringBuilder.append("  - ").append(torrentFile.name()).append(", ").append(torrentFile.size()).append("\n");
162                                         if ((torrentFile.magnetUri() != null) && (torrentFile.magnetUri().length() > 0)) {
163                                                 stringBuilder.append("    Magnet: ").append(torrentFile.magnetUri()).append("\n");
164                                         }
165                                         if ((torrentFile.downloadUri() != null) && (torrentFile.downloadUri().length() > 0)) {
166                                                 stringBuilder.append("    Download: ").append(torrentFile.downloadUri()).append("\n");
167                                         }
168                                 }
169                         }
170                 }
171                 if (!changedEpisodes.isEmpty()) {
172                         stringBuilder.append(reaction.name()).append(" - Changed Episodes\n\n");
173                         for (Episode episode : changedEpisodes) {
174                                 stringBuilder.append("- ").append(episode.identifier()).append("\n");
175                                 for (TorrentFile torrentFile : episode) {
176                                         stringBuilder.append("  - ").append(torrentFile.name()).append(", ").append(torrentFile.size()).append("\n");
177                                         if ((torrentFile.magnetUri() != null) && (torrentFile.magnetUri().length() > 0)) {
178                                                 stringBuilder.append("    Magnet: ").append(torrentFile.magnetUri()).append("\n");
179                                         }
180                                         if ((torrentFile.downloadUri() != null) && (torrentFile.downloadUri().length() > 0)) {
181                                                 stringBuilder.append("    Download: ").append(torrentFile.downloadUri()).append("\n");
182                                         }
183                                 }
184                         }
185                 }
186                 /* list all known episodes. */
187                 stringBuilder.append(reaction.name()).append(" - All Known Episodes\n\n");
188                 ImmutableMap<Integer, Collection<Episode>> episodesBySeason = FluentIterable.from(allEpisodes).index(new Function<Episode, Integer>() {
189
190                         @Override
191                         public Integer apply(Episode episode) {
192                                 return episode.season();
193                         }
194                 }).asMap();
195                 for (Entry<Integer, Collection<Episode>> seasonEntry : episodesBySeason.entrySet()) {
196                         stringBuilder.append("  Season ").append(seasonEntry.getKey()).append("\n\n");
197                         for (Episode episode : Ordering.natural().sortedCopy(seasonEntry.getValue())) {
198                                 stringBuilder.append("    Episode ").append(episode.episode()).append("\n");
199                                 for (TorrentFile torrentFile : episode) {
200                                         stringBuilder.append("      Size: ").append(torrentFile.size());
201                                         stringBuilder.append(" in ").append(torrentFile.fileCount()).append(" file(s): ");
202                                         stringBuilder.append(torrentFile.magnetUri());
203                                 }
204                         }
205                 }
206
207                 return stringBuilder.toString();
208         }
209
210         /**
211          * Generates the HTML trigger output.
212          *
213          * @param reaction
214          *            The reaction that was triggered
215          * @param newEpisodes
216          *            The new episodes
217          * @param changedEpisodes
218          *            The changed episodes
219          * @param allEpisodes
220          *            All episodes
221          * @return The HTML output
222          */
223         private static String generateHtmlText(Reaction reaction, Collection<Episode> newEpisodes, Collection<Episode> changedEpisodes, Collection<Episode> allEpisodes) {
224                 StringBuilder htmlBuilder = new StringBuilder();
225                 htmlBuilder.append("<html><body>\n");
226                 htmlBuilder.append("<h1>").append(StringEscapeUtils.escapeHtml4(reaction.name())).append("</h1>\n");
227                 if (!newEpisodes.isEmpty()) {
228                         htmlBuilder.append("<h2>New Episodes</h2>\n");
229                         htmlBuilder.append("<ul>\n");
230                         for (Episode episode : newEpisodes) {
231                                 htmlBuilder.append("<li>Season ").append(episode.season()).append(", Episode ").append(episode.episode()).append("</li>\n");
232                                 htmlBuilder.append("<ul>\n");
233                                 for (TorrentFile torrentFile : episode) {
234                                         htmlBuilder.append("<li>").append(StringEscapeUtils.escapeHtml4(torrentFile.name())).append("</li>\n");
235                                         htmlBuilder.append("<div>");
236                                         htmlBuilder.append("<strong>").append(StringEscapeUtils.escapeHtml4(torrentFile.size())).append("</strong>, ");
237                                         htmlBuilder.append("<strong>").append(torrentFile.fileCount()).append("</strong> file(s), ");
238                                         htmlBuilder.append("<strong>").append(torrentFile.seedCount()).append("</strong> seed(s), ");
239                                         htmlBuilder.append("<strong>").append(torrentFile.leechCount()).append("</strong> leecher(s)</div>\n");
240                                         htmlBuilder.append("<div>");
241                                         if ((torrentFile.magnetUri() != null) && (torrentFile.magnetUri().length() > 0)) {
242                                                 htmlBuilder.append("<a href=\"").append(StringEscapeUtils.escapeHtml4(torrentFile.magnetUri())).append("\">Magnet</a> ");
243                                         }
244                                         if ((torrentFile.downloadUri() != null) && (torrentFile.downloadUri().length() > 0)) {
245                                                 htmlBuilder.append("<a href=\"").append(StringEscapeUtils.escapeHtml4(torrentFile.downloadUri())).append("\">Download</a>");
246                                         }
247                                         htmlBuilder.append("</div>\n");
248                                 }
249                                 htmlBuilder.append("</ul>\n");
250                         }
251                         htmlBuilder.append("</ul>\n");
252                 }
253                 if (!changedEpisodes.isEmpty()) {
254                         htmlBuilder.append("<h2>Changed Episodes</h2>\n");
255                         htmlBuilder.append("<ul>\n");
256                         for (Episode episode : changedEpisodes) {
257                                 htmlBuilder.append("<li>Season ").append(episode.season()).append(", Episode ").append(episode.episode()).append("</li>\n");
258                                 htmlBuilder.append("<ul>\n");
259                                 for (TorrentFile torrentFile : episode) {
260                                         htmlBuilder.append("<li>").append(StringEscapeUtils.escapeHtml4(torrentFile.name())).append("</li>\n");
261                                         htmlBuilder.append("<div>");
262                                         htmlBuilder.append("<strong>").append(StringEscapeUtils.escapeHtml4(torrentFile.size())).append("</strong>, ");
263                                         htmlBuilder.append("<strong>").append(torrentFile.fileCount()).append("</strong> file(s), ");
264                                         htmlBuilder.append("<strong>").append(torrentFile.seedCount()).append("</strong> seed(s), ");
265                                         htmlBuilder.append("<strong>").append(torrentFile.leechCount()).append("</strong> leecher(s)</div>\n");
266                                         htmlBuilder.append("<div>");
267                                         if ((torrentFile.magnetUri() != null) && (torrentFile.magnetUri().length() > 0)) {
268                                                 htmlBuilder.append("<a href=\"").append(StringEscapeUtils.escapeHtml4(torrentFile.magnetUri())).append("\">Magnet</a> ");
269                                         }
270                                         if ((torrentFile.downloadUri() != null) && (torrentFile.downloadUri().length() > 0)) {
271                                                 htmlBuilder.append("<a href=\"").append(StringEscapeUtils.escapeHtml4(torrentFile.downloadUri())).append("\">Download</a>");
272                                         }
273                                         htmlBuilder.append("</div>\n");
274                                 }
275                                 htmlBuilder.append("</ul>\n");
276                         }
277                         htmlBuilder.append("</ul>\n");
278                 }
279                 htmlBuilder.append("</body></html>\n");
280                 return htmlBuilder.toString();
281         }
282
283 }