Exemplo n.º 1
0
    def from_isbn(cls, isbn):
        """Attempts to fetch an edition by isbn, or if no edition is found,
        attempts to import from amazon
        :param str isbn:
        :rtype: edition|None
        :return: an open library work for this isbn
        """
        isbn = canonical(isbn)

        if len(isbn) not in [10, 13]:
            return None  # consider raising ValueError

        isbn13 = to_isbn_13(isbn)
        isbn10 = isbn_13_to_isbn_10(isbn13)

        # Attempt to fetch book from OL
        for isbn in [isbn13, isbn10]:
            if isbn:
                matches = web.ctx.site.things({
                    "type": "/type/edition", 'isbn_%s' % len(isbn): isbn
                })
                if matches:
                    return web.ctx.site.get(matches[0])

        # Attempt to create from amazon, then fetch from OL
        key = (isbn10 or isbn13) and create_edition_from_amazon_metadata(isbn10 or isbn13)
        if key:
            return web.ctx.site.get(key)
Exemplo n.º 2
0
    def GET(self, key, value, suffix=''):
        key = key.lower()
        if key == 'isbn':
            if len(value) == 13:
                key = 'isbn_13'
            else:
                key = 'isbn_10'
        elif key == 'oclc':
            key = 'oclc_numbers'
        elif key == 'ia':
            key = 'ocaid'

        if key != 'ocaid':  # example: MN41558ucmf_6
            value = value.replace('_', ' ')

        if web.ctx.encoding and web.ctx.path.endswith('.' + web.ctx.encoding):
            ext = '.' + web.ctx.encoding
        else:
            ext = ''

        if web.ctx.env.get('QUERY_STRING'):
            ext += '?' + web.ctx.env['QUERY_STRING']

        q = {'type': '/type/edition', key: value}

        result = web.ctx.site.things(q)

        if result:
            return web.found(result[0] + ext)
        elif key == 'ocaid':
            # Try a range of ocaid alternatives:
            ocaid_alternatives = [{
                'type': '/type/edition',
                'source_records': 'ia:' + value
            }, {
                'type': '/type/volume',
                'ia_id': value
            }]
            for q in ocaid_alternatives:
                result = web.ctx.site.things(q)
                if result:
                    return web.found(result[0] + ext)
            # If nothing matched, try this as a last resort:
            return web.found('/books/ia:' + value + ext)
        elif key.startswith('isbn'):
            try:
                ed_key = create_edition_from_amazon_metadata(value)
            except Exception as e:
                logger.error(e)
                return e.message
            if ed_key:
                return web.found(ed_key + ext)
        web.ctx.status = '404 Not Found'
        return render.notfound(web.ctx.path, create=False)
Exemplo n.º 3
0
    def GET(self):
        i = web.input(isbn='', asin='')
        if not (i.isbn or i.asin):
            return json.dumps({'error': 'isbn or asin required'})
        id_ = i.asin if i.asin else normalize_isbn(i.isbn)
        id_type = 'asin' if i.asin else 'isbn_' + ('13' if len(id_) == 13 else '10')

        metadata = {
            'amazon': get_amazon_metadata(id_, id_type=id_type[:4]) or {},
            'betterworldbooks': get_betterworldbooks_metadata(id_)
            if id_type.startswith('isbn_')
            else {},
        }
        # if user supplied isbn_{n} fails for amazon, we may want to check the alternate isbn

        # if bwb fails and isbn10, try again with isbn13
        if id_type == 'isbn_10' and metadata['betterworldbooks'].get('price') is None:
            isbn_13 = isbn_10_to_isbn_13(id_)
            metadata['betterworldbooks'] = (
                isbn_13 and get_betterworldbooks_metadata(isbn_13) or {}
            )

        # fetch book by isbn if it exists
        # TODO: perform existing OL lookup by ASIN if supplied, if possible
        matches = web.ctx.site.things(
            {
                'type': '/type/edition',
                id_type: id_,
            }
        )

        book_key = matches[0] if matches else None

        # if no OL edition for isbn, attempt to create
        if (not book_key) and metadata.get('amazon'):
            book_key = create_edition_from_amazon_metadata(id_, id_type[:4])

        # include ol edition metadata in response, if available
        if book_key:
            ed = web.ctx.site.get(book_key)
            if ed:
                metadata['key'] = ed.key
                if getattr(ed, 'ocaid'):
                    metadata['ocaid'] = ed.ocaid

        return json.dumps(metadata)
Exemplo n.º 4
0
    def GET(self, key, value, suffix):
        key = key.lower()
        suffix = suffix or ""

        if key == "isbn":
            if len(value) == 13:
                key = "isbn_13"
            else:
                key = "isbn_10"
        elif key == "oclc":
            key = "oclc_numbers"
        elif key == "ia":
            key = "ocaid"

        if key != 'ocaid':  # example: MN41558ucmf_6
            value = value.replace('_', ' ')

        if web.ctx.encoding and web.ctx.path.endswith("." + web.ctx.encoding):
            ext = "." + web.ctx.encoding
        else:
            ext = ""

        if web.ctx.env.get('QUERY_STRING'):
            ext += '?' + web.ctx.env['QUERY_STRING']

        def redirect(key, ext, suffix):
            if ext:
                return web.found(key + ext)
            else:
                book = web.ctx.site.get(key)
                return web.found(book.url(suffix))

        q = {"type": "/type/edition", key: value}
        try:
            result = web.ctx.site.things(q)
            if result:
                raise redirect(result[0], ext, suffix)
            elif key == 'ocaid':
                q = {"type": "/type/edition", 'source_records': 'ia:' + value}
                result = web.ctx.site.things(q)
                if result:
                    raise redirect(result[0], ext, suffix)
                q = {"type": "/type/volume", 'ia_id': value}
                result = web.ctx.site.things(q)
                if result:
                    raise redirect(result[0], ext, suffix)
                else:
                    raise redirect("/books/ia:" + value, ext, suffix)
            elif key.startswith("isbn"):
                ed_key = create_edition_from_amazon_metadata(value)
                if ed_key:
                    raise web.seeother(ed_key)
            web.ctx.status = "404 Not Found"
            return render.notfound(web.ctx.path, create=False)
        except web.HTTPError:
            raise
        except:
            if key.startswith('isbn'):
                ed_key = create_edition_from_amazon_metadata(value)
                if ed_key:
                    raise web.seeother(ed_key)

            logger.error("unexpected error", exc_info=True)
            web.ctx.status = "404 Not Found"
            return render.notfound(web.ctx.path, create=False)
Exemplo n.º 5
0
    def GET(self, key, value, suffix):
        key = key.lower()
        suffix = suffix or ""

        if key == "isbn":
            if len(value) == 13:
                key = "isbn_13"
            else:
                key = "isbn_10"
        elif key == "oclc":
            key = "oclc_numbers"
        elif key == "ia":
            key = "ocaid"

        if key != 'ocaid': # example: MN41558ucmf_6
            value = value.replace('_', ' ')

        if web.ctx.encoding and web.ctx.path.endswith("." + web.ctx.encoding):
            ext = "." + web.ctx.encoding
        else:
            ext = ""

        if web.ctx.env.get('QUERY_STRING'):
            ext += '?' + web.ctx.env['QUERY_STRING']

        def redirect(key, ext, suffix):
            if ext:
                return web.found(key + ext)
            else:
                book = web.ctx.site.get(key)
                return web.found(book.url(suffix))

        q = {"type": "/type/edition", key: value}
        try:
            result = web.ctx.site.things(q)
            if result:
                raise redirect(result[0], ext, suffix)
            elif key =='ocaid':
                q = {"type": "/type/edition", 'source_records': 'ia:' + value}
                result = web.ctx.site.things(q)
                if result:
                    raise redirect(result[0], ext, suffix)
                q = {"type": "/type/volume", 'ia_id': value}
                result = web.ctx.site.things(q)
                if result:
                    raise redirect(result[0], ext, suffix)
                else:
                    raise redirect("/books/ia:" + value, ext, suffix)
            elif key.startswith("isbn"):
                ed_key = create_edition_from_amazon_metadata(value)
                if ed:
                    raise web.seeother(ed_key)
            web.ctx.status = "404 Not Found"
            return render.notfound(web.ctx.path, create=False)
        except web.HTTPError:
            raise
        except:
            if key.startswith('isbn'):
                ed_key = create_edition_from_amazon_metadata(value)
                if ed_key:
                    raise web.seeother(ed_key)

            logger.error("unexpected error", exc_info=True)
            web.ctx.status = "404 Not Found"
            return render.notfound(web.ctx.path, create=False)