3 from __future__ import print_function
5 from time import mktime
6 from shutil import copyfileobj
7 from zipfile import ZipFile
8 from .config import get_config
10 __all__ = ['download']
15 compiled_format = '%(file)s'
18 def _compile_format():
19 global format, compile_format, compiled_format
21 compile_format = False
23 format = get_config().get('download', 'format')
39 new_format = u'%(author)s'
41 new_format = u'%(extension)s'
43 new_format = u'%(file)s'
45 new_format = u'%(gname)s'
47 new_format = u'%(gtitle)s'
49 new_format = u'%(language)s'
51 new_format = u'%(ser_no)d'
53 new_format = u'%(series)s'
55 new_format = u'%(title)s'
57 raise ValueError('Bad format specifier "%%%c"' % c)
58 compiled.append(new_format)
61 compiled_format = ''.join(compiled)
67 def download(book, path=None, a_format=None):
70 if _library_path is None:
71 _library_path = get_config().get('library', 'path')
74 global format, compile_format, compiled_format
79 if compiled_format[-1] in ('\0', '\\', '/'):
80 raise ValueError('Bad format: "%s"' % compiled_format)
82 bdict['author'] = book.authors[0].fullname
83 bdict['extension'] = book.extension.name
84 bdict['file'] = book.file
85 genre = book.genres[0]
86 bdict['gname'] = genre.name
87 bdict['gtitle'] = genre.title
88 bdict['language'] = book.language.name
89 bdict['ser_no'] = book.ser_no or 0
90 bdict['series'] = book.series
91 bdict['title'] = book.title
92 if '%(extension)s' not in compiled_format:
93 compiled_format += '.%(extension)s'
94 filename = compiled_format % bdict
96 os.makedirs(os.path.dirname(filename))
99 zf = ZipFile(os.path.join(path, book.archive), 'r')
100 infile = zf.open('%s.%s' % (book.file, book.extension.name))
101 outfile = open(filename, 'wb')
102 copyfileobj(infile, outfile)
106 dt = mktime(book.date.timetuple())
107 os.utime(filename, (dt, dt))
112 print(compiled_format)
115 if __name__ == '__main__':