4 from time import mktime
5 from shutil import copyfileobj
6 from zipfile import ZipFile
7 from .config import get_config
14 compiled_format = '%(file)s'
17 def _compile_format():
18 global format, compile_format, compiled_format
20 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, path=None, a_format=None):
69 if _library_path is None:
70 _library_path = get_config().get('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
95 os.makedirs(os.path.dirname(filename))
98 zf = ZipFile(os.path.join(path, book.archive), 'r')
99 infile = zf.open('%s.%s' % (book.file, book.extension.name))
100 outfile = open(filename, 'wb')
101 copyfileobj(infile, outfile)
105 dt = mktime(book.date.timetuple())
106 os.utime(filename, (dt, dt))
111 print compiled_format
113 if __name__ == '__main__':