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