Fix Kevin & Kell filter.
[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          * {@inheritDoc}
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                         Episode existingEpisode = allEpisodes.get(episode);
93                         for (TorrentFile torrentFile : Lists.newArrayList(episode.torrentFiles())) {
94                                 int oldSize = existingEpisode.torrentFiles().size();
95                                 existingEpisode.addTorrentFile(torrentFile);
96                                 int newSize = existingEpisode.torrentFiles().size();
97                                 if (oldSize != newSize) {
98                                         newTorrentFiles.add(torrentFile);
99                                 }
100                                 if (!newEpisodes.contains(existingEpisode) && (oldSize != newSize)) {
101                                         changedEpisodes.add(existingEpisode);
102                                 }
103                         }
104                 }
105                 this.allEpisodes.addAll(allEpisodes.values());
106                 return new EpisodeState(this.allEpisodes);
107         }
108
109         /**
110          * {@inheritDoc}
111          */
112         @Override
113         public boolean triggers() {
114                 return !newEpisodes.isEmpty() || !changedEpisodes.isEmpty();
115         }
116
117         /**
118          * {@inheritDoc}
119          */
120         @Override
121         public Output output(Reaction reaction) {
122                 String summary;
123                 if (!newEpisodes.isEmpty()) {
124                         if (!changedEpisodes.isEmpty()) {
125                                 summary = String.format("%d new and %d changed Torrent(s) for “%s!”", newEpisodes.size(), changedEpisodes.size(), reaction.name());
126                         } else {
127                                 summary = String.format("%d new Torrent(s) for “%s!”", newEpisodes.size(), reaction.name());
128                         }
129                 } else {
130                         summary = String.format("%d changed Torrent(s) for “%s!”", changedEpisodes.size(), reaction.name());
131                 }
132                 DefaultOutput output = new DefaultOutput(summary);
133                 output.addText("text/plain", generatePlainText(reaction));
134                 output.addText("text/html", generateHtmlText(reaction));
135                 return output;
136         }
137
138         //
139         // PRIVATE METHODS
140         //
141
142         /**
143          * Generates the plain text trigger output.
144          *
145          * @param reaction
146          *            The reaction that was triggered
147          * @return The plain text output
148          */
149         private String generatePlainText(Reaction reaction) {
150                 StringBuilder stringBuilder = new StringBuilder();
151                 if (!newEpisodes.isEmpty()) {
152                         stringBuilder.append(reaction.name()).append(" - New Episodes\n\n");
153                         for (Episode episode : newEpisodes) {
154                                 stringBuilder.append("- ").append(episode.identifier()).append("\n");
155                                 for (TorrentFile torrentFile : episode) {
156                                         stringBuilder.append("  - ").append(torrentFile.name()).append(", ").append(torrentFile.size()).append("\n");
157                                         if ((torrentFile.magnetUri() != null) && (torrentFile.magnetUri().length() > 0)) {
158                                                 stringBuilder.append("    Magnet: ").append(torrentFile.magnetUri()).append("\n");
159                                         }
160                                         if ((torrentFile.downloadUri() != null) && (torrentFile.downloadUri().length() > 0)) {
161                                                 stringBuilder.append("    Download: ").append(torrentFile.downloadUri()).append("\n");
162                                         }
163                                 }
164                         }
165                 }
166                 if (!changedEpisodes.isEmpty()) {
167                         stringBuilder.append(reaction.name()).append(" - Changed Episodes\n\n");
168                         for (Episode episode : changedEpisodes) {
169                                 stringBuilder.append("- ").append(episode.identifier()).append("\n");
170                                 for (TorrentFile torrentFile : episode) {
171                                         stringBuilder.append("  - ").append(torrentFile.name()).append(", ").append(torrentFile.size()).append("\n");
172                                         if ((torrentFile.magnetUri() != null) && (torrentFile.magnetUri().length() > 0)) {
173                                                 stringBuilder.append("    Magnet: ").append(torrentFile.magnetUri()).append("\n");
174                                         }
175                                         if ((torrentFile.downloadUri() != null) && (torrentFile.downloadUri().length() > 0)) {
176                                                 stringBuilder.append("    Download: ").append(torrentFile.downloadUri()).append("\n");
177                                         }
178                                 }
179                         }
180                 }
181                 /* list all known episodes. */
182                 stringBuilder.append(reaction.name()).append(" - All Known Episodes\n\n");
183                 ImmutableMap<Integer, Collection<Episode>> episodesBySeason = FluentIterable.from(allEpisodes).index(new Function<Episode, Integer>() {
184
185                         @Override
186                         public Integer apply(Episode episode) {
187                                 return episode.season();
188                         }
189                 }).asMap();
190                 for (Entry<Integer, Collection<Episode>> seasonEntry : episodesBySeason.entrySet()) {
191                         stringBuilder.append("  Season ").append(seasonEntry.getKey()).append("\n\n");
192                         for (Episode episode : Ordering.natural().sortedCopy(seasonEntry.getValue())) {
193                                 stringBuilder.append("    Episode ").append(episode.episode()).append("\n");
194                                 for (TorrentFile torrentFile : episode) {
195                                         stringBuilder.append("      Size: ").append(torrentFile.size());
196                                         stringBuilder.append(" in ").append(torrentFile.fileCount()).append(" file(s): ");
197                                         stringBuilder.append(torrentFile.magnetUri());
198                                 }
199                         }
200                 }
201
202                 return stringBuilder.toString();
203         }
204
205         /**
206          * Generates the HTML trigger output.
207          *
208          * @param reaction
209          *            The reaction that was triggered
210          * @return The HTML output
211          */
212         private String generateHtmlText(Reaction reaction) {
213                 StringBuilder htmlBuilder = new StringBuilder();
214                 htmlBuilder.append("<html><body>\n");
215                 /* show all known episodes. */
216                 htmlBuilder.append("<table>\n<caption>All Known Episodes</caption>\n");
217                 htmlBuilder.append("<thead>\n");
218                 htmlBuilder.append("<tr>");
219                 htmlBuilder.append("<th>Season</th>");
220                 htmlBuilder.append("<th>Episode</th>");
221                 htmlBuilder.append("<th>Filename</th>");
222                 htmlBuilder.append("<th>Size</th>");
223                 htmlBuilder.append("<th>File(s)</th>");
224                 htmlBuilder.append("<th>Seeds</th>");
225                 htmlBuilder.append("<th>Leechers</th>");
226                 htmlBuilder.append("<th>Magnet</th>");
227                 htmlBuilder.append("<th>Download</th>");
228                 htmlBuilder.append("</tr>\n");
229                 htmlBuilder.append("</thead>\n");
230                 htmlBuilder.append("<tbody>\n");
231                 Episode lastEpisode = null;
232                 for (Entry<Integer, Collection<Episode>> seasonEntry : FluentIterable.from(Ordering.natural().reverse().sortedCopy(allEpisodes)).index(Episode.BY_SEASON).asMap().entrySet()) {
233                         for (Episode episode : seasonEntry.getValue()) {
234                                 for (TorrentFile torrentFile : episode) {
235                                         if (newEpisodes.contains(episode)) {
236                                                 htmlBuilder.append("<tr style=\"color: #008000; font-weight: bold;\">");
237                                         } else if (newTorrentFiles.contains(torrentFile)) {
238                                                 htmlBuilder.append("<tr style=\"color: #008000;\">");
239                                         } else {
240                                                 htmlBuilder.append("<tr>");
241                                         }
242                                         if ((lastEpisode == null) || !lastEpisode.equals(episode)) {
243                                                 htmlBuilder.append("<td>").append(episode.season()).append("</td><td>").append(episode.episode()).append("</td>");
244                                         } else {
245                                                 htmlBuilder.append("<td colspan=\"2\"></td>");
246                                         }
247                                         htmlBuilder.append("<td>").append(StringEscapeUtils.escapeHtml4(torrentFile.name())).append("</td>");
248                                         htmlBuilder.append("<td>").append(StringEscapeUtils.escapeHtml4(torrentFile.size())).append("</td>");
249                                         htmlBuilder.append("<td>").append(torrentFile.fileCount()).append("</td>");
250                                         htmlBuilder.append("<td>").append(torrentFile.seedCount()).append("</td>");
251                                         htmlBuilder.append("<td>").append(torrentFile.leechCount()).append("</td>");
252                                         htmlBuilder.append("<td><a href=\"").append(StringEscapeUtils.escapeHtml4(torrentFile.magnetUri())).append("\">Link</a></td>");
253                                         htmlBuilder.append("<td><a href=\"").append(StringEscapeUtils.escapeHtml4(torrentFile.downloadUri())).append("\">Link</a></td>");
254                                         htmlBuilder.append("</tr>\n");
255                                         lastEpisode = episode;
256                                 }
257                         }
258                 }
259                 htmlBuilder.append("</tbody>\n");
260                 htmlBuilder.append("</table>\n");
261                 htmlBuilder.append("</body></html>\n");
262                 return htmlBuilder.toString();
263         }
264
265 }