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'%(gname_list)s'
53 new_format = u'%(gtitle_list)s'
55 new_format = u'%(language)s'
57 new_format = u'%(ser_no)d'
59 new_format = u'%(series)s'
61 new_format = u'%(title)s'
63 raise ValueError('Bad format specifier "%%%c"' % c)
64 compiled.append(new_format)
67 compiled_format = ''.join(compiled)
73 def download(book, dest_path=None, lib_path=None, a_format=None):
76 if _library_path is None:
77 _library_path = get_config().getpath('library', 'path')
78 lib_path = _library_path
80 global format, compile_format, compiled_format
85 if compiled_format[-1] in ('\0', '\\', '/'):
86 raise ValueError('Bad format: "%s"' % compiled_format)
88 bdict['author1'] = book.author1
89 bdict['authors'] = book.author_list
90 bdict['extension'] = book.extension.name
91 bdict['file'] = book.file
92 genre = book.genres[0]
93 bdict['gname'] = genre.name
94 bdict['gtitle'] = genre.title
95 bdict['gname_list'] = book.genre_name_list
96 bdict['gtitle_list'] = book.genre_title_list
97 bdict['language'] = book.language.name
98 bdict['ser_no'] = book.ser_no or 0
99 bdict['series'] = book.series
100 bdict['title'] = book.title
101 if '%(extension)s' not in compiled_format:
102 compiled_format += '.%(extension)s'
103 filename = compiled_format % bdict
104 full_path = os.path.join(dest_path, filename)
106 os.makedirs(os.path.dirname(full_path))
108 pass # Already exists
109 zf = ZipFile(os.path.join(lib_path, book.archive), 'r')
110 infile = zf.open('%s.%s' % (book.file, book.extension.name))
111 outfile = open(full_path, 'wb')
112 copyfileobj(infile, outfile)
116 dt = mktime(book.date.timetuple())
117 os.utime(full_path, (dt, dt))
122 print(compiled_format)
125 if __name__ == '__main__':