import os import string import zipfile import conf import last class Book: """Single Project Gutenberg book class.""" def __init__(self, author, title, language, fname_gen, directory, fname, fsize, f_unit): self.author = author self.title = title self.language = language self.fname_gen = fname_gen # fnamexxx.xxx self.directory = directory self.fname = fname self.fsize = fsize self.f_unit = f_unit # size unit - KB or MB self.gzip = 0 def __str__(self): """Nicely format book name. e.g.: Shakespeare, William, 1564-1616; Othello => William Shakespeare 1564-1616 - Othello [500KB]. """ a = self.author.split(',') t = self.title.split(',') a.reverse() t.reverse() if a[0].strip()[0] in string.digits: # year a.append(a[0]) del a[0] size = "[%s%s]" % (self.fsize, self.f_unit) return "%s - %s " % (string.join(a).strip(), string.join(t)) + size def read(self): """Read this book. Download the book if needed, compress last and uncompress current. """ arg = "" self.l_fname = os.path.join(conf.local_books_path, self.directory, self.fname) if self not in last.lst: # to scroll past gutenberg licence stuff.. if conf.viewer.endswith("vim"): arg = "+/\*END\*" self.download() last.compress(self) if self.gzip: self.uncompress() last.add(self) if conf.viewer.endswith("vim"): # -N no vi-compat; -u use vimrc arg = " -N -u %s %s " % (conf.vimrc, arg) os.system(conf.viewer + arg + self.l_fname) def uncompress(self): """Uncompress the book. Gunzip is smart enough to uncompress file.txt.gz if you run gunzip file.txt. """ os.system("gunzip " + self.l_fname) self.gzip = 0 def compress(self): os.system("gzip " + self.l_fname) self.l_fname += ".gz" self.gzip = 1 def download(self): """Download book from PG site and unzip it if needed.""" print "Getting", self import ftputil h = ftputil.FTPHost(conf.pg_site, "anonymous", "ak@host.com") h.chdir(conf.pg_path) h.chdir(self.directory) lpath = os.path.join(conf.local_books_path, self.directory) if not os.path.exists(lpath): os.mkdir(lpath) target = open(self.l_fname, 'w') source = h.file(self.fname) h.copyfileobj(source, target) source.close() target.close() if self.l_fname.endswith(".zip"): f = zipfile.open(self.l_fname) d = f.read() self.l_fname = self.l_fname[:-4] + ".txt" fout = open(self.l_fname) fout.write(d) f.close() fout.close() print "done" # vim: sts=4:ts=8:et:sw=4