4 from time import mktime
5 from shutil import copyfileobj
6 from zipfile import ZipFile
7 from .config import get_config
13 _compile_format = True
14 _compiled_format = '%(file)s'
17 def _do_compile_format():
18 global _format, _compile_format, _compiled_format
20 _compile_format = False
22 _format = get_config().get('download', 'format')
38 new_format = u'%(author)s'
40 new_format = u'%(extension)s'
42 new_format = u'%(file)s'
44 new_format = u'%(gname)s'
46 new_format = u'%(gtitle)s'
48 new_format = u'%(language)s'
50 new_format = u'%(ser_no)d'
52 new_format = u'%(series)s'
54 new_format = u'%(title)s'
56 raise ValueError('Bad format specifier "%%%c"' % c)
57 compiled.append(new_format)
60 _compiled_format = ''.join(compiled)
66 def download(book, path=None):
69 if _library_path is None:
70 _library_path = get_config().get('library', 'path')
73 global _compiled_format
75 if _compiled_format[-1] in ('\0', '\\', '/'):
76 raise ValueError('Bad format: "%s"' % _compiled_format)
78 bdict['author'] = book.authors[0].fullname
79 bdict['extension'] = book.extension.name
80 bdict['file'] = book.file
81 genre = book.genres[0]
82 bdict['gname'] = genre.name
83 bdict['gtitle'] = genre.title
84 bdict['language'] = book.language.name
85 bdict['ser_no'] = book.ser_no or 0
86 bdict['series'] = book.series
87 bdict['title'] = book.title
88 if '%(extension)s' not in _compiled_format:
89 _compiled_format += '.%(extension)s'
90 filename = _compiled_format % bdict
92 os.makedirs(os.path.dirname(filename))
95 zf = ZipFile(os.path.join(path, book.archive), 'r')
96 infile = zf.open('%s.%s' % (book.file, book.extension.name))
97 outfile = open(filename, 'wb')
98 copyfileobj(infile, outfile)
102 dt = mktime(book.date.timetuple())
103 os.utime(filename, (dt, dt))
108 print _compiled_format
110 if __name__ == '__main__':