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 java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.HashSet;
25 import java.util.List;
27 import java.util.concurrent.TimeUnit;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
31 import net.pterodactylus.sone.data.Post;
32 import net.pterodactylus.sone.data.PostReply;
33 import net.pterodactylus.sone.data.Profile;
34 import net.pterodactylus.sone.data.Profile.Field;
35 import net.pterodactylus.sone.data.Reply;
36 import net.pterodactylus.sone.data.Sone;
37 import net.pterodactylus.sone.web.page.FreenetRequest;
38 import net.pterodactylus.util.collection.Pagination;
39 import net.pterodactylus.util.logging.Logging;
40 import net.pterodactylus.util.number.Numbers;
41 import net.pterodactylus.util.template.Template;
42 import net.pterodactylus.util.template.TemplateContext;
43 import net.pterodactylus.util.text.StringEscaper;
44 import net.pterodactylus.util.text.TextException;
46 import com.google.common.base.Function;
47 import com.google.common.base.Predicate;
48 import com.google.common.cache.CacheBuilder;
49 import com.google.common.cache.CacheLoader;
50 import com.google.common.cache.LoadingCache;
51 import com.google.common.collect.Collections2;
52 import com.google.common.collect.FluentIterable;
53 import com.google.common.collect.Ordering;
56 * This page lets the user search for posts and replies that contain certain
59 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
61 public class SearchPage extends SoneTemplatePage {
64 private static final Logger logger = Logging.getLogger(SearchPage.class);
66 /** Short-term cache. */
67 private final LoadingCache<List<Phrase>, Set<Hit<Post>>> hitCache = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.MINUTES).build(new CacheLoader<List<Phrase>, Set<Hit<Post>>>() {
70 @SuppressWarnings("synthetic-access")
71 public Set<Hit<Post>> load(List<Phrase> phrases) {
72 Set<Post> posts = new HashSet<Post>();
73 for (Sone sone : webInterface.getCore().getSones()) {
74 posts.addAll(sone.getPosts());
76 return getHits(Collections2.filter(posts, Post.FUTURE_POSTS_FILTER), phrases, new PostStringGenerator());
81 * Creates a new search page.
84 * The template to render
86 * The Sone web interface
88 public SearchPage(Template template, WebInterface webInterface) {
89 super("search.html", template, "Page.Search.Title", webInterface);
93 // SONETEMPLATEPAGE METHODS
100 @SuppressWarnings("synthetic-access")
101 protected void processTemplate(FreenetRequest request, TemplateContext templateContext) throws RedirectException {
102 super.processTemplate(request, templateContext);
103 String query = request.getHttpRequest().getParam("query").trim();
104 if (query.length() == 0) {
105 throw new RedirectException("index.html");
108 List<Phrase> phrases = parseSearchPhrases(query);
109 if (phrases.isEmpty()) {
110 throw new RedirectException("index.html");
113 /* check for a couple of shortcuts. */
114 if (phrases.size() == 1) {
115 String phrase = phrases.get(0).getPhrase();
117 /* is it a Sone ID? */
118 redirectIfNotNull(getSoneId(phrase), "viewSone.html?sone=");
120 /* is it a post ID? */
121 redirectIfNotNull(getPostId(phrase), "viewPost.html?post=");
123 /* is it a reply ID? show the post. */
124 redirectIfNotNull(getReplyPostId(phrase), "viewPost.html?post=");
126 /* is it an album ID? */
127 redirectIfNotNull(getAlbumId(phrase), "imageBrowser.html?album=");
129 /* is it an image ID? */
130 redirectIfNotNull(getImageId(phrase), "imageBrowser.html?image=");
133 Set<Sone> sones = webInterface.getCore().getSones();
134 Collection<Hit<Sone>> soneHits = getHits(sones, phrases, SoneStringGenerator.COMPLETE_GENERATOR);
136 Collection<Hit<Post>> postHits = hitCache.getUnchecked(phrases);
139 soneHits = Collections2.filter(soneHits, Hit.POSITIVE_FILTER);
140 postHits = Collections2.filter(postHits, Hit.POSITIVE_FILTER);
143 List<Hit<Sone>> sortedSoneHits = Ordering.from(Hit.DESCENDING_COMPARATOR).sortedCopy(soneHits);
144 List<Hit<Post>> sortedPostHits = Ordering.from(Hit.DESCENDING_COMPARATOR).sortedCopy(postHits);
146 /* extract Sones and posts. */
147 List<Sone> resultSones = FluentIterable.from(sortedSoneHits).transform(new HitMapper<Sone>()).toList();
148 List<Post> resultPosts = FluentIterable.from(sortedPostHits).transform(new HitMapper<Post>()).toList();
151 Pagination<Sone> sonePagination = new Pagination<Sone>(resultSones, webInterface.getCore().getPreferences().getPostsPerPage()).setPage(Numbers.safeParseInteger(request.getHttpRequest().getParam("sonePage"), 0));
152 Pagination<Post> postPagination = new Pagination<Post>(resultPosts, webInterface.getCore().getPreferences().getPostsPerPage()).setPage(Numbers.safeParseInteger(request.getHttpRequest().getParam("postPage"), 0));
154 templateContext.set("sonePagination", sonePagination);
155 templateContext.set("soneHits", sonePagination.getItems());
156 templateContext.set("postPagination", postPagination);
157 templateContext.set("postHits", postPagination.getItems());
165 * Collects hit information for the given objects. The objects are converted
166 * to a {@link String} using the given {@link StringGenerator}, and the
167 * {@link #calculateScore(List, String) calculated score} is stored together
168 * with the object in a {@link Hit}, and all resulting {@link Hit}s are then
172 * The type of the objects
174 * The objects to search over
176 * The phrases to search for
177 * @param stringGenerator
178 * The string generator for the objects
179 * @return The hits for the given phrases
181 private static <T> Set<Hit<T>> getHits(Collection<T> objects, List<Phrase> phrases, StringGenerator<T> stringGenerator) {
182 Set<Hit<T>> hits = new HashSet<Hit<T>>();
183 for (T object : objects) {
184 String objectString = stringGenerator.generateString(object);
185 double score = calculateScore(phrases, objectString);
186 hits.add(new Hit<T>(object, score));
192 * Parses the given query into search phrases. The query is split on
193 * whitespace while allowing to group words using single or double quotes.
194 * Isolated phrases starting with a “+” are
195 * {@link Phrase.Optionality#REQUIRED}, phrases with a “-” are
196 * {@link Phrase.Optionality#FORBIDDEN}.
200 * @return The parsed phrases
202 private static List<Phrase> parseSearchPhrases(String query) {
203 List<String> parsedPhrases = null;
205 parsedPhrases = StringEscaper.parseLine(query);
206 } catch (TextException te1) {
208 return Collections.emptyList();
211 List<Phrase> phrases = new ArrayList<Phrase>();
212 for (String phrase : parsedPhrases) {
213 if (phrase.startsWith("+")) {
214 if (phrase.length() > 1) {
215 phrases.add(new Phrase(phrase.substring(1), Phrase.Optionality.REQUIRED));
217 phrases.add(new Phrase("+", Phrase.Optionality.OPTIONAL));
219 } else if (phrase.startsWith("-")) {
220 if (phrase.length() > 1) {
221 phrases.add(new Phrase(phrase.substring(1), Phrase.Optionality.FORBIDDEN));
223 phrases.add(new Phrase("-", Phrase.Optionality.OPTIONAL));
226 phrases.add(new Phrase(phrase, Phrase.Optionality.OPTIONAL));
233 * Calculates the score for the given expression when using the given
237 * The phrases to search for
239 * The expression to search
240 * @return The score of the expression
242 private static double calculateScore(List<Phrase> phrases, String expression) {
243 logger.log(Level.FINEST, String.format("Calculating Score for “%s”…", expression));
244 double optionalHits = 0;
245 double requiredHits = 0;
246 int forbiddenHits = 0;
247 int requiredPhrases = 0;
248 for (Phrase phrase : phrases) {
249 String phraseString = phrase.getPhrase().toLowerCase();
250 if (phrase.getOptionality() == Phrase.Optionality.REQUIRED) {
256 while (index < expression.length()) {
257 int position = expression.toLowerCase().indexOf(phraseString, index);
258 if (position == -1) {
261 score += Math.pow(1 - position / (double) expression.length(), 2);
262 index = position + phraseString.length();
263 logger.log(Level.FINEST, String.format("Got hit at position %d.", position));
266 logger.log(Level.FINEST, String.format("Score: %f", score));
270 if (phrase.getOptionality() == Phrase.Optionality.REQUIRED) {
271 requiredHits += score;
273 if (phrase.getOptionality() == Phrase.Optionality.OPTIONAL) {
274 optionalHits += score;
276 if (phrase.getOptionality() == Phrase.Optionality.FORBIDDEN) {
277 forbiddenHits += matches;
280 return requiredHits * 3 + optionalHits + (requiredHits - requiredPhrases) * 5 - (forbiddenHits * 2);
285 * {@link net.pterodactylus.sone.web.page.FreenetTemplatePage.RedirectException}
286 * if the given object is not {@code null}, appending the object to the
290 * The object on which to redirect
292 * The target of the redirect
293 * @throws RedirectException
294 * if {@code object} is not {@code null}
296 private static void redirectIfNotNull(String object, String target) throws RedirectException {
297 if (object != null) {
298 throw new RedirectException(target + object);
303 * If the given phrase contains a Sone ID (optionally prefixed by
304 * “sone://”), returns said Sone ID, otherwise return {@code null}.
307 * The phrase that maybe is a Sone ID
308 * @return The Sone ID, or {@code null}
310 private String getSoneId(String phrase) {
311 String soneId = phrase.startsWith("sone://") ? phrase.substring(7) : phrase;
312 return (webInterface.getCore().getSone(soneId) != null) ? soneId : null;
316 * If the given phrase contains a post ID (optionally prefixed by
317 * “post://”), returns said post ID, otherwise return {@code null}.
320 * The phrase that maybe is a post ID
321 * @return The post ID, or {@code null}
323 private String getPostId(String phrase) {
324 String postId = phrase.startsWith("post://") ? phrase.substring(7) : phrase;
325 return (webInterface.getCore().getPost(postId) != null) ? postId : null;
329 * If the given phrase contains a reply ID (optionally prefixed by
330 * “reply://”), returns the ID of the post the reply belongs to, otherwise
331 * return {@code null}.
334 * The phrase that maybe is a reply ID
335 * @return The reply’s post ID, or {@code null}
337 private String getReplyPostId(String phrase) {
338 String replyId = phrase.startsWith("reply://") ? phrase.substring(8) : phrase;
339 return (webInterface.getCore().getPostReply(replyId) != null) ? webInterface.getCore().getPostReply(replyId).getPost().getId() : null;
343 * If the given phrase contains an album ID (optionally prefixed by
344 * “album://”), returns said album ID, otherwise return {@code null}.
347 * The phrase that maybe is an album ID
348 * @return The album ID, or {@code null}
350 private String getAlbumId(String phrase) {
351 String albumId = phrase.startsWith("album://") ? phrase.substring(8) : phrase;
352 return (webInterface.getCore().getAlbum(albumId, false) != null) ? albumId : null;
356 * If the given phrase contains an image ID (optionally prefixed by
357 * “image://”), returns said image ID, otherwise return {@code null}.
360 * The phrase that maybe is an image ID
361 * @return The image ID, or {@code null}
363 private String getImageId(String phrase) {
364 String imageId = phrase.startsWith("image://") ? phrase.substring(8) : phrase;
365 return (webInterface.getCore().getImage(imageId, false) != null) ? imageId : null;
369 * Converts a given object into a {@link String}.
372 * The type of the objects
373 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
375 private static interface StringGenerator<T> {
378 * Generates a {@link String} for the given object.
381 * The object to generate the {@link String} for
382 * @return The generated {@link String}
384 public String generateString(T object);
389 * Generates a {@link String} from a {@link Sone}, concatenating the name of
390 * the Sone and all {@link Profile} {@link Field} values.
392 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
394 private static class SoneStringGenerator implements StringGenerator<Sone> {
396 /** A static instance of a complete Sone string generator. */
397 public static final SoneStringGenerator COMPLETE_GENERATOR = new SoneStringGenerator(true);
400 * A static instance of a Sone string generator that will only use the
403 public static final SoneStringGenerator NAME_GENERATOR = new SoneStringGenerator(false);
405 /** Whether to generate a string from all data of a Sone. */
406 private final boolean complete;
409 * Creates a new Sone string generator.
412 * {@code true} to use the profile’s fields, {@code false} to
413 * not to use the profile‘s fields
415 private SoneStringGenerator(boolean complete) {
416 this.complete = complete;
423 public String generateString(Sone sone) {
424 StringBuilder soneString = new StringBuilder();
425 soneString.append(sone.getName());
426 Profile soneProfile = sone.getProfile();
427 if (soneProfile.getFirstName() != null) {
428 soneString.append(' ').append(soneProfile.getFirstName());
430 if (soneProfile.getMiddleName() != null) {
431 soneString.append(' ').append(soneProfile.getMiddleName());
433 if (soneProfile.getLastName() != null) {
434 soneString.append(' ').append(soneProfile.getLastName());
437 for (Field field : soneProfile.getFields()) {
438 soneString.append(' ').append(field.getValue());
441 return soneString.toString();
447 * Generates a {@link String} from a {@link Post}, concatenating the text of
448 * the post, the text of all {@link Reply}s, and the name of all
449 * {@link Sone}s that have replied.
451 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
453 private class PostStringGenerator implements StringGenerator<Post> {
459 public String generateString(Post post) {
460 StringBuilder postString = new StringBuilder();
461 postString.append(post.getText());
462 if (post.getRecipient() != null) {
463 postString.append(' ').append(SoneStringGenerator.NAME_GENERATOR.generateString(post.getRecipient()));
465 for (PostReply reply : Collections2.filter(webInterface.getCore().getReplies(post), Reply.FUTURE_REPLY_FILTER)) {
466 postString.append(' ').append(SoneStringGenerator.NAME_GENERATOR.generateString(reply.getSone()));
467 postString.append(' ').append(reply.getText());
469 return postString.toString();
477 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
479 private static class Phrase {
482 * The optionality of a search phrase.
484 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’
487 public enum Optionality {
489 /** The phrase is optional. */
492 /** The phrase is required. */
495 /** The phrase is forbidden. */
500 /** The phrase to search for. */
501 private final String phrase;
503 /** The optionality of the phrase. */
504 private final Optionality optionality;
507 * Creates a new phrase.
510 * The phrase to search for
512 * The optionality of the phrase
514 public Phrase(String phrase, Optionality optionality) {
515 this.optionality = optionality;
516 this.phrase = phrase;
520 * Returns the phrase to search for.
522 * @return The phrase to search for
524 public String getPhrase() {
529 * Returns the optionality of the phrase.
531 * @return The optionality of the phrase
533 public Optionality getOptionality() {
545 public int hashCode() {
546 return phrase.hashCode() ^ ((optionality == Optionality.FORBIDDEN) ? (0xaaaaaaaa) : ((optionality == Optionality.REQUIRED) ? 0x55555555 : 0));
553 public boolean equals(Object object) {
554 if (!(object instanceof Phrase)) {
557 Phrase phrase = (Phrase) object;
558 return (this.optionality == phrase.optionality) && this.phrase.equals(phrase.phrase);
564 * A hit consists of a searched object and the score it got for the phrases
567 * @see SearchPage#calculateScore(List, String)
569 * The type of the searched object
570 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
572 private static class Hit<T> {
574 /** Filter for {@link Hit}s with a score of more than 0. */
575 public static final Predicate<Hit<?>> POSITIVE_FILTER = new Predicate<Hit<?>>() {
578 public boolean apply(Hit<?> hit) {
579 return hit.getScore() > 0;
584 /** Comparator that sorts {@link Hit}s descending by score. */
585 public static final Comparator<Hit<?>> DESCENDING_COMPARATOR = new Comparator<Hit<?>>() {
588 public int compare(Hit<?> leftHit, Hit<?> rightHit) {
589 return (rightHit.getScore() < leftHit.getScore()) ? -1 : ((rightHit.getScore() > leftHit.getScore()) ? 1 : 0);
594 /** The object that was searched. */
595 private final T object;
597 /** The score of the object. */
598 private final double score;
604 * The object that was searched
606 * The score of the object
608 public Hit(T object, double score) {
609 this.object = object;
614 * Returns the object that was searched.
616 * @return The object that was searched
618 public T getObject() {
623 * Returns the score of the object.
625 * @return The score of the object
627 public double getScore() {
634 * Extracts the object from a {@link Hit}.
637 * The type of the object to extract
638 * @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
640 private static class HitMapper<T> implements Function<Hit<T>, T> {
646 public T apply(Hit<T> input) {
647 return input.getObject();