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):
75 dest_path = get_config().getpath('download', 'path')
78 if _library_path is None:
79 _library_path = get_config().getpath('library', 'path')
80 lib_path = _library_path
82 global format, compile_format, compiled_format
87 if compiled_format[-1] in ('\0', '\\', '/'):
88 raise ValueError('Bad format: "%s"' % compiled_format)
90 bdict['author1'] = book.author1
91 bdict['authors'] = book.author_list
92 bdict['extension'] = book.extension.name
93 bdict['file'] = book.file
94 genre = book.genres[0]
95 bdict['gname'] = genre.name
96 bdict['gtitle'] = genre.title
97 bdict['gname_list'] = book.genre_name_list
98 bdict['gtitle_list'] = book.genre_title_list
99 bdict['language'] = book.language.name
100 bdict['ser_no'] = book.ser_no or 0
101 bdict['series'] = book.series
102 bdict['title'] = book.title
103 if '%(extension)s' not in compiled_format:
104 compiled_format += '.%(extension)s'
105 filename = compiled_format % bdict
106 full_path = os.path.join(dest_path, filename)
108 os.makedirs(os.path.dirname(full_path))
110 pass # Already exists
111 zf = ZipFile(os.path.join(lib_path, book.archive), 'r')
112 infile = zf.open('%s.%s' % (book.file, book.extension.name))
113 outfile = open(full_path, 'wb')
114 copyfileobj(infile, outfile)
118 dt = mktime(book.date.timetuple())
119 os.utime(full_path, (dt, dt))
124 print(compiled_format)
127 if __name__ == '__main__':