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
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, dest_path=None, lib_path=None, a_format=None):
69 if _library_path is None:
70 _library_path = get_config().getpath('library', 'path')
71 lib_path = _library_path
73 global format, compile_format, compiled_format
78 if compiled_format[-1] in ('\0', '\\', '/'):
79 raise ValueError('Bad format: "%s"' % compiled_format)
81 bdict['author'] = book.authors[0].fullname
82 bdict['extension'] = book.extension.name
83 bdict['file'] = book.file
84 genre = book.genres[0]
85 bdict['gname'] = genre.name
86 bdict['gtitle'] = genre.title
87 bdict['language'] = book.language.name
88 bdict['ser_no'] = book.ser_no or 0
89 bdict['series'] = book.series
90 bdict['title'] = book.title
91 if '%(extension)s' not in compiled_format:
92 compiled_format += '.%(extension)s'
93 filename = compiled_format % bdict
94 full_path = os.path.join(dest_path, filename)
96 os.makedirs(os.path.dirname(full_path))
99 zf = ZipFile(os.path.join(lib_path, book.archive), 'r')
100 infile = zf.open('%s.%s' % (book.file, book.extension.name))
101 outfile = open(full_path, 'wb')
102 copyfileobj(infile, outfile)
106 dt = mktime(book.date.timetuple())
107 os.utime(full_path, (dt, dt))
112 print(compiled_format)
115 if __name__ == '__main__':