home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_960 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  6.1 KB  |  154 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 import MetaInformation
  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(MetaInformation):
  48.     
  49.     def __init__(self, book):
  50.         MetaInformation.__init__(self, None, [])
  51.         self.isbn = book.get('isbn13', book.get('isbn'))
  52.         self.title = book.find('titlelong').string
  53.         if not self.title:
  54.             self.title = book.find('title').string
  55.         
  56.         self.title = unicode(self.title).strip()
  57.         au = unicode(book.find('authorstext').string).strip()
  58.         temp = au.split(',')
  59.         self.authors = []
  60.         for au in temp:
  61.             if not au:
  62.                 continue
  63.             
  64.             []([ a.strip() for a in au.split('&') ])
  65.         
  66.         
  67.         try:
  68.             self.author_sort = book.find('authors').find('person').string
  69.             if self.authors and self.author_sort == self.authors[0]:
  70.                 self.author_sort = None
  71.         except:
  72.             []
  73.             self.authors.extend
  74.  
  75.         self.publisher = book.find('publishertext').string
  76.         summ = book.find('summary')
  77.  
  78.  
  79.  
  80. def build_isbn(base_url, opts):
  81.     return base_url + 'index1=isbn&value1=' + opts.isbn
  82.  
  83.  
  84. def build_combined(base_url, opts):
  85.     query = ''
  86.     for e in (opts.title, opts.author, opts.publisher):
  87.         if e is not None:
  88.             query += ' ' + e
  89.             continue
  90.     
  91.     query = query.strip()
  92.     if len(query) == 0:
  93.         raise ISBNDBError('You must specify at least one of --author, --title or --publisher')
  94.     len(query) == 0
  95.     query = re.sub('\\s+', '+', query)
  96.     if isinstance(query, unicode):
  97.         query = query.encode('utf-8')
  98.     
  99.     return base_url + 'index1=combined&value1=' + quote(query, '+')
  100.  
  101.  
  102. def option_parser():
  103.     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'))
  104.     parser.add_option('-i', '--isbn', default = None, dest = 'isbn', help = _('The ISBN ID of the book you want metadata for.'))
  105.     parser.add_option('-a', '--author', dest = 'author', default = None, help = _('The author whose book to search for.'))
  106.     parser.add_option('-t', '--title', dest = 'title', default = None, help = _('The title of the book to search for.'))
  107.     parser.add_option('-p', '--publisher', default = None, dest = 'publisher', help = _('The publisher of the book to search for.'))
  108.     parser.add_option('-v', '--verbose', default = False, action = 'store_true', help = _('Verbose processing'))
  109.     return parser
  110.  
  111.  
  112. def create_books(opts, args, timeout = 5):
  113.     base_url = BASE_URL % dict(key = args[1])
  114.     if opts.isbn is not None:
  115.         url = build_isbn(base_url, opts)
  116.     else:
  117.         url = build_combined(base_url, opts)
  118.     if opts.verbose:
  119.         print 'ISBNDB query: ' + url
  120.     
  121.     tans = [ ISBNDBMetadata(book) for book in fetch_metadata(url, timeout = timeout) ]
  122.     ans = []
  123.     for x in tans:
  124.         add = True
  125.         for y in ans:
  126.             if y.isbn == x.isbn:
  127.                 add = False
  128.                 continue
  129.             []
  130.         
  131.         if add:
  132.             ans.append(x)
  133.             continue
  134.         []
  135.     
  136.     return ans
  137.  
  138.  
  139. def main(args = sys.argv):
  140.     parser = option_parser()
  141.     (opts, args) = parser.parse_args(args)
  142.     if len(args) != 2:
  143.         parser.print_help()
  144.         print 'You must supply the isbndb.com key'
  145.         return 1
  146.     for book in create_books(opts, args):
  147.         print unicode(book).encode('utf-8')
  148.     
  149.     return 0
  150.  
  151. if __name__ == '__main__':
  152.     sys.exit(main())
  153.  
  154.