2 * Sone - SearchPage.java - Copyright © 2010–2013 David Roden
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.
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.
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/>.
18 package net.pterodactylus.sone.web;
20 import static com.google.common.base.Optional.fromNullable;
21 import static com.google.common.primitives.Ints.tryParse;
22 import static java.util.logging.Logger.getLogger;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Comparator;
28 import java.util.HashSet;
29 import java.util.List;
31 import java.util.concurrent.TimeUnit;
32 import java.util.logging.Level;
33 import java.util.logging.Logger;
35 import net.pterodactylus.sone.data.Album;
36 import net.pterodactylus.sone.data.Post;
37 import net.pterodactylus.sone.data.PostReply;
38 import net.pterodactylus.sone.data.Profile;
39 import net.pterodactylus.sone.data.Profile.Field;
40 import net.pterodactylus.sone.data.Reply;
41 import net.pterodactylus.sone.data.Sone;
42 import net.pterodactylus.sone.web.page.FreenetRequest;
43 import net.pterodactylus.util.collection.Pagination;
44 import net.pterodactylus.util.template.Template;
45 import net.pterodactylus.util.template.TemplateContext;
46 import net.pterodactylus.util.text.StringEscaper;
47 import net.pterodactylus.util.text.TextException;
49 import com.google.common.base.Function;
50 import com.google.common.base.Optional;
51 import com.google.common.base.Predicate;
52 import com.google.common.cache.CacheBuilder;
53 import com.google.common.cache.CacheLoader;
54 import com.google.common.cache.LoadingCache;
55 import com.google.common.collect.Collections2;
56 import com.google.common.collect.FluentIterable;
57 import com.google.common.collect.Ordering;
60 * This page lets the user search for posts and replies that contain certain
63 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
65 public class SearchPage extends SoneTemplatePage {
68 private static final Logger logger = getLogger(SearchPage.class.getName());
70 /** Short-term cache. */
71 private final LoadingCache<List<Phrase>, Set<Hit<Post>>> hitCache = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.MINUTES).build(new CacheLoader<List<Phrase>, Set<Hit<Post>>>() {
74 @SuppressWarnings("synthetic-access")
75 public Set<Hit<Post>> load(List<Phrase> phrases) {
76 Set<Post> posts = new HashSet<Post>();
77 for (Sone sone : webInterface.getCore().getSones()) {
78 posts.addAll(sone.getPosts());
80 return getHits(Collections2.filter(posts, Post.FUTURE_POSTS_FILTER), phrases, new PostStringGenerator());
85 * Creates a new search page.
88 * The template to render
90 * The Sone web interface
92 public SearchPage(Template template, WebInterface webInterface) {
93 super("search.html", template, "Page.Search.Title", webInterface);
97 // SONETEMPLATEPAGE METHODS
104 @SuppressWarnings("synthetic-access")
105 protected void processTemplate(FreenetRequest request, TemplateContext templateContext) throws RedirectException {
106 super.processTemplate(request, templateContext);
107 String query = request.getHttpRequest().getParam("query").trim();
108 if (query.length() == 0) {
109 throw new RedirectException("index.html");
112 List<Phrase> phrases = parseSearchPhrases(query);
113 if (phrases.isEmpty()) {
114 throw new RedirectException("index.html");
117 /* check for a couple of shortcuts. */
118 if (phrases.size() == 1) {
119 String phrase = phrases.get(0).getPhrase();
121 /* is it a Sone ID? */
122 redirectIfNotNull(getSoneId(phrase), "viewSone.html?sone=");
124 /* is it a post ID? */
125 redirectIfNotNull(getPostId(phrase), "viewPost.html?post=");
127 /* is it a reply ID? show the post. */
128 redirectIfNotNull(getReplyPostId(phrase), "viewPost.html?post=");
130 /* is it an album ID? */
131 redirectIfNotNull(getAlbumId(phrase), "imageBrowser.html?album=");
133 /* is it an image ID? */
134 redirectIfNotNull(getImageId(phrase), "imageBrowser.html?image=");
137 Collection<Sone> sones = webInterface.getCore().getSones();
138 Collection<Hit<Sone>> soneHits = getHits(sones, phrases, SoneStringGenerator.COMPLETE_GENERATOR);
140 Collection<Hit<Post>> postHits = hitCache.getUnchecked(phrases);
143 soneHits = Collections2.filter(soneHits, Hit.POSITIVE_FILTER);
144 postHits = Collections2.filter(postHits, Hit.POSITIVE_FILTER);
147 List<Hit<Sone>> sortedSoneHits = Ordering.from(Hit.DESCENDING_COMPARATOR).sortedCopy(soneHits);
148 List<Hit<Post>> sortedPostHits = Ordering.from(Hit.DESCENDING_COMPARATOR).sortedCopy(postHits);
150 /* extract Sones and posts. */
151 List<Sone> resultSones = FluentIterable.from(sortedSoneHits).transform(new HitMapper<Sone>()).toList();
152 List<Post> resultPosts = FluentIterable.from(sortedPostHits).transform(new HitMapper<Post>()).toList();
155 Pagination<Sone> sonePagination = new Pagination<Sone>(resultSones, webInterface.getCore().getPreferences().getPostsPerPage()).setPage(fromNullable(tryParse(request.getHttpRequest().getParam("sonePage"))).or(0));
156 Pagination<Post> postPagination = new Pagination<Post>(resultPosts, webInterface.getCore().getPreferences().getPostsPerPage()).setPage(fromNullable(tryParse(request.getHttpRequest().getParam("postPage"))).or(0));
158 templateContext.set("sonePagination", sonePagination);
159 templateContext.set("soneHits", sonePagination.getItems());
160 templateContext.set("postPagination", postPagination);
161 templateContext.set("postHits", postPagination.getItems());
169 * Collects hit information for the given objects. The objects are converted
170 * to a {@link String} using the given {@link StringGenerator}, and the
171 * {@link #calculateScore(List, String) calculated score} is stored together
172 * with the object in a {@link Hit}, and all resulting {@link Hit}s are then
176 * The type of the objects
178 * The objects to search over
180 * The phrases to search for
181 * @param stringGenerator
182 * The string generator for the objects
183 * @return The hits for the given phrases
185 private static <T> Set<Hit<T>> getHits(Collection<T> objects, List<Phrase> phrases, StringGenerator<T> stringGenerator) {
186 Set<Hit<T>> hits = new HashSet<Hit<T>>();
187 for (T object : objects) {
188 String objectString = stringGenerator.generateString(object);
189 double score = calculateScore(phrases, objectString);
190 hits.add(new Hit<T>(object, score));
196 * Parses the given query into search phrases. The query is split on
197 * whitespace while allowing to group words using single or double quotes.
198 * Isolated phrases starting with a “+” are
199 * {@link Phrase.Optionality#REQUIRED}, phrases with a “-” are
200 * {@link Phrase.Optionality#FORBIDDEN}.
204 * @return The parsed phrases
206 private static List<Phrase> parseSearchPhrases(String query) {
207 List<String> parsedPhrases;
209 parsedPhrases = StringEscaper.parseLine(query);
210 } catch (TextException te1) {
212 return Collections.emptyList();
215 List<Phrase> phrases = new ArrayList<Phrase>();
216 for (String phrase : parsedPhrases) {
217 if (phrase.startsWith("+")) {
218 if (phrase.length() > 1) {
219 phrases.add(new Phrase(phrase.substring(1), Phrase.Optionality.REQUIRED));
221 phrases.add(new Phrase("+", Phrase.Optionality.OPTIONAL));
223 } else if (phrase.startsWith("-")) {
224 if (phrase.length() > 1) {
225 phrases.add(new Phrase(phrase.substring(1), Phrase.Optionality.FORBIDDEN));
227 phrases.add(new Phrase("-", Phrase.Optionality.OPTIONAL));
230 phrases.add(new Phrase(phrase, Phrase.Optionality.OPTIONAL));
237 * Calculates the score for the given expression when using the given
241 * The phrases to search for
243 * The expression to search
244 * @return The score of the expression
246 private static double calculateScore(List<Phrase> phrases, String expression) {
247 logger.log(Level.FINEST, String.format("Calculating Score for “%s”…", expression));
248 double optionalHits = 0;
249 double requiredHits = 0;
250 int forbiddenHits = 0;
251 int requiredPhrases = 0;
252 for (Phrase phrase : phrases) {
253 String phraseString = phrase.getPhrase().toLowerCase();
254 if (phrase.getOptionality() == Phrase.Optionality.REQUIRED) {
260 while (index < expression.length()) {
261 int position = expression.toLowerCase().indexOf(phraseString, index);
262 if (position == -1) {
265 score += Math.pow(1 - position / (double) expression.length(), 2);
266 index = position + phraseString.length();
267 logger.log(Level.FINEST, String.format("Got hit at position %d.", position));
270 logger.log(Level.FINEST, String.format("Score: %f", score));
274 if (phrase.getOptionality() == Phrase.Optionality.REQUIRED) {
275 requiredHits += score;
277 if (phrase.getOptionality() == Phrase.Optionality.OPTIONAL) {
278 optionalHits += score;
280 if (phrase.getOptionality() == Phrase.Optionality.FORBIDDEN) {
281 forbiddenHits += matches;
284 return requiredHits * 3 + optionalHits + (requiredHits - requiredPhrases) * 5 - (forbiddenHits * 2);
289 * {@link net.pterodactylus.sone.web.page.FreenetTemplatePage.RedirectException}
290 * if the given object is not {@code null}, appending the object to the
294 * The object on which to redirect
296 * The target of the redirect
297 * @throws RedirectException
298 * if {@code object} is not {@code null}
300 private static void redirectIfNotNull(String object, String target) throws RedirectException {
301 if (object != null) {
302 throw new RedirectException(target + object);
307 * If the given phrase contains a Sone ID (optionally prefixed by
308 * “sone://”), returns said Sone ID, otherwise return {@code null}.
311 * The phrase that maybe is a Sone ID
312 * @return The Sone ID, or {@code null}
314 private String getSoneId(String phrase) {
315 String soneId = phrase.startsWith("sone://") ? phrase.substring(7) : phrase;
316 return (webInterface.getCore().getSone(soneId).isPresent()) ? soneId : null;
320 * If the given phrase contains a post ID (optionally prefixed by
321 * “post://”), returns said post ID, otherwise return {@code null}.
324 * The phrase that maybe is a post ID
325 * @return The post ID, or {@code null}
327 private String getPostId(String phrase) {
328 String postId = phrase.startsWith("post://") ? phrase.substring(7) : phrase;
329 return (webInterface.getCore().getPost(postId).isPresent()) ? postId : null;
333 * If the given phrase contains a reply ID (optionally prefixed by
334 * “reply://”), returns the ID of the post the reply belongs to, otherwise
335 * return {@code null}.
338 * The phrase that maybe is a reply ID
339 * @return The reply’s post ID, or {@code null}
341 private String getReplyPostId(String phrase) {
342 String replyId = phrase.startsWith("reply://") ? phrase.substring(8) : phrase;
343 Optional<PostReply> postReply = webInterface.getCore().getPostReply(replyId);
344 if (!postReply.isPresent()) {
347 return postReply.get().getPostId();
351 * If the given phrase contains an album ID (optionally prefixed by
352 * “album://”), returns said album ID, otherwise return {@code null}.
355 * The phrase that maybe is an album ID
356 * @return The album ID, or {@code null}
358 private String getAlbumId(String phrase) {
359 String albumId = phrase.startsWith("album://") ? phrase.substring(8) : phrase;
360 return webInterface.getCore().getAlbum(albumId).isPresent() ? albumId : null;
364 * If the given phrase contains an image ID (optionally prefixed by
365 * “image://”), returns said image ID, otherwise return {@code null}.
368 * The phrase that maybe is an image ID
369 * @return The image ID, or {@code null}
371 private String getImageId(String phrase) {
372 String imageId = phrase.startsWith("image://") ? phrase.substring(8) : phrase;
373 return (webInterface.getCore().getImage(imageId, false) != null) ? imageId : null;
377 * Converts a given object into a {@link String}.
380 * The type of the objects
381 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
383 private static interface StringGenerator<T> {
386 * Generates a {@link String} for the given object.
389 * The object to generate the {@link String} for
390 * @return The generated {@link String}
392 public String generateString(T object);
397 * Generates a {@link String} from a {@link Sone}, concatenating the name of
398 * the Sone and all {@link Profile} {@link Field} values.
400 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
402 private static class SoneStringGenerator implements StringGenerator<Sone> {
404 /** A static instance of a complete Sone string generator. */
405 public static final SoneStringGenerator COMPLETE_GENERATOR = new SoneStringGenerator(true);
408 * A static instance of a Sone string generator that will only use the
411 public static final SoneStringGenerator NAME_GENERATOR = new SoneStringGenerator(false);
413 /** Whether to generate a string from all data of a Sone. */
414 private final boolean complete;
417 * Creates a new Sone string generator.
420 * {@code true} to use the profile’s fields, {@code false} to
421 * not to use the profile‘s fields
423 private SoneStringGenerator(boolean complete) {
424 this.complete = complete;
431 public String generateString(Sone sone) {
432 StringBuilder soneString = new StringBuilder();
433 soneString.append(sone.getName());
434 Profile soneProfile = sone.getProfile();
435 if (soneProfile.getFirstName() != null) {
436 soneString.append(' ').append(soneProfile.getFirstName());
438 if (soneProfile.getMiddleName() != null) {
439 soneString.append(' ').append(soneProfile.getMiddleName());
441 if (soneProfile.getLastName() != null) {
442 soneString.append(' ').append(soneProfile.getLastName());
445 for (Field field : soneProfile.getFields()) {
446 soneString.append(' ').append(field.getValue());
449 return soneString.toString();
455 * Generates a {@link String} from a {@link Post}, concatenating the text of
456 * the post, the text of all {@link Reply}s, and the name of all
457 * {@link Sone}s that have replied.
459 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
461 private class PostStringGenerator implements StringGenerator<Post> {
467 public String generateString(Post post) {
468 StringBuilder postString = new StringBuilder();
469 postString.append(post.getText());
470 if (post.getRecipient().isPresent()) {
471 postString.append(' ').append(SoneStringGenerator.NAME_GENERATOR.generateString(post.getRecipient().get()));
473 for (PostReply reply : Collections2.filter(webInterface.getCore().getReplies(post.getId()), Reply.FUTURE_REPLY_FILTER)) {
474 postString.append(' ').append(SoneStringGenerator.NAME_GENERATOR.generateString(reply.getSone()));
475 postString.append(' ').append(reply.getText());
477 return postString.toString();
485 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
487 private static class Phrase {
490 * The optionality of a search phrase.
492 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
495 public enum Optionality {
497 /** The phrase is optional. */
500 /** The phrase is required. */
503 /** The phrase is forbidden. */
508 /** The phrase to search for. */
509 private final String phrase;
511 /** The optionality of the phrase. */
512 private final Optionality optionality;
515 * Creates a new phrase.
518 * The phrase to search for
520 * The optionality of the phrase
522 public Phrase(String phrase, Optionality optionality) {
523 this.optionality = optionality;
524 this.phrase = phrase;
528 * Returns the phrase to search for.
530 * @return The phrase to search for
532 public String getPhrase() {
537 * Returns the optionality of the phrase.
539 * @return The optionality of the phrase
541 public Optionality getOptionality() {
553 public int hashCode() {
554 return phrase.hashCode() ^ ((optionality == Optionality.FORBIDDEN) ? (0xaaaaaaaa) : ((optionality == Optionality.REQUIRED) ? 0x55555555 : 0));
561 public boolean equals(Object object) {
562 if (!(object instanceof Phrase)) {
565 Phrase phrase = (Phrase) object;
566 return (this.optionality == phrase.optionality) && this.phrase.equals(phrase.phrase);
572 * A hit consists of a searched object and the score it got for the phrases
575 * @see SearchPage#calculateScore(List, String)
577 * The type of the searched object
578 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
580 private static class Hit<T> {
582 /** Filter for {@link Hit}s with a score of more than 0. */
583 public static final Predicate<Hit<?>> POSITIVE_FILTER = new Predicate<Hit<?>>() {
586 public boolean apply(Hit<?> hit) {
587 return (hit != null) && (hit.getScore() > 0);
592 /** Comparator that sorts {@link Hit}s descending by score. */
593 public static final Comparator<Hit<?>> DESCENDING_COMPARATOR = new Comparator<Hit<?>>() {
596 public int compare(Hit<?> leftHit, Hit<?> rightHit) {
597 return (rightHit.getScore() < leftHit.getScore()) ? -1 : ((rightHit.getScore() > leftHit.getScore()) ? 1 : 0);
602 /** The object that was searched. */
603 private final T object;
605 /** The score of the object. */
606 private final double score;
612 * The object that was searched
614 * The score of the object
616 public Hit(T object, double score) {
617 this.object = object;
622 * Returns the object that was searched.
624 * @return The object that was searched
626 public T getObject() {
631 * Returns the score of the object.
633 * @return The score of the object
635 public double getScore() {
642 * Extracts the object from a {@link Hit}.
645 * The type of the object to extract
646 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
648 private static class HitMapper<T> implements Function<Hit<T>, T> {
654 public T apply(Hit<T> input) {
655 return input.getObject();