home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 January / maximum-cd-2011-01.iso / DiscContents / calibre-0.7.26.msi / file_943 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-10-31  |  20.4 KB  |  573 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 copy
  8. import traceback
  9. from calibre import prints
  10. from calibre.constants import DEBUG
  11. from calibre.ebooks.metadata.book import SC_COPYABLE_FIELDS
  12. from calibre.ebooks.metadata.book import SC_FIELDS_COPY_NOT_NULL
  13. from calibre.ebooks.metadata.book import STANDARD_METADATA_FIELDS
  14. from calibre.ebooks.metadata.book import TOP_LEVEL_CLASSIFIERS
  15. from calibre.ebooks.metadata.book import ALL_METADATA_FIELDS
  16. from calibre.library.field_metadata import FieldMetadata
  17. from calibre.utils.date import isoformat, format_date
  18. from calibre.utils.formatter import TemplateFormatter
  19. NULL_VALUES = {
  20.     'user_metadata': { },
  21.     'cover_data': (None, None),
  22.     'tags': [],
  23.     'classifiers': { },
  24.     'languages': [],
  25.     'device_collections': [],
  26.     'author_sort_map': { },
  27.     'authors': [
  28.         _('Unknown')],
  29.     'title': _('Unknown'),
  30.     'language': 'und' }
  31. field_metadata = FieldMetadata()
  32.  
  33. class SafeFormat(TemplateFormatter):
  34.     
  35.     def get_value(self, key, args, kwargs):
  36.         
  37.         try:
  38.             if key != 'title_sort':
  39.                 key = field_metadata.search_term_to_field_key(key.lower())
  40.             
  41.             b = self.book.get_user_metadata(key, False)
  42.             if b and b['datatype'] == 'int' and self.book.get(key, 0) == 0:
  43.                 v = ''
  44.             elif b and b['datatype'] == 'float' and self.book.get(key, 0) == 0:
  45.                 v = ''
  46.             else:
  47.                 (ign, v) = self.book.format_field(key.lower(), series_with_index = False)
  48.             if v is None:
  49.                 return ''
  50.             if v == '':
  51.                 return ''
  52.             return v
  53.         except:
  54.             if DEBUG:
  55.                 traceback.print_exc()
  56.             
  57.             return key
  58.  
  59.  
  60.  
  61. composite_formatter = SafeFormat()
  62.  
  63. class Metadata(object):
  64.     
  65.     def __init__(self, title, authors = (_('Unknown'),), other = None):
  66.         _data = copy.deepcopy(NULL_VALUES)
  67.         object.__setattr__(self, '_data', _data)
  68.         if other is not None:
  69.             self.smart_update(other)
  70.         elif title:
  71.             self.title = title
  72.         
  73.         if authors:
  74.             self.author = None if authors else []
  75.             self.authors = None if authors else []
  76.         
  77.  
  78.     
  79.     def is_null(self, field):
  80.         null_val = NULL_VALUES.get(field, None)
  81.         val = getattr(self, field, None)
  82.         if not not val:
  83.             pass
  84.         return val == null_val
  85.  
  86.     
  87.     def __getattribute__(self, field):
  88.         _data = object.__getattribute__(self, '_data')
  89.         if field in TOP_LEVEL_CLASSIFIERS:
  90.             return _data.get('classifiers').get(field, None)
  91.         if field in STANDARD_METADATA_FIELDS:
  92.             return _data.get(field, None)
  93.         
  94.         try:
  95.             return object.__getattribute__(self, field)
  96.         except AttributeError:
  97.             field in STANDARD_METADATA_FIELDS
  98.             field in STANDARD_METADATA_FIELDS
  99.             field in TOP_LEVEL_CLASSIFIERS
  100.         except:
  101.             field in STANDARD_METADATA_FIELDS
  102.  
  103.         if field in _data['user_metadata'].iterkeys():
  104.             d = _data['user_metadata'][field]
  105.             val = d['#value#']
  106.             if d['datatype'] != 'composite':
  107.                 return val
  108.             return val
  109.         raise AttributeError('Metadata object has no attribute named: ' + repr(field))
  110.  
  111.     
  112.     def __setattr__(self, field, val, extra = None):
  113.         _data = object.__getattribute__(self, '_data')
  114.         if field in TOP_LEVEL_CLASSIFIERS:
  115.             _data['classifiers'].update({
  116.                 field: val })
  117.         elif field in STANDARD_METADATA_FIELDS:
  118.             if val is None:
  119.                 val = NULL_VALUES.get(field, None)
  120.             
  121.             _data[field] = val
  122.         elif field in _data['user_metadata'].iterkeys():
  123.             if _data['user_metadata'][field]['datatype'] == 'composite':
  124.                 _data['user_metadata'][field]['#value#'] = None
  125.             else:
  126.                 _data['user_metadata'][field]['#value#'] = val
  127.             _data['user_metadata'][field]['#extra#'] = extra
  128.         else:
  129.             self.__dict__[field] = val
  130.  
  131.     
  132.     def __iter__(self):
  133.         return object.__getattribute__(self, '_data').iterkeys()
  134.  
  135.     
  136.     def has_key(self, key):
  137.         return key in object.__getattribute__(self, '_data')
  138.  
  139.     
  140.     def deepcopy(self):
  141.         m = Metadata(None)
  142.         m.__dict__ = copy.deepcopy(self.__dict__)
  143.         object.__setattr__(m, '_data', copy.deepcopy(object.__getattribute__(self, '_data')))
  144.         return m
  145.  
  146.     
  147.     def deepcopy_metadata(self):
  148.         m = Metadata(None)
  149.         object.__setattr__(m, '_data', copy.deepcopy(object.__getattribute__(self, '_data')))
  150.         return m
  151.  
  152.     
  153.     def get(self, field, default = None):
  154.         
  155.         try:
  156.             return self.__getattribute__(field)
  157.         except AttributeError:
  158.             return default
  159.  
  160.  
  161.     
  162.     def get_extra(self, field):
  163.         _data = object.__getattribute__(self, '_data')
  164.         if field in _data['user_metadata'].iterkeys():
  165.             return _data['user_metadata'][field]['#extra#']
  166.         raise AttributeError('Metadata object has no attribute named: ' + repr(field))
  167.  
  168.     
  169.     def set(self, field, val, extra = None):
  170.         self.__setattr__(field, val, extra)
  171.  
  172.     
  173.     def get_classifiers(self):
  174.         return copy.deepcopy(object.__getattribute__(self, '_data')['classifiers'])
  175.  
  176.     
  177.     def set_classifiers(self, classifiers):
  178.         object.__getattribute__(self, '_data')['classifiers'] = classifiers
  179.  
  180.     
  181.     def standard_field_keys(self):
  182.         return STANDARD_METADATA_FIELDS
  183.  
  184.     
  185.     def custom_field_keys(self):
  186.         return object.__getattribute__(self, '_data')['user_metadata'].iterkeys()
  187.  
  188.     
  189.     def all_field_keys(self):
  190.         _data = object.__getattribute__(self, '_data')
  191.         return frozenset(ALL_METADATA_FIELDS.union(_data['user_metadata'].iterkeys()))
  192.  
  193.     
  194.     def metadata_for_field(self, key):
  195.         if key not in self.custom_field_keys():
  196.             return self.get_standard_metadata(key, make_copy = False)
  197.         return self.get_user_metadata(key, make_copy = False)
  198.  
  199.     
  200.     def all_non_none_fields(self):
  201.         result = { }
  202.         _data = object.__getattribute__(self, '_data')
  203.         for attr in STANDARD_METADATA_FIELDS:
  204.             v = _data.get(attr, None)
  205.             if v is not None:
  206.                 result[attr] = v
  207.                 continue
  208.         
  209.         for attr in TOP_LEVEL_CLASSIFIERS:
  210.             v = self.get(attr, None)
  211.             if v is not None:
  212.                 result[attr] = v
  213.                 continue
  214.         
  215.         for attr in _data['user_metadata'].iterkeys():
  216.             v = self.get(attr, None)
  217.             if v is not None:
  218.                 result[attr] = v
  219.                 if _data['user_metadata'][attr]['datatype'] == 'series':
  220.                     result[attr + '_index'] = _data['user_metadata'][attr]['#extra#']
  221.                 
  222.             _data['user_metadata'][attr]['datatype'] == 'series'
  223.         
  224.         return result
  225.  
  226.     
  227.     def get_standard_metadata(self, field, make_copy):
  228.         if field in field_metadata and field_metadata[field]['kind'] == 'field':
  229.             if make_copy:
  230.                 return copy.deepcopy(field_metadata[field])
  231.             return field_metadata[field]
  232.  
  233.     
  234.     def get_all_standard_metadata(self, make_copy):
  235.         if not make_copy:
  236.             return field_metadata
  237.         res = { }
  238.         for k in field_metadata:
  239.             if field_metadata[k]['kind'] == 'field':
  240.                 res[k] = copy.deepcopy(field_metadata[k])
  241.                 continue
  242.             make_copy
  243.         
  244.         return res
  245.  
  246.     
  247.     def get_all_user_metadata(self, make_copy):
  248.         _data = object.__getattribute__(self, '_data')
  249.         user_metadata = _data['user_metadata']
  250.         if not make_copy:
  251.             return user_metadata
  252.         res = { }
  253.         for k in user_metadata:
  254.             res[k] = copy.deepcopy(user_metadata[k])
  255.         
  256.         return res
  257.  
  258.     
  259.     def get_user_metadata(self, field, make_copy):
  260.         _data = object.__getattribute__(self, '_data')
  261.         _data = _data['user_metadata']
  262.         if field in _data:
  263.             if make_copy:
  264.                 return copy.deepcopy(_data[field])
  265.             return _data[field]
  266.  
  267.     
  268.     def set_all_user_metadata(self, metadata):
  269.         if metadata is None:
  270.             traceback.print_stack()
  271.         else:
  272.             for key in metadata:
  273.                 self.set_user_metadata(key, metadata[key])
  274.             
  275.  
  276.     
  277.     def set_user_metadata(self, field, metadata):
  278.         if field is not None:
  279.             if not field.startswith('#'):
  280.                 raise AttributeError("Custom field name %s must begin with '#'" % repr(field))
  281.             field.startswith('#')
  282.             if metadata is None:
  283.                 traceback.print_stack()
  284.                 return None
  285.             metadata = copy.deepcopy(metadata)
  286.             if '#value#' not in metadata:
  287.                 if metadata['datatype'] == 'text' and metadata['is_multiple']:
  288.                     metadata['#value#'] = []
  289.                 else:
  290.                     metadata['#value#'] = None
  291.             
  292.             _data = object.__getattribute__(self, '_data')
  293.             _data['user_metadata'][field] = metadata
  294.         
  295.  
  296.     
  297.     def template_to_attribute(self, other, ops):
  298.         if not ops:
  299.             return None
  300.         for op in ops:
  301.             
  302.             try:
  303.                 src = op[0]
  304.                 dest = op[1]
  305.                 val = composite_formatter.safe_format(src, other, 'PLUGBOARD TEMPLATE ERROR', other)
  306.                 if dest == 'tags':
  307.                     []([], _[1])
  308.                 elif dest == 'authors':
  309.                     []([], _[2])
  310.                 else:
  311.                     self.set(dest, val)
  312.             continue
  313.             if DEBUG:
  314.                 traceback.print_exc()
  315.             
  316.  
  317.         
  318.  
  319.     
  320.     def print_all_attributes(self):
  321.         for x in STANDARD_METADATA_FIELDS:
  322.             prints('%s:' % x, getattr(self, x, 'None'))
  323.         
  324.         for x in self.custom_field_keys():
  325.             meta = self.get_user_metadata(x, make_copy = False)
  326.             if meta is not None:
  327.                 prints(x, meta)
  328.                 continue
  329.         
  330.         prints('--------------')
  331.  
  332.     
  333.     def smart_update(self, other, replace_metadata = False):
  334.         
  335.         def copy_not_none(dest, src, attr):
  336.             v = getattr(src, attr, None)
  337.             if v not in (None, NULL_VALUES.get(attr, None)):
  338.                 setattr(dest, attr, copy.deepcopy(v))
  339.             
  340.  
  341.         if other.title and other.title != _('Unknown'):
  342.             self.title = other.title
  343.             if hasattr(other, 'title_sort'):
  344.                 self.title_sort = other.title_sort
  345.             
  346.         
  347.         if other.authors and other.authors[0] != _('Unknown'):
  348.             self.authors = list(other.authors)
  349.             if hasattr(other, 'author_sort_map'):
  350.                 self.author_sort_map = dict(other.author_sort_map)
  351.             
  352.             if hasattr(other, 'author_sort'):
  353.                 self.author_sort = other.author_sort
  354.             
  355.         
  356.         other_lang = getattr(other, 'language', None)
  357.         if other_lang and other_lang.lower() != 'und':
  358.             self.language = other_lang
  359.         
  360.  
  361.     
  362.     def format_series_index(self, val = None):
  363.         fmt_sidx = fmt_sidx
  364.         import calibre.ebooks.metadata
  365.         v = None if val is None else val
  366.         
  367.         try:
  368.             x = float(v)
  369.         except (ValueError, TypeError):
  370.             x = 1
  371.  
  372.         return fmt_sidx(x)
  373.  
  374.     
  375.     def authors_from_string(self, raw):
  376.         string_to_authors = string_to_authors
  377.         import calibre.ebooks.metadata
  378.         self.authors = string_to_authors(raw)
  379.  
  380.     
  381.     def format_authors(self):
  382.         authors_to_string = authors_to_string
  383.         import calibre.ebooks.metadata
  384.         return authors_to_string(self.authors)
  385.  
  386.     
  387.     def format_tags(self):
  388.         return []([ unicode(t) for t in self.tags ])
  389.  
  390.     
  391.     def format_rating(self):
  392.         return unicode(self.rating)
  393.  
  394.     
  395.     def format_field(self, key, series_with_index = True):
  396.         (name, val, ign, ign) = self.format_field_extended(key, series_with_index)
  397.         return (name, val)
  398.  
  399.     
  400.     def format_field_extended(self, key, series_with_index = True):
  401.         authors_to_string = authors_to_string
  402.         import calibre.ebooks.metadata
  403.         if key.startswith('#') and key.endswith('_index'):
  404.             tkey = key[:-6]
  405.             cmeta = self.get_user_metadata(tkey, make_copy = False)
  406.             if cmeta and cmeta['datatype'] == 'series':
  407.                 if self.get(tkey):
  408.                     res = self.get_extra(tkey)
  409.                     return (unicode(cmeta['name'] + '_index'), self.format_series_index(res), res, cmeta)
  410.                 return (unicode(cmeta['name'] + '_index'), '', '', cmeta)
  411.             cmeta['datatype'] == 'series'
  412.         
  413.         if key in self.custom_field_keys():
  414.             res = self.get(key, None)
  415.             cmeta = self.get_user_metadata(key, make_copy = False)
  416.             name = unicode(cmeta['name'])
  417.             if cmeta['datatype'] != 'composite':
  418.                 if res is None or res == '':
  419.                     return (name, res, None, None)
  420.                 orig_res = res
  421.                 cmeta = self.get_user_metadata(key, make_copy = False)
  422.                 if res is None or res == '':
  423.                     return (name, res, None, None)
  424.                 orig_res = res
  425.                 datatype = cmeta['datatype']
  426.                 if datatype == 'text' and cmeta['is_multiple']:
  427.                     res = u', '.join(res)
  428.                 elif datatype == 'series' and series_with_index:
  429.                     if self.get_extra(key) is not None:
  430.                         res = res + ' [%s]' % self.format_series_index(val = self.get_extra(key))
  431.                     
  432.                 elif datatype == 'datetime':
  433.                     res = format_date(res, cmeta['display'].get('date_format', 'dd MMM yyyy'))
  434.                 elif datatype == 'bool':
  435.                     res = res == '' if res else _('No')
  436.                 
  437.             return (name, unicode(res), orig_res, cmeta)
  438.         fmkey = field_metadata.search_term_to_field_key(key)
  439.         if fmkey in field_metadata and field_metadata[fmkey]['kind'] == 'field':
  440.             res = self.get(key, None)
  441.             fmeta = field_metadata[fmkey]
  442.             name = unicode(fmeta['name'])
  443.             if res is None or res == '':
  444.                 return (name, res, None, None)
  445.             orig_res = res
  446.             name = unicode(fmeta['name'])
  447.             datatype = fmeta['datatype']
  448.             if key == 'authors':
  449.                 res = authors_to_string(res)
  450.             elif key == 'series_index':
  451.                 res = self.format_series_index(res)
  452.             elif datatype == 'text' and fmeta['is_multiple']:
  453.                 res = u', '.join(res)
  454.             elif datatype == 'series' and series_with_index:
  455.                 res = res + ' [%s]' % self.format_series_index()
  456.             elif datatype == 'datetime':
  457.                 res = format_date(res, fmeta['display'].get('date_format', 'dd MMM yyyy'))
  458.             
  459.             return (name, unicode(res), orig_res, fmeta)
  460.         return (None, None, None, None)
  461.  
  462.     
  463.     def __unicode__(self):
  464.         authors_to_string = authors_to_string
  465.         import calibre.ebooks.metadata
  466.         ans = []
  467.         
  468.         def fmt(x, y):
  469.             ans.append(u'%-20s: %s' % (unicode(x), unicode(y)))
  470.  
  471.         fmt('Title', self.title)
  472.         if self.title_sort:
  473.             fmt('Title sort', self.title_sort)
  474.         
  475.         if self.authors:
  476.             None(fmt, 'Author(s)' + authors_to_string(self.authors) if self.author_sort else '')
  477.         
  478.         if self.publisher:
  479.             fmt('Publisher', self.publisher)
  480.         
  481.         if getattr(self, 'book_producer', False):
  482.             fmt('Book Producer', self.book_producer)
  483.         
  484.         if self.comments:
  485.             fmt('Comments', self.comments)
  486.         
  487.         if self.isbn:
  488.             fmt('ISBN', self.isbn)
  489.         
  490.         if self.series:
  491.             fmt('Series', self.series + ' #%s' % self.format_series_index())
  492.         
  493.         if self.language:
  494.             fmt('Language', self.language)
  495.         
  496.         if self.rating is not None:
  497.             fmt('Rating', self.rating)
  498.         
  499.         if self.timestamp is not None:
  500.             fmt('Timestamp', isoformat(self.timestamp))
  501.         
  502.         if self.pubdate is not None:
  503.             fmt('Published', isoformat(self.pubdate))
  504.         
  505.         if self.rights is not None:
  506.             fmt('Rights', unicode(self.rights))
  507.         
  508.         for key in self.custom_field_keys():
  509.             val = self.get(key, None)
  510.             if val:
  511.                 (name, val) = self.format_field(key)
  512.                 fmt(name, unicode(val))
  513.                 continue
  514.         
  515.         return u'\n'.join(ans)
  516.  
  517.     
  518.     def to_html(self):
  519.         authors_to_string = authors_to_string
  520.         import calibre.ebooks.metadata
  521.         ans = [
  522.             (_('Title'), unicode(self.title))]
  523.         None += [
  524.             (ans, _('Author(s)') if self.authors else _('Unknown'))]
  525.         ans += [
  526.             (_('Publisher'), unicode(self.publisher))]
  527.         ans += [
  528.             (_('Producer'), unicode(self.book_producer))]
  529.         ans += [
  530.             (_('Comments'), unicode(self.comments))]
  531.         ans += [
  532.             ('ISBN', unicode(self.isbn))]
  533.         u', '.join += [
  534.             ([], []([ unicode(t) for t in self.tags ]))]
  535.         ans += [
  536.             (_('Language'), unicode(self.language))]
  537.         if self.timestamp is not None:
  538.             ans += [
  539.                 (_('Timestamp'), unicode(self.timestamp.isoformat(' ')))]
  540.         
  541.         if self.pubdate is not None:
  542.             ans += [
  543.                 (_('Published'), unicode(self.pubdate.isoformat(' ')))]
  544.         
  545.         if self.rights is not None:
  546.             ans += [
  547.                 (_('Rights'), unicode(self.rights))]
  548.         
  549.         for key in self.custom_field_keys():
  550.             val = self.get(key, None)
  551.             if val:
  552.                 (name, val) = self.format_field(key)
  553.                 ans += [
  554.                     (name, val)]
  555.                 continue
  556.         
  557.         for i, x in enumerate(ans):
  558.             ans[i] = u'<tr><td><b>%s</b></td><td>%s</td></tr>' % x
  559.         
  560.         return u'<table>%s</table>' % u'\n'.join(ans)
  561.  
  562.     
  563.     def __str__(self):
  564.         return self.__unicode__().encode('utf-8')
  565.  
  566.     
  567.     def __nonzero__(self):
  568.         if not self.title and self.author and self.comments:
  569.             pass
  570.         return bool(self.tags)
  571.  
  572.  
  573.