Beispiel #1
0
    def index(self, **kwargs):
        """ Check with google. """

        cherrypy.lib.caching.expires(0, True)

        os = BaseSearcher.OpenSearch()

        # Remove Session cookie.
        name = cherrypy.serving.request.config.get('tools.sessions.name',
                                                   'session_id')
        del cherrypy.serving.response.cookie[name]

        if 'recaptcha_challenge_field' in kwargs:
            response = submit(kwargs['recaptcha_challenge_field'],
                              kwargs['recaptcha_response_field'],
                              cherrypy.config['recaptcha_private_key'],
                              cherrypy.request.remote.ip)

            cherrypy.ipsession.captcha_answer(response)

            if not response.is_valid:
                raise cherrypy.HTTPRedirect(
                    os.url('captcha.question', error='incorrect-captcha-sol'))

        for req in reversed(cherrypy.ipsession['requests']):
            if 'captcha' not in req:
                raise cherrypy.HTTPRedirect(req)

        raise cherrypy.HTTPRedirect(os.url('start'))
    def index(self, **dummy_kwargs):
        """ Output the suggestions page. """

        cherrypy.request.params['format'] = 'json'  # override user

        os = BaseSearcher.OpenSearch()
        os.sort_order = 'nentry'
        os.start_index = 1
        os.items_per_page = 5

        if os.format != 'json':
            raise cherrypy.HTTPError(400, 'Bad Request. Unknown format.')

        if len(os.query) == 0:
            raise cherrypy.HTTPError(400, 'Bad Request. No query.')

        last_word = os.query.split()[-1]
        if len(last_word) < 4:
            raise cherrypy.HTTPError(400, 'Bad Request. Query too short.')

        # ok. request looks sane. process it

        os.log_request('suggestions')

        os.f_format_title = os.format_suggestion
        os.f_format_subtitle = os.format_none
        os.f_format_extra = os.format_none
        os.f_format_url = os.format_none
        os.f_format_thumb_url = os.format_none
        os.f_format_icon = os.format_none

        sql = BaseSearcher.SQLStatement()

        # prepare inner query
        sql.query = 'SELECT tsvec'
        sql.from_ = ('books', )
        sql.fulltext('books.tsvec', os.query)
        inner_sql_query = self.sql_searcher.mogrify(os, sql)

        sql.query = "SELECT substr (word, 2) AS title FROM ts_stat ( %(inner)s )"
        sql.from_ = ()
        sql.params['inner'] = inner_sql_query
        sql.where = ["word ~* %(re_word)s"]
        sql.params['re_word'] = '^0' + last_word

        try:
            os = self.sql_searcher.search(os, sql)
        except DatabaseError as what:
            cherrypy.log("SQL Error: " + str(what),
                         context='REQUEST',
                         severity=logging.ERROR)
            raise cherrypy.HTTPError(500, 'Internal Server Error.')

        os.template = os.page = 'results'
        os.finalize()

        return self.format(os)
    def index(self, **dummy_kwargs):
        """ Output the start page. """

        os = BaseSearcher.OpenSearch()

        os.log_request('start')

        os.search_terms = ''
        os.title = {
            'mobile': _('PG Mobile'),
            'opds': _('Project Gutenberg'),
            'stanza': _('Project Gutenberg')
        }.get(os.format, _('Search Project Gutenberg'))

        cat = BaseSearcher.Cat()
        cat.header = _(
            'Welcome to Project Gutenberg. Use the search box to find your book or pick a link.'
        )
        cat.title = _('Popular')
        cat.subtitle = _('Our most popular books.')
        cat.url = os.url('search', sort_order='downloads')
        cat.class_ += 'navlink'
        cat.icon = 'popular'
        cat.order = 2
        os.entries.append(cat)

        cat = BaseSearcher.Cat()
        cat.title = _('Latest')
        cat.subtitle = _('Our latest releases.')
        cat.url = os.url('search', sort_order='release_date')
        cat.class_ += 'navlink'
        cat.icon = 'date'
        cat.order = 3
        os.entries.append(cat)

        cat = BaseSearcher.Cat()
        cat.title = _('Random')
        cat.subtitle = _('Random books.')
        cat.url = os.url('search', sort_order='random')
        cat.class_ += 'navlink'
        cat.icon = 'random'
        cat.order = 4
        os.entries.append(cat)

        os.total_results = 0
        os.template = 'results'
        os.page = 'start'

        os.url_share = os.url('/', host=os.file_host)
        os.twit = os.tagline

        os.finalize()

        return self.format(os)
Beispiel #4
0
    def index(self, **kwargs):
        """ Output captcha. """

        cherrypy.lib.caching.expires(3600, True)

        os = BaseSearcher.OpenSearch()
        os.template = 'recaptcha'
        os.recaptcha_public_key = cherrypy.config['recaptcha_public_key']
        os.error = kwargs.get('error')
        os.finalize()

        # Remove Session cookie, so that page can be cached.
        name = cherrypy.serving.request.config.get('tools.sessions.name',
                                                   'session_id')
        del cherrypy.serving.response.cookie[name]

        return self.format(os)
Beispiel #5
0
    def index (self, **dummy_kwargs):
        """ Output sitemap index. """

        sitemaps = []
        now = datetime.datetime.utcnow ().replace (microsecond = 0).isoformat () + 'Z'

        # 99999 is safeguard against bogus ebook numbers
        lastbook = BaseSearcher.sql_get ('select max (pk) as lastbook from books where pk < 99999')

        os = BaseSearcher.OpenSearch ()
        host = cherrypy.config['host']

        for n in range (0, lastbook // SITEMAP_SIZE + 1):
            sitemap = Struct ()
            sitemap.loc = os.url ('sitemap_index', page = n, host = host, format = None)
            sitemap.lastmod = now
            sitemaps.append (sitemap)

        data = Struct ()
        data.sitemaps = sitemaps

        return self.output ('sitemap-index', data = data)
Beispiel #6
0
    def index (self, **kwargs):
        """ Output sitemap. """

        urls = []
        start = int (kwargs['page']) * SITEMAP_SIZE

        rows = BaseSearcher.SQLSearcher.execute (
            'select pk from books where pk >= %(start)s and pk <  %(end)s order by pk',
            { 'start': str (start), 'end': str (start + SITEMAP_SIZE) })

        os = BaseSearcher.OpenSearch ()
        host = cherrypy.config['host']

        for row in rows:
            url = Struct ()
            url.loc = os.url ('bibrec', id = row[0], host = host, format = None)
            urls.append (url)

        data = Struct ()
        data.urls = urls

        return self.output ('sitemap', data = data)
Beispiel #7
0
    def index(self, **kwargs):
        """ Output a search result page. """

        os = BaseSearcher.OpenSearch()
        os.log_request('search')

        if 'default_prefix' in kwargs:
            raise cherrypy.HTTPError(
                400, 'Bad Request. Unknown parameter: default_prefix')

        if os.start_index > BaseSearcher.MAX_RESULTS:
            raise cherrypy.HTTPError(
                400, 'Bad Request. Parameter start_index too high')

        sql = BaseSearcher.SQLStatement()
        sql.query = 'SELECT *'
        sql.from_ = ['v_appserver_books_4 as books']

        # let derived classes prepare the query
        try:
            self.setup(os, sql)
        except ValueError as what:
            raise cherrypy.HTTPError(400, 'Bad Request. ' + str(what))

        os.fix_sortorder()

        # execute the query
        try:
            BaseSearcher.SQLSearcher().search(os, sql)
        except DatabaseError as what:
            cherrypy.log("SQL Error: " + str(what),
                         context='REQUEST',
                         severity=logging.ERROR)
            raise cherrypy.HTTPError(400, 'Bad Request. Check your query.')

        # sync os.title and first entry header
        if os.entries:
            entry = os.entries[0]
            if os.title and not entry.header:
                entry.header = os.title
            elif entry.header and not os.title:
                os.title = entry.header

        os.template = os.page = 'results'

        # give derived class a chance to tweak result set
        self.fixup(os)

        # warn user about no records found
        if os.total_results == 0:
            self.nothing_found(os)

        # suggest alternate queries
        if os.total_results < 5:
            self.output_suggestions(os)

        # add sort by links
        if os.start_index == 1 and os.total_results > 1:
            if 'downloads' in os.alternate_sort_orders:
                self.sort_by_downloads(os)
            if 'release_date' in os.alternate_sort_orders:
                self.sort_by_release_date(os)
            if 'title' in os.alternate_sort_orders:
                self.sort_by_title(os)
            if 'alpha' in os.alternate_sort_orders:
                self.sort_alphabetically(os)
            if 'quantity' in os.alternate_sort_orders:
                self.sort_by_quantity(os)

        os.finalize()
        self.finalize(os)

        if os.total_results > 0:
            # call this after finalize ()
            os.entries.insert(0, self.status_line(os))

        return self.format(os)
    def index(self, **dummy_kwargs):
        """ A bibrec page. """

        os = BaseSearcher.OpenSearch()

        os.log_request('bibrec')

        dc = BaseSearcher.DC(cherrypy.engine.pool)

        # the bulk of the work is done here
        dc.load_from_database(os.id)
        if not dc.files:
            # NOTE: Error message
            cherrypy.tools.rate_limiter.e404()
            raise cherrypy.HTTPError(404, _('No ebook by that number.'))

        # add these fields so we won't have to test for their existence later
        dc.extra_info = None
        dc.url = None

        dc.translate()
        dc.header = gg.cut_at_newline(dc.title)
        os.title = dc.make_pretty_title()
        dc.extra_info = ''
        dc.class_ = BaseSearcher.ClassAttr()
        dc.order = 10
        dc.icon = 'book'
        if 'Sound' in dc.categories:
            dc.icon = 'audiobook'
        os.title_icon = dc.icon
        os.twit = os.title
        os.qrcode_url = '//%s/cache/epub/%d/pg%d.qrcode.png' % (os.file_host,
                                                                os.id, os.id)

        os.entries.append(dc)

        s = cherrypy.session
        last_visited = s.get('last_visited', [])
        last_visited.append(os.id)
        s['last_visited'] = last_visited

        # can we find some meaningful breadcrumbs ?
        for a in dc.authors:
            if a.marcrel in ('aut', 'cre'):
                book_cnt = BaseSearcher.sql_get(
                    "select count (*) from mn_books_authors where fk_authors = %(aid)s",
                    aid=a.id)
                if book_cnt > 1:
                    os.breadcrumbs.append(
                        (__('One by {author}', '{count} by {author}',
                            book_cnt).format(count=book_cnt,
                                             author=dc.make_pretty_name(
                                                 a.name)),
                         _('Find more ebooks by the same author.'),
                         os.url('author', id=a.id)))

        if os.format in ('html', 'mobile'):
            cat = BaseSearcher.Cat()
            cat.header = _('Similar Books')
            cat.title = _('Readers also downloaded…')
            cat.rel = 'related'
            cat.url = os.url('also', id=os.id)
            cat.class_ += 'navlink grayed noprint'
            cat.icon = 'suggestion'
            cat.order = 30
            os.entries.append(cat)

            for bookshelf in dc.bookshelves:
                cat = BaseSearcher.Cat()
                cat.title = _('In {bookshelf}').format(
                    bookshelf=bookshelf.bookshelf)
                cat.rel = 'related'
                cat.url = os.url('bookshelf', id=bookshelf.id)
                cat.class_ += 'navlink grayed'
                cat.icon = 'bookshelf'
                cat.order = 33
                os.entries.append(cat)

        if os.format in ('mobile', ):
            for author in dc.authors:
                cat = BaseSearcher.Cat()
                cat.title = _('By {author}').format(
                    author=author.name_and_dates)
                cat.rel = 'related'
                cat.url = os.url('author', id=author.id)
                cat.class_ += 'navlink grayed'
                cat.icon = 'author'
                cat.order = 31
                os.entries.append(cat)

            for subject in dc.subjects:
                cat = BaseSearcher.Cat()
                cat.title = _('On {subject}').format(subject=subject.subject)
                cat.rel = 'related'
                cat.url = os.url('subject', id=subject.id)
                cat.class_ += 'navlink grayed'
                cat.icon = 'subject'
                cat.order = 32
                os.entries.append(cat)

        os.total_results = 1

        os.template = 'results' if os.format == 'mobile' else 'bibrec'
        os.page = 'bibrec'
        os.og_type = 'book'
        os.finalize()

        return self.format(os)
Beispiel #9
0
 def index(self, **kwargs):
     os = BaseSearcher.OpenSearch()
     raise cherrypy.HTTPRedirect(os.url('start'))