🔀 Merge branch 'website/epic-games' into next
[rhynodge.git] / src / main / java / net / pterodactylus / rhynodge / filters / EpisodeFilter.java
1 /*
2  * Rhynodge - EpisodeFilter.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.filters;
19
20 import static com.google.common.base.Optional.absent;
21 import static com.google.common.base.Preconditions.checkState;
22 import static com.google.common.collect.FluentIterable.from;
23 import static java.util.Arrays.asList;
24
25 import java.util.Collection;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 import net.pterodactylus.rhynodge.Filter;
30 import net.pterodactylus.rhynodge.State;
31 import net.pterodactylus.rhynodge.states.EpisodeState;
32 import net.pterodactylus.rhynodge.states.EpisodeState.Episode;
33 import net.pterodactylus.rhynodge.states.FailedState;
34 import net.pterodactylus.rhynodge.states.TorrentState;
35 import net.pterodactylus.rhynodge.states.TorrentState.TorrentFile;
36
37 import com.google.common.base.Function;
38 import com.google.common.base.Optional;
39 import com.google.common.collect.HashMultimap;
40 import com.google.common.collect.Multimap;
41 import org.apache.log4j.Logger;
42 import org.jetbrains.annotations.NotNull;
43
44 /**
45  * {@link Filter} implementation that extracts {@link Episode} information from
46  * the {@link TorrentFile}s contained in a {@link TorrentState}.
47  *
48  * @author <a href="mailto:bombe@pterodactylus.net">David â€˜Bombe’ Roden</a>
49  */
50 public class EpisodeFilter implements Filter {
51
52         private static final Logger logger = Logger.getLogger(EpisodeFilter.class);
53
54         /** The pattern to parse episode information from the filename. */
55         private static final Collection<Pattern> episodePatterns = asList(Pattern.compile("[Ss](\\d{2})[Ee](\\d{2})"), Pattern.compile("[^\\d](\\d{1,2})x(\\d{2})[^\\d]"));
56
57         //
58         // FILTER METHODS
59         //
60
61         /**
62          * {@inheritDoc}
63          */
64         @NotNull
65         @Override
66         public State filter(@NotNull State state) {
67                 if (!state.success()) {
68                         return FailedState.from(state);
69                 }
70                 checkState(state instanceof TorrentState, "state is not a TorrentState but a %s!", state.getClass());
71
72                 TorrentState torrentState = (TorrentState) state;
73                 final Multimap<Episode, TorrentFile> episodes = HashMultimap.create();
74                 for (TorrentFile torrentFile : torrentState) {
75                         Optional<Episode> episode = extractEpisode(torrentFile);
76                         if (!episode.isPresent()) {
77                                 continue;
78                         }
79                         episodes.put(episode.get(), torrentFile);
80                 }
81
82                 return new EpisodeState(from(episodes.keySet()).transform(episodeFiller(episodes)).toSet());
83         }
84
85         //
86         // STATIC METHODS
87         //
88
89         /**
90          * Returns a function that creates an {@link Episode} that contains all {@link
91          * TorrentFile}s.
92          *
93          * @param episodeTorrents
94          *              A multimap mapping episodes to torrent files.
95          * @return The function that performs the extraction of torrent files
96          */
97         private static Function<Episode, Episode> episodeFiller(final Multimap<Episode, TorrentFile> episodeTorrents) {
98                 return new Function<Episode, Episode>() {
99                         @Override
100                         public Episode apply(Episode episode) {
101                                 Episode completeEpisode = new Episode(episode.season(), episode.episode());
102                                 for (TorrentFile torrentFile : episodeTorrents.get(episode)) {
103                                         completeEpisode.addTorrentFile(torrentFile);
104                                 }
105                                 return completeEpisode;
106                         }
107                 };
108         }
109
110         /**
111          * Extracts episode information from the given torrent file.
112          *
113          * @param torrentFile
114          *              The torrent file to extract the episode information from
115          * @return The extracted episode information, or {@link Optional#absent()} if
116          *         no episode information could be found
117          */
118         private static Optional<Episode> extractEpisode(TorrentFile torrentFile) {
119                 logger.debug(String.format("Extracting episode from %s...", torrentFile));
120                 for (Pattern episodePattern : episodePatterns) {
121                         Matcher matcher = episodePattern.matcher(torrentFile.name());
122                         if (!matcher.find() || matcher.groupCount() < 2) {
123                                 continue;
124                         }
125                         String seasonString = matcher.group(1);
126                         String episodeString = matcher.group(2);
127                         logger.debug(String.format("Parsing %s and %s as season and episode...", seasonString, episodeString));
128                         int season = Integer.valueOf(seasonString);
129                         int episode = Integer.valueOf(episodeString);
130                         return Optional.of(new Episode(season, episode));
131                 }
132                 return absent();
133         }
134
135 }