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