Пример #1
0
 def item(i):
     templ = (
         u'<div title="{4}" class="category-item">'
         '<div class="category-name">'
         '<a href="{5}{3}" title="{4}">{0}</a></div>'
         "<div>{1}</div>"
         "<div>{2}</div></div>"
     )
     rating, rstring = render_rating(i.avg_rating, prefix)
     orig_name = i.sort if i.use_sort_as_name else i.name
     name = xml(orig_name)
     if datatype == "rating":
         name = xml(_("%d stars") % int(i.avg_rating))
     id_ = i.id
     if id_ is None:
         id_ = hexlify(force_unicode(orig_name).encode("utf-8"))
     id_ = xml(str(id_))
     desc = ""
     if i.count > 0:
         desc += "[" + _("%d books") % i.count + "]"
     q = i.category
     if not q:
         q = category
     href = "/browse/matches/%s/%s" % (quote(q), quote(id_))
     return templ.format(xml(name), rating, xml(desc), xml(href, True), rstring, prefix)
Пример #2
0
 def item(i):
     templ = (u'<div title="{4}" class="category-item">'
             '<div class="category-name">'
             '<a href="{5}{3}" title="{4}">{0}</a></div>'
             '<div>{1}</div>'
             '<div>{2}</div></div>')
     rating, rstring = render_rating(i.avg_rating, prefix)
     if i.use_sort_as_name:
         name = xml(i.sort)
     else:
         name = xml(i.name)
     if datatype == 'rating':
         name = xml(_('%d stars')%int(i.avg_rating))
     id_ = i.id
     if id_ is None:
         id_ = hexlify(force_unicode(name).encode('utf-8'))
     id_ = xml(str(id_))
     desc = ''
     if i.count > 0:
         desc += '[' + _('%d books')%i.count + ']'
     q = i.category
     if not q:
         q = category
     href = '/browse/matches/%s/%s'%(quote(q), quote(id_))
     return templ.format(xml(name), rating,
             xml(desc), xml(href, True), rstring, prefix)
Пример #3
0
 def item(i):
     templ = (u'<div title="{4}" class="category-item">'
              '<div class="category-name">'
              '<a href="{5}{3}" title="{4}">{0}</a></div>'
              '<div>{1}</div>'
              '<div>{2}</div></div>')
     rating, rstring = render_rating(i.avg_rating, prefix)
     if i.use_sort_as_name:
         name = xml(i.sort)
     else:
         name = xml(i.name)
     if datatype == 'rating':
         name = xml(_('%d stars') % int(i.avg_rating))
     id_ = i.id
     if id_ is None:
         id_ = hexlify(force_unicode(name).encode('utf-8'))
     id_ = xml(str(id_))
     desc = ''
     if i.count > 0:
         desc += '[' + _('%d books') % i.count + ']'
     q = i.category
     if not q:
         q = category
     href = '/browse/matches/%s/%s' % (quote(q), quote(id_))
     return templ.format(xml(name), rating, xml(desc), xml(href, True),
                         rstring, prefix)
Пример #4
0
    def browse_toplevel(self):
        categories = self.categories_cache()
        category_meta = self.db.field_metadata
        cats = [
                (_('Newest'), 'newest', 'forward.png'),
                (_('All books'), 'allbooks', 'book.png'),
                ]

        def getter(x):
            return category_meta[x]['name'].lower()

        displayed_custom_fields = custom_fields_to_display(self.db)
        uc_displayed = set()
        for category in sorted(categories, key=lambda x: sort_key(getter(x))):
            if len(categories[category]) == 0:
                continue
            if category in ('formats', 'identifiers'):
                continue
            meta = category_meta.get(category, None)
            if meta is None:
                continue
            if meta['is_custom'] and category not in displayed_custom_fields:
                continue
            # get the icon files
            if category in self.icon_map:
                icon = '_'+quote(self.icon_map[category])
            elif category in category_icon_map:
                icon = category_icon_map[category]
            elif meta['is_custom']:
                icon = category_icon_map['custom:']
            elif meta['kind'] == 'user':
                icon = category_icon_map['user:'******'blank.png'

            if meta['kind'] == 'user':
                dot = category.find('.')
                if dot > 0:
                    cat = category[:dot]
                    if cat not in uc_displayed:
                        cats.append((meta['name'][:dot-1], cat, icon))
                        uc_displayed.add(cat)
                else:
                    cats.append((meta['name'], category, icon))
                    uc_displayed.add(category)
            else:
                cats.append((meta['name'], category, icon))

        cats = [(u'<li><a title="{2} {0}" href="{3}/browse/category/{1}">&nbsp;</a>'
                 u'<img src="{3}{src}" alt="{0}" />'
                 u'<span class="label">{0}</span>'
                 u'</li>')
                .format(xml(x, True), xml(quote(y)), xml(_('Browse books by')),
                    self.opts.url_prefix, src='/browse/icon/'+z)
                for x, y, z in cats]

        main = u'<div class="toplevel"><h3>{0}</h3><ul>{1}</ul></div>'\
                .format(_('Choose a category to browse by:'), u'\n\n'.join(cats))
        return self.browse_template('name').format(title='',
                    script='toplevel();', main=main)
Пример #5
0
 def browse_get_book_args(self, mi, id_, add_category_links=False):
     fmts = self.db.formats(id_, index_is_id=True)
     if not fmts:
         fmts = ""
     fmts = [x.lower() for x in fmts.split(",") if x]
     pf = prefs["output_format"].lower()
     try:
         fmt = pf if pf in fmts else fmts[0]
     except:
         fmt = None
     args = {"id": id_, "mi": mi}
     ccache = self.categories_cache() if add_category_links else {}
     ftitle = fauthors = ""
     for key in mi.all_field_keys():
         val = mi.format_field(key)[1]
         if not val:
             val = ""
         if key == "title":
             ftitle = xml(val, True)
         elif key == "authors":
             fauthors = xml(val, True)
         if add_category_links:
             added_key = False
             fm = mi.metadata_for_field(key)
             if (
                 val
                 and fm
                 and fm["is_category"]
                 and not fm["is_csp"]
                 and key != "formats"
                 and fm["datatype"] not in ["rating"]
             ):
                 categories = mi.get(key)
                 if isinstance(categories, basestring):
                     categories = [categories]
                 dbtags = []
                 for category in categories:
                     dbtag = None
                     for tag in ccache[key]:
                         if tag.name == category:
                             dbtag = tag
                             break
                     dbtags.append(dbtag)
                 if None not in dbtags:
                     vals = []
                     for tag in dbtags:
                         tval = (
                             '<a title="Browse books by {3}: {0}"'
                             ' href="{1}" class="details_category_link">{2}</a>'
                         )
                         href = "%s/browse/matches/%s/%s" % (
                             self.opts.url_prefix,
                             quote(tag.category),
                             quote(str(tag.id)),
                         )
                         vals.append(
                             tval.format(
                                 xml(tag.name, True),
                                 xml(href, True),
                                 xml(val if len(dbtags) == 1 else tag.name),
                                 xml(key, True),
                             )
                         )
                     join = (
                         " &amp; "
                         if key == "authors" or (fm["is_custom"] and fm["display"].get("is_names", False))
                         else ", "
                     )
                     args[key] = join.join(vals)
                     added_key = True
             if not added_key:
                 args[key] = xml(val, True)
         else:
             args[key] = xml(val, True)
     fname = quote(ascii_filename(ftitle) + " - " + ascii_filename(fauthors))
     return args, fmt, fmts, fname
Пример #6
0
    def browse_category(self, category, sort):
        categories = self.categories_cache()
        categories["virt_libs"] = {}
        if category not in categories:
            raise cherrypy.HTTPError(404, "category not found")
        category_meta = self.db.field_metadata
        category_name = _("Virtual Libraries") if category == "virt_libs" else category_meta[category]["name"]
        datatype = "text" if category == "virt_libs" else category_meta[category]["datatype"]

        # See if we have any sub-categories to display. As we find them, add
        # them to the displayed set to avoid showing the same item twice
        uc_displayed = set()
        cats = []
        for ucat in sorted(categories.keys(), key=sort_key):
            if len(categories[ucat]) == 0:
                continue
            if category == "formats":
                continue
            meta = category_meta.get(ucat, None)
            if meta is None:
                continue
            if meta["kind"] != "user":
                continue
            cat_len = len(category)
            if not (len(ucat) > cat_len and ucat.startswith(category + ".")):
                continue

            if ucat in self.icon_map:
                icon = "_" + quote(self.icon_map[ucat])
            else:
                icon = category_icon_map["user:"******".")
            if dot > 0:
                # More subcats
                cat = cat[:dot]
                if cat not in uc_displayed:
                    cats.append((cat, ucat[: cat_len + dot], icon))
                    uc_displayed.add(cat)
            else:
                # This is the end of the chain
                cats.append((cat, ucat, icon))
                uc_displayed.add(cat)

        cats = u"\n\n".join(
            [
                (
                    u'<li><a title="{2} {0}" href="{3}/browse/category/{1}">&nbsp;</a>'
                    u'<img src="{3}{src}" alt="{0}" />'
                    u'<span class="label">{0}</span>'
                    u"</li>"
                ).format(
                    xml(x, True),
                    xml(quote(y)),
                    xml(_("Browse books by")),
                    self.opts.url_prefix,
                    src="/browse/icon/" + z,
                )
                for x, y, z in cats
            ]
        )
        if cats:
            cats = (u'\n<div class="toplevel">\n' "{0}</div>").format(cats)
            script = "toplevel();"
        else:
            script = "true"

        # Now do the category items
        vls = self.db.prefs.get("virtual_libraries", {})
        categories["virt_libs"] = sorted([Tag(k) for k, v in vls.iteritems()], key=lambda x: sort_key(x.name))
        items = categories[category]

        sort = self.browse_sort_categories(items, sort)

        if not cats and len(items) == 1:
            # Only one item in category, go directly to book list
            html = get_category_items(category, items, datatype, self.opts.url_prefix)
            href = re.search(r'<a href="([^"]+)"', html)
            if href is not None:
                # cherrypy does not auto unquote params when using
                # InternalRedirect
                raise cherrypy.InternalRedirect(unquote(href.group(1)))

        if len(items) <= self.opts.max_opds_ungrouped_items:
            script = "false"
            items = get_category_items(category, items, datatype, self.opts.url_prefix)
        else:
            getter = lambda x: unicode(getattr(x, "sort", x.name))
            starts = set([])
            for x in items:
                val = getter(x)
                if not val:
                    val = u"A"
                starts.add(val[0].upper())
            category_groups = OrderedDict()
            for x in sorted(starts):
                category_groups[x] = len([y for y in items if getter(y).upper().startswith(x)])
            items = [
                (
                    u'<h3 title="{0}"><a class="load_href" title="{0}"'
                    u' href="{4}{3}"><strong>{0}</strong> [{2}]</a></h3><div>'
                    u'<div class="loaded" style="display:none"></div>'
                    u'<div class="loading"><img alt="{1}" src="{4}/static/loading.gif" /><em>{1}</em></div>'
                    u"</div>"
                ).format(
                    xml(s, True),
                    xml(_("Loading, please wait")) + "&hellip;",
                    unicode(c),
                    xml(
                        u"/browse/category_group/%s/%s"
                        % (hexlify(category.encode("utf-8")), hexlify(s.encode("utf-8"))),
                        True,
                    ),
                    self.opts.url_prefix,
                )
                for s, c in category_groups.items()
            ]
            items = "\n\n".join(items)
            items = u'<div id="groups">\n{0}</div>'.format(items)

        if cats:
            script = "toplevel();category(%s);" % script
        else:
            script = "category(%s);" % script

        main = u"""
            <div class="category">
                <h3>{0}</h3>
                    <a class="navlink" href="{3}/browse"
                        title="{2}">{2}&nbsp;&uarr;</a>
                {1}
            </div>
        """.format(
            xml(_("Browsing by") + ": " + category_name), cats + items, xml(_("Up"), True), self.opts.url_prefix
        )

        return self.browse_template(sort).format(title=category_name, script=script, main=main)
Пример #7
0
    def browse_toplevel(self):
        categories = self.categories_cache()
        category_meta = self.db.field_metadata
        cats = [
            (_("Newest"), "newest", "forward.png"),
            (_("All books"), "allbooks", "book.png"),
            (_("Random book"), "randombook", "random.png"),
        ]
        virt_libs = self.db.prefs.get("virtual_libraries", {})
        if virt_libs:
            cats.append((_("Virtual Libs."), "virt_libs", "lt.png"))

        def getter(x):
            try:
                return category_meta[x]["name"].lower()
            except KeyError:
                return x

        displayed_custom_fields = custom_fields_to_display(self.db)
        uc_displayed = set()
        for category in sorted(categories, key=lambda x: sort_key(getter(x))):
            if len(categories[category]) == 0:
                continue
            if category in ("formats", "identifiers"):
                continue
            meta = category_meta.get(category, None)
            if meta is None:
                continue
            if self.db.field_metadata.is_ignorable_field(category) and category not in displayed_custom_fields:
                continue
            # get the icon files
            main_cat = (category.partition(".")[0]) if hasattr(category, "partition") else category
            if main_cat in self.icon_map:
                icon = "_" + quote(self.icon_map[main_cat])
            elif category in category_icon_map:
                icon = category_icon_map[category]
            elif meta["is_custom"]:
                icon = category_icon_map["custom:"]
            elif meta["kind"] == "user":
                icon = category_icon_map["user:"******"blank.png"

            if meta["kind"] == "user":
                dot = category.find(".")
                if dot > 0:
                    cat = category[:dot]
                    if cat not in uc_displayed:
                        cats.append((meta["name"][: dot - 1], cat, icon))
                        uc_displayed.add(cat)
                else:
                    cats.append((meta["name"], category, icon))
                    uc_displayed.add(category)
            else:
                cats.append((meta["name"], category, icon))

        cats = [
            (
                u'<li><a title="{2} {0}" href="{3}/browse/category/{1}">&nbsp;</a>'
                u'<img src="{3}{src}" alt="{0}" />'
                u'<span class="label">{0}</span>'
                u"</li>"
            ).format(
                xml(x, True), xml(quote(y)), xml(_("Browse books by")), self.opts.url_prefix, src="/browse/icon/" + z
            )
            for x, y, z in cats
        ]

        main = u'<div class="toplevel"><h3>{0}</h3><ul>{1}</ul></div>'.format(
            _("Choose a category to browse by:"), u"\n\n".join(cats)
        )
        return self.browse_template("name").format(title="", script="toplevel();", main=main)
Пример #8
0
 def browse_get_book_args(self, mi, id_, add_category_links=False):
     fmts = self.db.formats(id_, index_is_id=True)
     if not fmts:
         fmts = ''
     fmts = [x.lower() for x in fmts.split(',') if x]
     pf = prefs['output_format'].lower()
     try:
         fmt = pf if pf in fmts else fmts[0]
     except:
         fmt = None
     args = {
         'id': id_,
         'mi': mi,
     }
     ccache = self.categories_cache() if add_category_links else {}
     ftitle = fauthors = ''
     for key in mi.all_field_keys():
         val = mi.format_field(key)[1]
         if not val:
             val = ''
         if key == 'title':
             ftitle = xml(val, True)
         elif key == 'authors':
             fauthors = xml(val, True)
         if add_category_links:
             added_key = False
             fm = mi.metadata_for_field(key)
             if val and fm and fm['is_category'] and not fm['is_csp'] and\
                     key != 'formats' and fm['datatype'] not in ['rating']:
                 categories = mi.get(key)
                 if isinstance(categories, basestring):
                     categories = [categories]
                 dbtags = []
                 for category in categories:
                     dbtag = None
                     for tag in ccache[key]:
                         if tag.name == category:
                             dbtag = tag
                             break
                     dbtags.append(dbtag)
                 if None not in dbtags:
                     vals = []
                     for tag in dbtags:
                         tval = (
                             '<a title="Browse books by {3}: {0}"'
                             ' href="{1}" class="details_category_link">{2}</a>'
                         )
                         href='%s/browse/matches/%s/%s' % \
                         (self.opts.url_prefix, quote(tag.category), quote(str(tag.id)))
                         vals.append(
                             tval.format(
                                 xml(tag.name, True), xml(href, True),
                                 xml(val if len(dbtags) == 1 else tag.name),
                                 xml(key, True)))
                     join = ' &amp; ' if key == 'authors' or \
                                         (fm['is_custom'] and
                                          fm['display'].get('is_names', False)) \
                                      else ', '
                     args[key] = join.join(vals)
                     added_key = True
             if not added_key:
                 args[key] = xml(val, True)
         else:
             args[key] = xml(val, True)
     fname = quote(
         ascii_filename(ftitle) + ' - ' + ascii_filename(fauthors))
     return args, fmt, fmts, fname
Пример #9
0
    def browse_category(self, category, sort):
        categories = self.categories_cache()
        categories['virt_libs'] = {}
        if category not in categories:
            raise cherrypy.HTTPError(404, 'category not found')
        category_meta = self.db.field_metadata
        category_name = _(
            'Virtual Libraries'
        ) if category == 'virt_libs' else category_meta[category]['name']
        datatype = 'text' if category == 'virt_libs' else category_meta[
            category]['datatype']

        # See if we have any sub-categories to display. As we find them, add
        # them to the displayed set to avoid showing the same item twice
        uc_displayed = set()
        cats = []
        for ucat in sorted(categories.keys(), key=sort_key):
            if len(categories[ucat]) == 0:
                continue
            if category == 'formats':
                continue
            meta = category_meta.get(ucat, None)
            if meta is None:
                continue
            if meta['kind'] != 'user':
                continue
            cat_len = len(category)
            if not (len(ucat) > cat_len and ucat.startswith(category + '.')):
                continue

            if ucat in self.icon_map:
                icon = '_' + quote(self.icon_map[ucat])
            else:
                icon = category_icon_map['user:'******'.')
            if dot > 0:
                # More subcats
                cat = cat[:dot]
                if cat not in uc_displayed:
                    cats.append((cat, ucat[:cat_len + dot], icon))
                    uc_displayed.add(cat)
            else:
                # This is the end of the chain
                cats.append((cat, ucat, icon))
                uc_displayed.add(cat)

        cats = u'\n\n'.join([(
            u'<li><a title="{2} {0}" href="{3}/browse/category/{1}">&nbsp;</a>'
            u'<img src="{3}{src}" alt="{0}" />'
            u'<span class="label">{0}</span>'
            u'</li>').format(xml(x, True),
                             xml(quote(y)),
                             xml(_('Browse books by')),
                             self.opts.url_prefix,
                             src='/browse/icon/' + z) for x, y, z in cats])
        if cats:
            cats = (u'\n<div class="toplevel">\n' '{0}</div>').format(cats)
            script = 'toplevel();'
        else:
            script = 'true'

        # Now do the category items
        vls = self.db.prefs.get('virtual_libraries', {})
        categories['virt_libs'] = sorted([Tag(k) for k, v in vls.iteritems()],
                                         key=lambda x: sort_key(x.name))
        items = categories[category]

        sort = self.browse_sort_categories(items, sort)

        if not cats and len(items) == 1:
            # Only one item in category, go directly to book list
            html = get_category_items(category, items, datatype,
                                      self.opts.url_prefix)
            href = re.search(r'<a href="([^"]+)"', html)
            if href is not None:
                # cherrypy does not auto unquote params when using
                # InternalRedirect
                raise cherrypy.InternalRedirect(unquote(href.group(1)))

        if len(items) <= self.opts.max_opds_ungrouped_items:
            script = 'false'
            items = get_category_items(category, items, datatype,
                                       self.opts.url_prefix)
        else:
            getter = lambda x: unicode(getattr(x, 'sort', x.name))
            starts = set([])
            for x in items:
                val = getter(x)
                if not val:
                    val = u'A'
                starts.add(val[0].upper())
            category_groups = OrderedDict()
            for x in sorted(starts):
                category_groups[x] = len(
                    [y for y in items if getter(y).upper().startswith(x)])
            items = [(
                u'<h3 title="{0}"><a class="load_href" title="{0}"'
                u' href="{4}{3}"><strong>{0}</strong> [{2}]</a></h3><div>'
                u'<div class="loaded" style="display:none"></div>'
                u'<div class="loading"><img alt="{1}" src="{4}/static/loading.gif" /><em>{1}</em></div>'
                u'</div>').format(
                    xml(s, True),
                    xml(_('Loading, please wait')) + '&hellip;', unicode(c),
                    xml(
                        u'/browse/category_group/%s/%s' %
                        (hexlify(category.encode('utf-8')),
                         hexlify(s.encode('utf-8'))), True),
                    self.opts.url_prefix) for s, c in category_groups.items()]
            items = '\n\n'.join(items)
            items = u'<div id="groups">\n{0}</div>'.format(items)

        if cats:
            script = 'toplevel();category(%s);' % script
        else:
            script = 'category(%s);' % script

        main = u'''
            <div class="category">
                <h3>{0}</h3>
                    <a class="navlink" href="{3}/browse"
                        title="{2}">{2}&nbsp;&uarr;</a>
                {1}
            </div>
        '''.format(xml(_('Browsing by') + ': ' + category_name), cats + items,
                   xml(_('Up'), True), self.opts.url_prefix)

        return self.browse_template(sort).format(title=category_name,
                                                 script=script,
                                                 main=main)
Пример #10
0
    def browse_toplevel(self):
        categories = self.categories_cache()
        category_meta = self.db.field_metadata
        cats = [
            (_('Newest'), 'newest', 'forward.png'),
            (_('All books'), 'allbooks', 'book.png'),
            (_('Random book'), 'randombook', 'random.png'),
        ]
        virt_libs = self.db.prefs.get('virtual_libraries', {})
        if virt_libs:
            cats.append((_('Virtual Libs.'), 'virt_libs', 'lt.png'))

        def getter(x):
            try:
                return category_meta[x]['name'].lower()
            except KeyError:
                return x

        displayed_custom_fields = custom_fields_to_display(self.db)
        uc_displayed = set()
        for category in sorted(categories, key=lambda x: sort_key(getter(x))):
            if len(categories[category]) == 0:
                continue
            if category in ('formats', 'identifiers'):
                continue
            meta = category_meta.get(category, None)
            if meta is None:
                continue
            if self.db.field_metadata.is_ignorable_field(category) and \
                        category not in displayed_custom_fields:
                continue
            # get the icon files
            main_cat = (category.partition('.')[0]) if hasattr(
                category, 'partition') else category
            if main_cat in self.icon_map:
                icon = '_' + quote(self.icon_map[main_cat])
            elif category in category_icon_map:
                icon = category_icon_map[category]
            elif meta['is_custom']:
                icon = category_icon_map['custom:']
            elif meta['kind'] == 'user':
                icon = category_icon_map['user:'******'blank.png'

            if meta['kind'] == 'user':
                dot = category.find('.')
                if dot > 0:
                    cat = category[:dot]
                    if cat not in uc_displayed:
                        cats.append((meta['name'][:dot - 1], cat, icon))
                        uc_displayed.add(cat)
                else:
                    cats.append((meta['name'], category, icon))
                    uc_displayed.add(category)
            else:
                cats.append((meta['name'], category, icon))

        cats = [(
            u'<li><a title="{2} {0}" href="{3}/browse/category/{1}">&nbsp;</a>'
            u'<img src="{3}{src}" alt="{0}" />'
            u'<span class="label">{0}</span>'
            u'</li>').format(xml(x, True),
                             xml(quote(y)),
                             xml(_('Browse books by')),
                             self.opts.url_prefix,
                             src='/browse/icon/' + z) for x, y, z in cats]

        main = u'<div class="toplevel"><h3>{0}</h3><ul>{1}</ul></div>'\
                .format(_('Choose a category to browse by:'), u'\n\n'.join(cats))
        return self.browse_template('name').format(title='',
                                                   script='toplevel();',
                                                   main=main)
Пример #11
0
 def browse_get_book_args(self, mi, id_, add_category_links=False):
     fmts = self.db.formats(id_, index_is_id=True)
     if not fmts:
         fmts = ''
     fmts = [x.lower() for x in fmts.split(',') if x]
     pf = prefs['output_format'].lower()
     try:
         fmt = pf if pf in fmts else fmts[0]
     except:
         fmt = None
     args = {'id':id_, 'mi':mi,
             }
     ccache = self.categories_cache() if add_category_links else {}
     ftitle = fauthors = ''
     for key in mi.all_field_keys():
         val = mi.format_field(key)[1]
         if not val:
             val = ''
         if key == 'title':
             ftitle = xml(val, True)
         elif key == 'authors':
             fauthors = xml(val, True)
         if add_category_links:
             added_key = False
             fm = mi.metadata_for_field(key)
             if val and fm and fm['is_category'] and not fm['is_csp'] and\
                     key != 'formats' and fm['datatype'] not in ['rating']:
                 categories = mi.get(key)
                 if isinstance(categories, basestring):
                     categories = [categories]
                 dbtags = []
                 for category in categories:
                     dbtag = None
                     for tag in ccache[key]:
                         if tag.name == category:
                             dbtag = tag
                             break
                     dbtags.append(dbtag)
                 if None not in dbtags:
                     vals = []
                     for tag in dbtags:
                         tval = ('<a title="Browse books by {3}: {0}"'
                         ' href="{1}" class="details_category_link">{2}</a>')
                         href='%s/browse/matches/%s/%s' % \
                         (self.opts.url_prefix, quote(tag.category), quote(str(tag.id)))
                         vals.append(tval.format(xml(tag.name, True),
                             xml(href, True),
                             xml(val if len(dbtags) == 1 else tag.name),
                             xml(key, True)))
                     join = ' &amp; ' if key == 'authors' or \
                                         (fm['is_custom'] and
                                          fm['display'].get('is_names', False)) \
                                      else ', '
                     args[key] = join.join(vals)
                     added_key = True
             if not added_key:
                 args[key] = xml(val, True)
         else:
             args[key] = xml(val, True)
     fname = quote(ascii_filename(ftitle) + ' - ' +
             ascii_filename(fauthors))
     return args, fmt, fmts, fname
Пример #12
0
    def browse_category(self, category, sort):
        categories = self.categories_cache()
        if category not in categories:
            raise cherrypy.HTTPError(404, 'category not found')
        category_meta = self.db.field_metadata
        category_name = category_meta[category]['name']
        datatype = category_meta[category]['datatype']

        # See if we have any sub-categories to display. As we find them, add
        # them to the displayed set to avoid showing the same item twice
        uc_displayed = set()
        cats = []
        for ucat in sorted(categories.keys(), key=sort_key):
            if len(categories[ucat]) == 0:
                continue
            if category == 'formats':
                continue
            meta = category_meta.get(ucat, None)
            if meta is None:
                continue
            if meta['kind'] != 'user':
                continue
            cat_len = len(category)
            if not (len(ucat) > cat_len and ucat.startswith(category+'.')):
                continue
            icon = category_icon_map['user:'******'.')
            if dot > 0:
                # More subcats
                cat = cat[:dot]
                if cat not in uc_displayed:
                    cats.append((cat, ucat[:cat_len+dot], icon))
                    uc_displayed.add(cat)
            else:
                # This is the end of the chain
                cats.append((cat, ucat, icon))
                uc_displayed.add(cat)

        cats = u'\n\n'.join(
                [(u'<li><a title="{2} {0}" href="{3}/browse/category/{1}">&nbsp;</a>'
                 u'<img src="{3}{src}" alt="{0}" />'
                 u'<span class="label">{0}</span>'
                 u'</li>')
                .format(xml(x, True), xml(quote(y)), xml(_('Browse books by')),
                    self.opts.url_prefix, src='/browse/icon/'+z)
                for x, y, z in cats])
        if cats:
            cats = (u'\n<div class="toplevel">\n'
                     '{0}</div>').format(cats)
            script = 'toplevel();'
        else:
            script = 'true'

        # Now do the category items
        items = categories[category]
        sort = self.browse_sort_categories(items, sort)

        if not cats and len(items) == 1:
            # Only one item in category, go directly to book list
            html = get_category_items(category, items,
                    self.search_restriction_name, datatype,
                    self.opts.url_prefix)
            href = re.search(r'<a href="([^"]+)"', html)
            if href is not None:
                raise cherrypy.HTTPRedirect(href.group(1))

        if len(items) <= self.opts.max_opds_ungrouped_items:
            script = 'false'
            items = get_category_items(category, items,
                    self.search_restriction_name, datatype,
                    self.opts.url_prefix)
        else:
            getter = lambda x: unicode(getattr(x, 'sort', x.name))
            starts = set([])
            for x in items:
                val = getter(x)
                if not val:
                    val = u'A'
                starts.add(val[0].upper())
            category_groups = OrderedDict()
            for x in sorted(starts):
                category_groups[x] = len([y for y in items if
                    getter(y).upper().startswith(x)])
            items = [(u'<h3 title="{0}"><a class="load_href" title="{0}"'
                      u' href="{4}{3}"><strong>{0}</strong> [{2}]</a></h3><div>'
                      u'<div class="loaded" style="display:none"></div>'
                      u'<div class="loading"><img alt="{1}" src="{4}/static/loading.gif" /><em>{1}</em></div>'
                      u'</div>').format(
                        xml(s, True),
                        xml(_('Loading, please wait'))+'&hellip;',
                        unicode(c),
                        xml(u'/browse/category_group/%s/%s'%(
                            hexlify(category.encode('utf-8')),
                            hexlify(s.encode('utf-8'))), True),
                        self.opts.url_prefix)
                    for s, c in category_groups.items()]
            items = '\n\n'.join(items)
            items = u'<div id="groups">\n{0}</div>'.format(items)



        if cats:
            script = 'toplevel();category(%s);'%script
        else:
            script = 'category(%s);'%script

        main = u'''
            <div class="category">
                <h3>{0}</h3>
                    <a class="navlink" href="{3}/browse"
                        title="{2}">{2}&nbsp;&uarr;</a>
                {1}
            </div>
        '''.format(
                xml(_('Browsing by')+': ' + category_name), cats + items,
                xml(_('Up'), True), self.opts.url_prefix)

        return self.browse_template(sort).format(title=category_name,
                script=script, main=main)
Пример #13
0
    def browse_nav(self):
        categories = self.categories_cache()
        category_meta = self.db.field_metadata
        cats = [
                (_('Newest'), 'newest', 'whatshot'),
                (_('All books'), 'allbooks', 'library_books'),
                (_('Random book'), 'randombook', 'shuffle'),
                ]
        virt_libs = self.db.prefs.get('virtual_libraries', {})
        if virt_libs:
            cats.append((_('Virtual Libs.'), 'virt_libs', 'graphic_eq'))

        def getter(x):
            try:
                return category_meta[x]['name'].lower()
            except KeyError:
                return x

        displayed_custom_fields = custom_fields_to_display(self.db)
        uc_displayed = set()
        for category in sorted(categories, key=lambda x: sort_key(getter(x))):
            if len(categories[category]) == 0:
                continue
            if category in ('formats', 'identifiers'):
                continue
            meta = category_meta.get(category, None)
            if meta is None:
                continue
            if self.db.field_metadata.is_ignorable_field(category) and \
                        category not in displayed_custom_fields:
                continue

            # get the icon files
            main_cat = (category.partition('.')[0]) if hasattr(category,
                                                    'partition') else category
            if main_cat in self.icon_map:
                icon = self.icon_map[main_cat]
            elif category in category_icon_map:
                icon = category_icon_map[category]
            elif meta['is_custom']:
                icon = category_icon_map['custom:']
            elif meta['kind'] == 'user':
                icon = category_icon_map['user:'******'check_box_outline_blank'

            if meta['kind'] == 'user':
                dot = category.find('.')
                if dot > 0:
                    cat = category[:dot]
                    if cat not in uc_displayed:
                        cats.append((meta['name'][:dot-1], cat, icon))
                        uc_displayed.add(cat)
                else:
                    cats.append((meta['name'], category, icon))
                    uc_displayed.add(category)
            else:
                cats.append((meta['name'], category, icon))

        cats = [(u'<li><a title="{2} {0}" href="{3}/browse/category/{1}">'
                 u'<i class="material-icons">{icon}</i>'
                 u'<span>{0}</span></a>'
                 u'</li>')
                .format(xml(name, True), xml(quote(cat)), xml(_('Browse books by')),
                    self.opts.url_prefix, icon=icon)
                for name, cat, icon in cats]

        return '\n'.join(cats)