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
20 if not compile_format:
22 compile_format = False
23 format = get_config().get('download', 'format')
39 new_format = u'%(author1)s'
41 new_format = u'%(authors)s'
43 new_format = u'%(extension)s'
45 new_format = u'%(file)s'
47 new_format = u'%(gname)s'
49 new_format = u'%(gtitle)s'
51 new_format = u'%(language)s'
53 new_format = u'%(ser_no)d'
55 new_format = u'%(series)s'
57 new_format = u'%(title)s'
59 raise ValueError('Bad format specifier "%%%c"' % c)
60 compiled.append(new_format)
63 compiled_format = ''.join(compiled)
69 def download(book, dest_path=None, lib_path=None, a_format=None):
72 if _library_path is None:
73 _library_path = get_config().getpath('library', 'path')
74 lib_path = _library_path
76 global format, compile_format, compiled_format
81 if compiled_format[-1] in ('\0', '\\', '/'):
82 raise ValueError('Bad format: "%s"' % compiled_format)
84 bdict['author1'] = book.author1
85 bdict['authors'] = book.author_list
86 bdict['extension'] = book.extension.name
87 bdict['file'] = book.file
88 genre = book.genres[0]
89 bdict['gname'] = genre.name
90 bdict['gtitle'] = genre.title
91 bdict['language'] = book.language.name
92 bdict['ser_no'] = book.ser_no or 0
93 bdict['series'] = book.series
94 bdict['title'] = book.title
95 if '%(extension)s' not in compiled_format:
96 compiled_format += '.%(extension)s'
97 filename = compiled_format % bdict
98 full_path = os.path.join(dest_path, filename)
100 os.makedirs(os.path.dirname(full_path))
102 pass # Already exists
103 zf = ZipFile(os.path.join(lib_path, book.archive), 'r')
104 infile = zf.open('%s.%s' % (book.file, book.extension.name))
105 outfile = open(full_path, 'wb')
106 copyfileobj(infile, outfile)
110 dt = mktime(book.date.timetuple())
111 os.utime(full_path, (dt, dt))
116 print(compiled_format)
119 if __name__ == '__main__':