1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 from django.conf import settings
6 from django.shortcuts import render_to_response
7 from django.template import RequestContext
8 from django.views.decorators import cache
9 from django.http import HttpResponse, JsonResponse
11 from catalogue.utils import split_tags
12 from catalogue.models import Book, Tag
13 from search.index import Search, SearchResult
14 from suggest.forms import PublishingSuggestForm
18 from wolnelektury.utils import re_escape
21 def match_word_re(word):
22 if 'sqlite' in settings.DATABASES['default']['ENGINE']:
23 return r"\b%s\b" % word
24 elif 'mysql' in settings.DATABASES['default']['ENGINE']:
25 return "[[:<:]]%s[[:>:]]" % word
28 query_syntax_chars = re.compile(r"[\\/*:(){}]")
31 def remove_query_syntax_chars(query, replace=' '):
32 return query_syntax_chars.sub(replace, query)
35 def did_you_mean(query, tokens):
39 # authors = Tag.objects.filter(category='author', name__iregex=match_word_re(t))
40 # if len(authors) > 0:
44 # if not dictionary.check(t):
46 # change_to = dictionary.suggest(t)[0].lower()
47 # if change_to != t.lower():
48 # change[t] = change_to
55 # for frm, to in change.items():
56 # query = query.replace(frm, to)
63 prefix = request.GET.get('term', '')
65 return JsonResponse([], safe=False)
67 prefix = re_escape(' '.join(remove_query_syntax_chars(prefix).split()))
70 limit = int(request.GET.get('max', ''))
77 authors = Tag.objects.filter(
78 category='author', name_pl__iregex='\m' + prefix).only('name', 'id', 'slug', 'category')
83 'url': author.get_absolute_url(),
85 for author in authors[:limit]
91 'author': b.author_unicode(),
93 'url': b.get_absolute_url()
95 for b in Book.objects.filter(title__iregex='\m' + prefix)[:limit-len(data)]
97 callback = request.GET.get('callback', None)
99 return HttpResponse("%s(%s);" % (callback, json.dumps(data)),
100 content_type="application/json; charset=utf-8")
102 return JsonResponse(data, safe=False)
107 query = request.GET.get('q', '')
108 query = ' '.join(query.split())
109 # filter out private use characters
111 query = ''.join(ch for ch in query if unicodedata.category(ch) != 'Co')
114 return render_to_response(
115 'catalogue/search_too_short.html', {'prefix': query},
116 context_instance=RequestContext(request))
117 elif len(query) > 256:
118 return render_to_response(
119 'catalogue/search_too_long.html', {'prefix': query}, context_instance=RequestContext(request))
121 query = remove_query_syntax_chars(query)
123 words = query.split()
125 query = ' '.join(words[:10])
129 tags = search.hint_tags(query, pdcounter=True, prefix=False)
130 tags = split_tags(tags)
138 (['metadata'], True),
139 (['text', 'themes_pl'], False),
141 for fieldset, is_book in fieldsets:
142 search_fields += fieldset
143 results_parts.append(search.search_words(words, search_fields, book=is_book))
147 for results_part in results_parts:
148 for result in sorted(SearchResult.aggregate(results_part), reverse=True):
149 book_id = result.book_id
150 if book_id in ids_results:
151 ids_results[book_id].merge(result)
153 results.append(result)
154 ids_results[book_id] = result
156 for result in results:
157 search.get_snippets(result, query, num=3)
161 def ensure_exists(r):
164 except Book.DoesNotExist:
167 results = filter(ensure_exists, results)
170 form = PublishingSuggestForm(initial={"books": query + ", "})
171 return render_to_response(
172 'catalogue/search_no_hits.html',
177 'did_you_mean': suggestion
179 context_instance=RequestContext(request))
181 return render_to_response(
182 'catalogue/search_multiple_hits.html',
184 'tags': tags['author'] + tags['kind'] + tags['genre'] + tags['epoch'] + tags['theme'],
187 'did_you_mean': suggestion
189 context_instance=RequestContext(request))