home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 January / maximum-cd-2011-01.iso / DiscContents / calibre-0.7.26.msi / file_956 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-10-31  |  6.4 KB  |  166 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __license__ = 'GPL v3'
  5. __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
  6. import sys
  7. import re
  8. from urllib import quote
  9. from calibre.utils.config import OptionParser
  10. from calibre.ebooks.metadata.book.base import Metadata
  11. from calibre.ebooks.BeautifulSoup import BeautifulStoneSoup
  12. from calibre import browser
  13. BASE_URL = 'http://isbndb.com/api/books.xml?access_key=%(key)s&page_number=1&results=subjects,authors,texts&'
  14.  
  15. class ISBNDBError(Exception):
  16.     pass
  17.  
  18.  
  19. def fetch_metadata(url, max = 100, timeout = 5):
  20.     books = []
  21.     page_number = 1
  22.     total_results = sys.maxint
  23.     br = browser()
  24.     while len(books) < total_results and max > 0:
  25.         
  26.         try:
  27.             raw = br.open(url, timeout = timeout).read()
  28.         except Exception:
  29.             err = None
  30.             raise ISBNDBError('Could not fetch ISBNDB metadata. Error: ' + str(err))
  31.  
  32.         soup = BeautifulStoneSoup(raw, convertEntities = BeautifulStoneSoup.XML_ENTITIES)
  33.         book_list = soup.find('booklist')
  34.         if book_list is None:
  35.             errmsg = soup.find('errormessage').string
  36.             raise ISBNDBError('Error fetching metadata: ' + errmsg)
  37.         book_list is None
  38.         total_results = int(book_list['total_results'])
  39.         page_number += 1
  40.         np = '&page_number=%s&' % page_number
  41.         url = re.sub('\\&page_number=\\d+\\&', np, url)
  42.         books.extend(book_list.findAll('bookdata'))
  43.         max -= 1
  44.     return books
  45.  
  46.  
  47. class ISBNDBMetadata(Metadata):
  48.     
  49.     def __init__(self, book):
  50.         Metadata.__init__(self, None)
  51.         
  52.         def tostring(e):
  53.             if not hasattr(e, 'string'):
  54.                 return None
  55.             ans = e.string
  56.             if ans is not None:
  57.                 ans = unicode(ans).strip()
  58.             
  59.             if not ans:
  60.                 ans = None
  61.             
  62.             return ans
  63.  
  64.         self.isbn = unicode(book.get('isbn13', book.get('isbn')))
  65.         title = tostring(book.find('titlelong'))
  66.         if not title:
  67.             title = tostring(book.find('title'))
  68.         
  69.         self.title = title
  70.         self.title = unicode(self.title).strip()
  71.         authors = []
  72.         au = tostring(book.find('authorstext'))
  73.         if authors:
  74.             self.authors = authors
  75.         
  76.         
  77.         try:
  78.             self.author_sort = tostring(book.find('authors').find('person'))
  79.             if self.authors and self.author_sort == self.authors[0]:
  80.                 self.author_sort = None
  81.         except:
  82.             pass
  83.  
  84.         self.publisher = tostring(book.find('publishertext'))
  85.         summ = tostring(book.find('summary'))
  86.         if summ:
  87.             self.comments = 'SUMMARY:\n' + summ
  88.         
  89.  
  90.  
  91.  
  92. def build_isbn(base_url, opts):
  93.     return base_url + 'index1=isbn&value1=' + opts.isbn
  94.  
  95.  
  96. def build_combined(base_url, opts):
  97.     query = ''
  98.     for e in (opts.title, opts.author, opts.publisher):
  99.         if e is not None:
  100.             query += ' ' + e
  101.             continue
  102.     
  103.     query = query.strip()
  104.     if len(query) == 0:
  105.         raise ISBNDBError('You must specify at least one of --author, --title or --publisher')
  106.     len(query) == 0
  107.     query = re.sub('\\s+', '+', query)
  108.     if isinstance(query, unicode):
  109.         query = query.encode('utf-8')
  110.     
  111.     return base_url + 'index1=combined&value1=' + quote(query, '+')
  112.  
  113.  
  114. def option_parser():
  115.     parser = OptionParser(usage = _('\n%prog [options] key\n\nFetch metadata for books from isndb.com. You can specify either the\nbooks ISBN ID or its title and author. If you specify the title and author,\nthen more than one book may be returned.\n\nkey is the account key you generate after signing up for a free account from isbndb.com.\n\n'))
  116.     parser.add_option('-i', '--isbn', default = None, dest = 'isbn', help = _('The ISBN ID of the book you want metadata for.'))
  117.     parser.add_option('-a', '--author', dest = 'author', default = None, help = _('The author whose book to search for.'))
  118.     parser.add_option('-t', '--title', dest = 'title', default = None, help = _('The title of the book to search for.'))
  119.     parser.add_option('-p', '--publisher', default = None, dest = 'publisher', help = _('The publisher of the book to search for.'))
  120.     parser.add_option('-v', '--verbose', default = False, action = 'store_true', help = _('Verbose processing'))
  121.     return parser
  122.  
  123.  
  124. def create_books(opts, args, timeout = 5):
  125.     base_url = BASE_URL % dict(key = args[1])
  126.     if opts.isbn is not None:
  127.         url = build_isbn(base_url, opts)
  128.     else:
  129.         url = build_combined(base_url, opts)
  130.     if opts.verbose:
  131.         print 'ISBNDB query: ' + url
  132.     
  133.     tans = [ ISBNDBMetadata(book) for book in fetch_metadata(url, timeout = timeout) ]
  134.     ans = []
  135.     for x in tans:
  136.         add = True
  137.         for y in ans:
  138.             if y.isbn == x.isbn:
  139.                 add = False
  140.                 continue
  141.             []
  142.         
  143.         if add:
  144.             ans.append(x)
  145.             continue
  146.         []
  147.     
  148.     return ans
  149.  
  150.  
  151. def main(args = sys.argv):
  152.     parser = option_parser()
  153.     (opts, args) = parser.parse_args(args)
  154.     if len(args) != 2:
  155.         parser.print_help()
  156.         print 'You must supply the isbndb.com key'
  157.         return 1
  158.     for book in create_books(opts, args):
  159.         print unicode(book).encode('utf-8')
  160.     
  161.     return 0
  162.  
  163. if __name__ == '__main__':
  164.     sys.exit(main())
  165.  
  166.