home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_951 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-08-06  |  9.1 KB  |  294 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. __license__ = 'GPL v3'
  5. __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
  6. __docformat__ = 'restructuredtext en'
  7. import traceback
  8. import socket
  9. import re
  10. import sys
  11. from functools import partial
  12. from threading import Thread, Event
  13. from Queue import Queue, Empty
  14. import mechanize
  15. from calibre.customize import Plugin
  16. from calibre import browser, prints
  17. from calibre.ebooks.BeautifulSoup import BeautifulSoup
  18. from calibre.constants import preferred_encoding, DEBUG
  19.  
  20. class CoverDownload(Plugin):
  21.     supported_platforms = [
  22.         'windows',
  23.         'osx',
  24.         'linux']
  25.     author = 'Kovid Goyal'
  26.     type = _('Cover download')
  27.     
  28.     def has_cover(self, mi, ans, timeout = 5):
  29.         raise NotImplementedError()
  30.  
  31.     
  32.     def get_covers(self, mi, result_queue, abort, timeout = 5):
  33.         raise NotImplementedError()
  34.  
  35.     
  36.     def exception_to_string(self, ex):
  37.         
  38.         try:
  39.             return unicode(ex)
  40.         except:
  41.             
  42.             try:
  43.                 return str(ex).decode(preferred_encoding, 'replace')
  44.             return repr(ex)
  45.  
  46.  
  47.  
  48.     
  49.     def debug(self, *args, **kwargs):
  50.         if DEBUG:
  51.             prints('\t' + self.name + ':', *args, **kwargs)
  52.         
  53.  
  54.  
  55.  
  56. class HeadRequest(mechanize.Request):
  57.     
  58.     def get_method(self):
  59.         return 'HEAD'
  60.  
  61.  
  62.  
  63. class OpenLibraryCovers(CoverDownload):
  64.     OPENLIBRARY = 'http://covers.openlibrary.org/b/isbn/%s-L.jpg?default=false'
  65.     name = 'openlibrary.org covers'
  66.     description = _('Download covers from openlibrary.org')
  67.     author = 'Kovid Goyal'
  68.     
  69.     def has_cover(self, mi, ans, timeout = 5):
  70.         if not mi.isbn:
  71.             return False
  72.         br = browser()
  73.         br.set_handle_redirect(False)
  74.         
  75.         try:
  76.             br.open_novisit(HeadRequest(self.OPENLIBRARY % mi.isbn), timeout = timeout)
  77.             self.debug('cover for', mi.isbn, 'found')
  78.             ans.set()
  79.         except Exception:
  80.             mi.isbn
  81.             e = mi.isbn
  82.             if callable(getattr(e, 'getcode', None)) and e.getcode() == 302:
  83.                 self.debug('cover for', mi.isbn, 'found')
  84.                 ans.set()
  85.             else:
  86.                 self.debug(e)
  87.         except:
  88.             e.getcode() == 302
  89.  
  90.  
  91.     
  92.     def get_covers(self, mi, result_queue, abort, timeout = 5):
  93.         if not mi.isbn:
  94.             return None
  95.         br = browser()
  96.         
  97.         try:
  98.             ans = br.open(self.OPENLIBRARY % mi.isbn, timeout = timeout).read()
  99.             result_queue.put((True, ans, 'jpg', self.name))
  100.         except Exception:
  101.             mi.isbn
  102.             e = mi.isbn
  103.             if callable(getattr(e, 'getcode', None)) and e.getcode() == 404:
  104.                 result_queue.put((False, _('ISBN: %s not found') % mi.isbn, '', self.name))
  105.             else:
  106.                 result_queue.put((False, self.exception_to_string(e), traceback.format_exc(), self.name))
  107.         except:
  108.             e.getcode() == 404
  109.  
  110.  
  111.  
  112.  
  113. class LibraryThingCovers(CoverDownload):
  114.     name = 'librarything.com covers'
  115.     description = _('Download covers from librarything.com')
  116.     author = 'Kovid Goyal'
  117.     LIBRARYTHING = 'http://www.librarything.com/isbn/'
  118.     
  119.     def get_cover_url(self, isbn, br, timeout = 5):
  120.         
  121.         try:
  122.             src = br.open_novisit('http://www.librarything.com/isbn/' + isbn, timeout = timeout).read().decode('utf-8', 'replace')
  123.         except Exception:
  124.             err = None
  125.             if isinstance(getattr(err, 'args', [
  126.                 None])[0], socket.timeout):
  127.                 err = Exception(_('LibraryThing.com timed out. Try again later.'))
  128.             
  129.             raise err
  130.  
  131.         s = BeautifulSoup(src)
  132.         url = s.find('td', attrs = {
  133.             'class': 'left' })
  134.         if url is None:
  135.             if s.find('div', attrs = {
  136.                 'class': 'highloadwarning' }) is not None:
  137.                 raise Exception(_('Could not fetch cover as server is experiencing high load. Please try again later.'))
  138.             s.find('div', attrs = {
  139.                 'class': 'highloadwarning' }) is not None
  140.             raise Exception(_('ISBN: %s not found') % isbn)
  141.         url is None
  142.         url = url.find('img')
  143.         if url is None:
  144.             raise Exception(_('LibraryThing.com server error. Try again later.'))
  145.         url is None
  146.         url = re.sub('_S[XY]\\d+', '', url['src'])
  147.         return url
  148.  
  149.     
  150.     def has_cover(self, mi, ans, timeout = 5):
  151.         if not mi.isbn:
  152.             return False
  153.         br = browser()
  154.         
  155.         try:
  156.             self.get_cover_url(mi.isbn, br, timeout = timeout)
  157.             self.debug('cover for', mi.isbn, 'found')
  158.             ans.set()
  159.         except Exception:
  160.             mi.isbn
  161.             e = mi.isbn
  162.             self.debug(e)
  163.         except:
  164.             mi.isbn
  165.  
  166.  
  167.     
  168.     def get_covers(self, mi, result_queue, abort, timeout = 5):
  169.         if not mi.isbn:
  170.             return None
  171.         br = browser()
  172.         
  173.         try:
  174.             url = self.get_cover_url(mi.isbn, br, timeout = timeout)
  175.             cover_data = br.open_novisit(url).read()
  176.             result_queue.put((True, cover_data, 'jpg', self.name))
  177.         except Exception:
  178.             mi.isbn
  179.             e = mi.isbn
  180.             result_queue.put((False, self.exception_to_string(e), traceback.format_exc(), self.name))
  181.         except:
  182.             mi.isbn
  183.  
  184.  
  185.  
  186.  
  187. def check_for_cover(mi, timeout = 5):
  188.     cover_sources = cover_sources
  189.     import calibre.customize.ui
  190.     ans = Event()
  191.     checkers = [ partial(p.has_cover, mi, ans, timeout = timeout) for p in cover_sources() ]
  192.     workers = [ Thread(target = c) for c in checkers ]
  193.     for w in workers:
  194.         w.daemon = True
  195.         w.start()
  196.     
  197.     for w in workers:
  198.         if _[3](_[3][int(w.is_alive())]) == 0:
  199.             break
  200.             continue
  201.         []
  202.         []
  203.     return ans.is_set()
  204.  
  205.  
  206. def download_covers(mi, result_queue, max_covers = 50, timeout = 5):
  207.     cover_sources = cover_sources
  208.     import calibre.customize.ui
  209.     abort = Event()
  210.     temp = Queue()
  211.     getters = [ partial(p.get_covers, mi, temp, abort, timeout = timeout) for p in cover_sources() ]
  212.     workers = [ Thread(target = c) for c in getters ]
  213.     for w in workers:
  214.         w.daemon = True
  215.         w.start()
  216.     
  217.     count = 0
  218.     for w in workers:
  219.         if _[3](_[3][int(w.is_alive())]) == 0:
  220.             break
  221.             continue
  222.         []
  223.         []
  224.     abort.set()
  225.     while True:
  226.         
  227.         try:
  228.             result = temp.get_nowait()
  229.             count += 1
  230.             result_queue.put(result)
  231.         continue
  232.         except Empty:
  233.             sum
  234.             sum
  235.             []
  236.             break
  237.             continue
  238.             []
  239.         
  240.  
  241.         sum<EXCEPTION MATCH>Empty
  242.  
  243.  
  244. def download_cover(mi, timeout = 5):
  245.     results = Queue()
  246.     download_covers(mi, results, max_covers = 1, timeout = timeout)
  247.     errors = []
  248.     ans = None
  249.     while True:
  250.         
  251.         try:
  252.             x = results.get_nowait()
  253.             if x[0]:
  254.                 ans = x[1]
  255.             else:
  256.                 errors.append(x)
  257.         continue
  258.         except Empty:
  259.             break
  260.             continue
  261.         
  262.  
  263.         None<EXCEPTION MATCH>Empty
  264.     return (ans, errors)
  265.  
  266.  
  267. def test(isbns):
  268.     MetaInformation = MetaInformation
  269.     import calibre.ebooks.metadata
  270.     mi = MetaInformation('test', [
  271.         'test'])
  272.     for isbn in isbns:
  273.         prints('Testing ISBN:', isbn)
  274.         mi.isbn = isbn
  275.         found = check_for_cover(mi)
  276.         prints('Has cover:', found)
  277.         (ans, errors) = download_cover(mi)
  278.         if ans is not None:
  279.             prints('Cover downloaded')
  280.         else:
  281.             prints('Download failed:')
  282.             for err in errors:
  283.                 prints('\t', err[-1] + ':', err[1])
  284.             
  285.         print '\n'
  286.     
  287.  
  288. if __name__ == '__main__':
  289.     isbns = sys.argv[1:] + [
  290.         '9781591025412',
  291.         '9780307272119']
  292.     test(isbns)
  293.  
  294.