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
10 from django.utils.translation import ugettext as _
12 from catalogue.utils import split_tags
13 from catalogue.models import Book
14 from pdcounter.models import Author as PDCounterAuthor, BookStub as PDCounterBook
15 from search.index import Search, SearchResult
16 from suggest.forms import PublishingSuggestForm
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(' ', 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 = remove_query_syntax_chars(prefix)
70 # tagi beda ograniczac tutaj
71 # ale tagi moga byc na ksiazce i na fragmentach
72 # jezeli tagi dot tylko ksiazki, to wazne zeby te nowe byly w tej samej ksiazce
73 # jesli zas dotycza themes, to wazne, zeby byly w tym samym fragmencie.
76 if isinstance(tag, PDCounterAuthor):
77 if filter(lambda t: t.slug == tag.slug and t != tag, tags):
79 elif isinstance(tag, PDCounterBook):
80 if filter(lambda b: b.slug == tag.slug, tags):
85 if c.startswith('pd_'):
90 limit = int(request.GET.get('max', ''))
99 tags = search.hint_tags(prefix, pdcounter=True)
100 tags = filter(lambda t: not is_dupe(t), tags)
107 'category': category_name(t.category),
109 'url': t.get_absolute_url()
112 books = search.hint_books(prefix)
118 'label': '<cite>%s</cite>, %s' % (b.title, b.author_unicode()),
119 'category': _('book'),
121 'url': b.get_absolute_url()
124 callback = request.GET.get('callback', None)
126 return HttpResponse("%s(%s);" % (callback, json.dumps(data)),
127 content_type="application/json; charset=utf-8")
129 return JsonResponse(data, safe=False)
134 query = request.GET.get('q', '')
135 query = ' '.join(query.split())
136 # filter out private use characters
138 query = ''.join(ch for ch in query if unicodedata.category(ch) != 'Co')
141 return render_to_response(
142 'catalogue/search_too_short.html', {'prefix': query},
143 context_instance=RequestContext(request))
144 elif len(query) > 256:
145 return render_to_response(
146 'catalogue/search_too_long.html', {'prefix': query}, context_instance=RequestContext(request))
148 query = remove_query_syntax_chars(query)
150 words = query.split()
152 query = ' '.join(words[:10])
156 tags = search.hint_tags(query, pdcounter=True, prefix=False)
157 tags = split_tags(tags)
165 (['metadata'], True),
166 (['text', 'themes_pl'], False),
168 for fieldset, is_book in fieldsets:
169 search_fields += fieldset
170 results_parts.append(search.search_words(words, search_fields, book=is_book))
174 for results_part in results_parts:
175 for result in sorted(SearchResult.aggregate(results_part), reverse=True):
176 book_id = result.book_id
177 if book_id in ids_results:
178 ids_results[book_id].merge(result)
180 results.append(result)
181 ids_results[book_id] = result
183 for result in results:
184 search.get_snippets(result, query, num=3)
188 def ensure_exists(r):
191 except Book.DoesNotExist:
194 results = filter(ensure_exists, results)
197 form = PublishingSuggestForm(initial={"books": query + ", "})
198 return render_to_response(
199 'catalogue/search_no_hits.html',
204 'did_you_mean': suggestion
206 context_instance=RequestContext(request))
208 return render_to_response(
209 'catalogue/search_multiple_hits.html',
211 'tags': tags['author'] + tags['kind'] + tags['genre'] + tags['epoch'] + tags['theme'],
214 'did_you_mean': suggestion
216 context_instance=RequestContext(request))