def readotherfile(self, book_href): id = unicode_str(book_href) if id in self.id_to_href: raise WrapperException('Incorrect interface routine - use readfile') # handle special case of trying to read the opf if id is not None and id == "OEBPS/content.opf": return self.build_opf() filepath = self.id_to_filepath.get(id, None) if filepath is None: raise WrapperException('book href does not exist') basedir = self.ebook_root if id in self.added or id in self.modified: basedir = self.outdir filepath = os.path.join(basedir, filepath) if not unipath.exists(filepath): raise WrapperException('File Does Not Exist') basename = os.path.basename(filepath) ext = os.path.splitext(basename)[1] ext = ext.lower() mime = ext_mime_map.get(ext,'') data = b'' with open(filepath,'rb') as fp: data = fp.read() if mime.endswith('+xml'): data = unicode_str(data) return data
def set_manifest_epub3_properties(self, id, properties): id = unicode_str(id) properties = unicode_str(properties) if properties is not None and properties == "": properties = None if id not in self.id_to_props: raise WrapperException('Id does not exist in manifest') del self.id_to_props[id] self.id_to_props[id] = properties self.modified['OEBPS/content.opf'] = 'file'
def spine_insert_before(self, pos, sid, linear): sid = unicode_str(sid) linear = unicode_str(linear) if sid not in self.id_to_mime: raise WrapperException('that spine idref does not exist in manifest') n = len(self.spine) if pos == 0: self.spine = [(sid, linear)] + self.spine elif pos == -1 or pos >= n: self.spine = self.spine.append((sid, linear)) else: self.spine = self.spine[0:pos] + [(sid, linear)] + self.spine[pos:] self.modified['OEBPS/content.opf'] = 'file'
def setspine(self,new_spine): spine = [] for (sid, linear) in new_spine: sid = unicode_str(sid) linear = unicode_str(linear) if sid not in self.id_to_href: raise WrapperException('Spine Id not in Manifest') if linear is not None: linear = linear.lower() if linear not in ['yes', 'no']: raise Exception('Improper Spine Linear Attribute') spine.append((sid, linear)) self.spine = spine self.modified['OEBPS/content.opf'] = 'file'
def setbindings_epub3(self, new_bindings): bindings = [] for (mtype, handler) in new_bindings: mtype = unicode_str(mtype) handler = unicode_str(handler) if mtype is None or mtype == "": continue if handler is None or handler == "": continue if handler not in self.id_to_href: raise WrapperException('Handler not in Manifest') bindings.append((mtype, handler)) self.bindings = bindings self.modified['OEBPS/content.opf'] = 'file'
def setspine(self, new_spine): spine = [] for (sid, linear) in new_spine: sid = unicode_str(sid) linear = unicode_str(linear) if sid not in self.id_to_href: raise WrapperException("Spine Id not in Manifest") if linear is not None: linear = linear.lower() if linear not in ["yes", "no"]: raise Exception("Improper Spine Linear Attribute") spine.append((sid, linear)) self.spine = spine self.modified["OEBPS/content.opf"] = "file"
def setguide(self, new_guide): guide = [] for (type, title, href) in new_guide: type = unicode_str(type) title = unicode_str(title) href = unicode_str(href) if type not in _guide_types: type = "other." + type if title is None: title = 'title missing' thref = href.split('#')[0] if thref not in self.href_to_id: raise WrapperException('guide href not in manifest') guide.append((type, title, href)) self.guide = guide self.modified['OEBPS/content.opf'] = 'file'
def copy_book_contents_to(self, destdir): destdir = unicode_str(destdir) if destdir is None or not unipath.isdir(destdir): raise WrapperException('destination directory does not exist') for id in self.id_to_filepath: rpath = self.id_to_filepath[id] in_manifest = id in self.id_to_mime data = self.readfile(id) filepath = os.path.join(destdir,rpath) base = os.path.dirname(filepath) if not unipath.exists(base): os.makedirs(base) if isinstance(data,text_type): data = utf8_str(data) with open(pathof(filepath),'wb') as fp: fp.write(data) for id in self.book_href_to_filepath: rpath = self.book_href_to_filepath[id] data = self.readotherfile(id) filepath = os.path.join(destdir,rpath) base = os.path.dirname(filepath) if not unipath.exists(base): os.makedirs(base) if isinstance(data,text_type): data = utf8_str(data) with open(pathof(filepath),'wb') as fp: fp.write(data)
def getmime(self, href): href = unicode_str(href) href = unquoteurl(href) filename = os.path.basename(href) ext = os.path.splitext(filename)[1] ext = ext.lower() return ext_mime_map.get(ext, "")
def deleteotherfile(self, book_href): id = unicode_str(book_href) if id in self.id_to_href: raise WrapperException('Incorrect interface routine - use deletefile') filepath = self.id_to_filepath.get(id, None) if id is None: raise WrapperException('book href does not exist') if id in PROTECTED_FILES: raise WrapperException('attempt to delete protected file') add_to_deleted = True # if file was added or modified delete file from outdir if id in self.added or id in self.modified: filepath = os.path.join(self.outdir,filepath) if unipath.exists(filepath) and unipath.isfile(filepath): os.remove(filepath) if id in self.added: self.added.remove(id) add_to_deleted = False if id in self.other: self.other.remove(id) if id in self.modified: del self.modified[id] if add_to_deleted: self.deleted.append(('other', id, book_href)) del self.id_to_filepath[id]
def deletefile(self, id): id = unicode_str(id) filepath = self.id_to_filepath.get(id, None) if id is None: raise WrapperException('id does not exist in manifest') add_to_deleted = True # if file was added or modified, delete file from outdir if id in self.added or id in self.modified: filepath = os.path.join(self.outdir,filepath) if unipath.exists(filepath) and unipath.isfile(filepath): os.remove(pathof(filepath)) if id in self.added: self.added.remove(id) add_to_deleted = False if id in self.modified: del self.modified[id] # remove from manifest href = self.id_to_href[id] del self.id_to_href[id] del self.id_to_mime[id] del self.href_to_id[href] # remove from spine new_spine = [] was_modified = False for sid, linear in self.spine: if sid != id: new_spine.append((sid, linear)) else: was_modified = True if was_modified: setspine(new_spine) if add_to_deleted: self.deleted.append(id) self.modified['OEBPS/content.opf'] = 'file' del self.id_to_filepath[id]
def setspine_itemref_epub3_attributes(idref, linear, properties): idref = unicode_str(idref) linear = unicode_str(linear) properties = unicode_str(properties) if properties is not None and properties == "": properties = None pos = -1 i = 0 for (sid, slinear, sproperties) in self.spine: if sid == idref: pos = i break; i += 1 if pos == -1: raise WrapperException('that idref is not exist in the spine') self.spine[pos] = (sid, linear, properties) self.modified['OEBPS/content.opf'] = 'file'
def build_container_xml(relative_path_to_opf): opf_path = unicode_str(relative_path_to_opf) container = '<?xml version="1.0" encoding="UTF-8"?>\n' container += '<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">\n' container += ' <rootfiles>\n' container += '<rootfile full-path="%s" media-type="application/oebps-package+xml"/>' % opf_path container += ' </rootfiles>\n</container>\n' return container
def setpackagetag(self, new_packagetag): pkgtag = unicode_str(new_packagetag) version = "" mo = _PKG_VER.search(pkgtag) if mo: version = mo.group(1) if version != self.epub_version: raise WrapperException('Illegal to change the package version attribute') self.package_tag = pkgtag self.modified['OEBPS/content.opf'] = 'file'
def readfile(self, id): id = unicode_str(id) filepath = self.id_to_filepath.get(id, None) if filepath is None: raise WrapperException('Id does not exist in manifest') # already added or modified it will be in outdir basedir = self.ebook_root if id in self.added or id in self.modified: basedir = self.outdir filepath = os.path.join(basedir, filepath) if not unipath.exists(filepath): raise WrapperException('File Does Not Exist') data = '' with open(filepath,'rb') as fp: data = fp.read() mime = self.id_to_mime.get(id,'') if mime.endswith('+xml'): data = unicode_str(data) return data
def addfile(self, uniqueid, basename, data, mime=None, properties=None, fallback=None, overlay=None): uniqueid = unicode_str(uniqueid) basename = unicode_str(basename) mime = unicode_str(mime) if mime is None: ext = os.path.splitext(basename)[1] ext = ext.lower() mime = ext_mime_map.get(ext, None) if mime is None: raise WrapperException("Mime Type Missing") if mime.startswith("audio"): base = 'Audio' elif mime.startswith("video"): base = "Video" else: base = mime_base_map.get(mime,'Misc') href = base + "/" + basename if uniqueid in self.id_to_href: raise WrapperException('Manifest Id is not unique') if href in self.href_to_id: raise WrapperException('Basename is not unique') # now actually write out the new file filepath = href.replace("/",os.sep) filepath = os.path.join('OEBPS', filepath) self.id_to_filepath[uniqueid] = filepath filepath = os.path.join(self.outdir,filepath) base = os.path.dirname(filepath) if not unipath.exists(base): os.makedirs(base) if mime.endswith('+xml') or isinstance(data, text_type): data = utf8_str(data) with open(filepath,'wb') as fp: fp.write(data) self.id_to_href[uniqueid] = href self.id_to_mime[uniqueid] = mime self.id_to_props[uniqueid] = properties self.id_to_fall[uniqueid] = fallback self.id_to_over[uniqueid] = overlay self.href_to_id[href] = uniqueid self.added.append(uniqueid) self.modified['OEBPS/content.opf'] = 'file' return uniqueid
def set_manifest_epub3_attributes(self, id, properties=None, fallback=None, overlay=None): id = unicode_str(id) properties = unicode_str(properties) if properties is not None and properties == "": properties = None fallback = unicode_str(fallback) if fallback is not None and fallback == "": fallback = None overlay = unicode_str(overlay) if overlay is not None and overlay == "": overlay = None if id not in self.id_to_props: raise WrapperException('Id does not exist in manifest') del self.id_to_props[id] del self.id_to_fall[id] del self.id_to_over[id] self.id_to_props[id] = properties self.id_to_fall[id] = fallback self.id_to_over[id] = overlay self.modified['OEBPS/content.opf'] = 'file'
def map_basename_to_id(self, basename, ow): basename = unicode_str(basename) ext = os.path.splitext(basename)[1] ext = ext.lower() mime = ext_mime_map.get(ext,None) if mime.startswith("audio"): base = 'Audio' elif mime.startswith("video"): base = "Video" else: base = mime_base_map.get(mime,'Misc') href = base + "/" + basename return self.href_to_id.get(href,ow)
def fileChooser(): localRoot = Tk() localRoot.withdraw() file_opt = {} file_opt['parent'] = None file_opt['title']= 'Select iBooks XML file' file_opt['defaultextension'] = '.xml' # retrieve the initialdir from JSON prefs file_opt['initialdir'] = unicode_str(prefs['use_file_path'], 'utf-8') file_opt['multiple'] = False file_opt['filetypes'] = [('XML Files', ('.xml'))] localRoot.quit() return tkinter_filedialog.askopenfilename(**file_opt)
def addfile(self, uniqueid, basename, data, mime=None): uniqueid = unicode_str(uniqueid) basename = unicode_str(basename) mime = unicode_str(mime) if mime is None: ext = os.path.splitext(basename)[1] ext = ext.lower() mime = ext_mime_map.get(ext, None) if mime is None: raise WrapperException("Mime Type Missing") if mime.startswith("audio"): base = "Audio" elif mime.startswith("video"): base = "Video" else: base = mime_base_map.get(mime, "Misc") href = base + "/" + basename if uniqueid in self.id_to_href: raise WrapperException("Manifest Id is not unique") if href in self.href_to_id: raise WrapperException("Basename is not unique") # now actually write out the new file filepath = href.replace("/", os.sep) filepath = os.path.join("OEBPS", filepath) self.id_to_filepath[uniqueid] = filepath filepath = os.path.join(self.outdir, filepath) base = os.path.dirname(filepath) if not unipath.exists(base): os.makedirs(base) if mime.endswith("+xml") or isinstance(data, text_type): data = utf8_str(data) with open(filepath, "wb") as fp: fp.write(data) self.id_to_href[uniqueid] = href self.id_to_mime[uniqueid] = mime self.href_to_id[href] = uniqueid self.added.append(uniqueid) self.modified["OEBPS/content.opf"] = "file" return uniqueid
def writefile(self, id, data): id = unicode_str(id) filepath = self.id_to_filepath.get(id, None) if filepath is None: raise WrapperException('Id does not exist in manifest') mime = self.id_to_mime.get(id,'') filepath = os.path.join(self.outdir, filepath) base = os.path.dirname(filepath) if not unipath.exists(base): os.makedirs(pathof(base)) if mime.endswith('+xml') or isinstance(data, text_type): data = utf8_str(data) with open(filepath,'wb') as fp: fp.write(data) self.modified[id] = 'file'
def fileChooser(self): file_opt = {} file_opt['parent'] = None file_opt['title']= 'Select exception file' file_opt['defaultextension'] = '.txt' file_opt['initialdir'] = unicode_str(self.misc_prefs['lastDir'], 'utf-8') file_opt['multiple'] = False file_opt['filetypes'] = [('Text Files', '.txt'), ('All files', '.*')] inpath = tkinter_filedialog.askopenfilename(**file_opt) if len(inpath): self.cust_file_path.config(state="normal") self.cust_file_path.delete(0, tkinter_constants.END) self.cust_file_path.insert(0, os.path.normpath(inpath)) self.misc_prefs['lastDir'] = pathof(os.path.dirname(inpath)) self.cust_file_path.config(state="readonly")
def writeotherfile(self, book_href, data): id = unicode_str(book_href) filepath = self.id_to_filepath.get(id, None) if filepath is None: raise WrapperException('book href does not exist') if id in PROTECTED_FILES: raise WrapperException('Attempt to modify protected file') filepath = os.path.join(self.outdir, filepath) base = os.path.dirname(filepath) if not unipath.exists(base): os.makedirs(base) if isinstance(data, text_type): data = utf8_str(data) with open(filepath,'wb') as fp: fp.write(data) self.modified[id] = 'file'
def writeotherfile(self, book_href, data): id = unicode_str(book_href) if id in self.id_to_href: raise WrapperException("Incorrect interface routine - use writefile") filepath = self.id_to_filepath.get(id, None) if filepath is None: raise WrapperException("book href does not exist") if id in PROTECTED_FILES: raise WrapperException("Attempt to modify protected file") filepath = os.path.join(self.outdir, filepath) base = os.path.dirname(filepath) if not unipath.exists(base): os.makedirs(base) if isinstance(data, text_type): data = utf8_str(data) with open(filepath, "wb") as fp: fp.write(data) self.modified[id] = "file"
def addotherfile(self, book_href, data) : id = unicode_str(book_href) if id in self.other: raise WrapperException('book href must be unquie') desired_path = id.replace("/",os.sep) filepath = os.path.join(self.outdir,desired_path) if unipath.isfile(filepath): raise WrapperException('desired path already exists') base = os.path.dirname(filepath) if not unipath.exists(base): os.makedirs(pathof(base)) if isinstance(data, text_type): data = utf8_str(data) with open(pathof(filepath),'wb')as fp: fp.write(data) self.other.append(id) self.added.append(id) self.id_to_filepath[id] = desired_path
def writeotherfile(self, book_href, data): id = unicode_str(book_href) id = unquoteurl(id) if id is None: raise WrapperException('None is not a valid book href') if id not in self.other and id in self.id_to_href: raise WrapperException('Incorrect interface routine - use writefile') filepath = self.book_href_to_filepath.get(id, None) if filepath is None: raise WrapperException('Book href does not exist') if id in PROTECTED_FILES: raise WrapperException('Attempt to modify protected file') filepath = os.path.join(self.outdir, filepath) base = os.path.dirname(filepath) if not unipath.exists(base): os.makedirs(base) if isinstance(data, text_type): data = utf8_str(data) with open(filepath,'wb') as fp: fp.write(data) self.modified[id] = 'file'
def map_bookpath_to_id(self, bookpath, ow): bookpath = unicode_str(bookpath) return self.bookpath_to_id.get(bookpath, ow)
def map_id_to_bookpath(self, id, ow): id = unicode_str(id) return self.id_to_bookpath.get(id, ow)
def map_id_to_properties(self, id, ow): id = unicode_str(id) return self.id_to_props.get(id, ow)
def map_id_to_href(self, id, ow): id = unicode_str(id) return self.id_to_href.get(id, ow)
def initUI(self): """ Build the GUI and assign variables and handler functions to elements. """ self.parent.title(PLUGIN_NAME) body = tkinter.Frame(self) body.pack(fill=tkinter_constants.BOTH, expand=True) chk_frame2 = tkinter.Frame(body) self.edu_quotes = tkinter.StringVar() quote_checkbox = tkinter.Checkbutton(chk_frame2, text="'Educate' quotes", command=self.edu_quotesActions, variable=self.edu_quotes, onvalue='q', offvalue='') quote_checkbox.pack(side=tkinter_constants.LEFT, fill=tkinter_constants.BOTH) chk_frame2.pack(side=tkinter_constants.TOP, fill=tkinter_constants.BOTH) if self.gui_prefs['educateQuotes']: quote_checkbox.select() chk_frame7 = tkinter.Frame(body) self.use_file = tkinter.IntVar() self.file_checkbox = tkinter.Checkbutton( chk_frame7, text="Use apostrophe exception file", command=self.chkBoxActions, variable=self.use_file, onvalue=1, offvalue=0) self.file_checkbox.pack(side=tkinter_constants.LEFT, fill=tkinter_constants.BOTH) chk_frame7.pack(side=tkinter_constants.TOP, fill=tkinter_constants.BOTH) if self.gui_prefs['useFile']: self.file_checkbox.select() if not self.edu_quotes.get(): self.file_checkbox.config(state="disabled") entry_frame1 = tkinter.Frame(body, bd=1) self.cust_file_path = tkinter.Entry(entry_frame1) self.cust_file_path.pack(side=tkinter_constants.LEFT, fill=tkinter_constants.BOTH, expand=1) self.choose_button = tkinter.Button(entry_frame1, text="...", command=self.fileChooser) self.choose_button.pack(side=tkinter_constants.RIGHT, fill=tkinter_constants.BOTH) if len(self.gui_prefs['useFilePath']): self.cust_file_path.insert( 0, unicode_str(self.gui_prefs['useFilePath'], 'utf-8')) self.cust_file_path.config(state="readonly") if not self.use_file.get(): self.choose_button.config(state="disabled") entry_frame1.pack(side=tkinter_constants.TOP, fill=tkinter_constants.BOTH) combo2 = tkinter.Frame(body, bd=2, relief=tkinter_constants.SUNKEN) dash_label = tkinter.Label(combo2, text='(EM|EN)-Dash Settings') dash_label.pack(fill=tkinter_constants.BOTH) self.dashBox_value = tkinter.StringVar() self.dashBox = tkinter_ttk.Combobox(combo2, textvariable=self.dashBox_value) self.dashBox['values'] = ('No dash support', "'--' = emdash (no endash support)", "'--' = emdash '---' = endash", "'---' = emdash '--' = endash") self.dashBox.current(self.gui_prefs['dashes']) self.dashBox.pack(side=tkinter_constants.LEFT, fill=tkinter_constants.BOTH, expand=True) combo2.pack(side=tkinter_constants.TOP, fill=tkinter_constants.BOTH) chk_frame5 = tkinter.Frame(body) self.edu_ellipses = tkinter.StringVar() ellipses_checkbox = tkinter.Checkbutton(chk_frame5, text="'Educate' ellipses", variable=self.edu_ellipses, onvalue='e', offvalue='') ellipses_checkbox.pack(side=tkinter_constants.LEFT, fill=tkinter_constants.BOTH) chk_frame5.pack(side=tkinter_constants.TOP, fill=tkinter_constants.BOTH) if self.gui_prefs['educateEllipses']: ellipses_checkbox.select() chk_frame10 = tkinter.Frame(body) self.unicodevar = tkinter.IntVar() unicode_checkbox = tkinter.Checkbutton(chk_frame10, text='Use Unicode Characters', variable=self.unicodevar, onvalue=1, offvalue=0) unicode_checkbox.pack(side=tkinter_constants.LEFT, fill=tkinter_constants.BOTH) chk_frame10.pack(side=tkinter_constants.TOP, fill=tkinter_constants.BOTH) if self.gui_prefs['useUnicodeChars']: unicode_checkbox.select() filelist_frame = tkinter.Frame(body, bd=2, relief=tkinter_constants.SUNKEN) filelist_label = tkinter.Label(filelist_frame, text='Select files to process:') filelist_label.pack(fill=tkinter_constants.BOTH) scrollbar = tkinter.Scrollbar(filelist_frame, orient=tkinter_constants.VERTICAL) self.filelist = tkinter.Listbox(filelist_frame, yscrollcommand=scrollbar.set, selectmode=tkinter_constants.EXTENDED) scrollbar.config(command=self.filelist.yview) scrollbar.pack(side=tkinter_constants.RIGHT, fill=tkinter_constants.Y) selected_indices = [] listboxindex = 0 for (id, href) in self.bk.text_iter(): self.filelist.insert(tkinter_constants.END, href) # bk.selected_iter() is not available on older versions of Sigil # The files selected in the Book Browser will not be pre-selected if so. selected_op = getattr(self.bk, "selected_iter", None) if callable(selected_op): if href in [ self.bk.id_to_href(ident) for typ, ident in selected_op() ]: selected_indices.append(listboxindex) listboxindex += 1 self.filelist.pack(side=tkinter_constants.LEFT, fill=tkinter_constants.BOTH, expand=1) filelist_frame.pack(side=tkinter_constants.TOP, fill=tkinter_constants.BOTH) # Pre-select files that were selected in Sigil's Book Browser for index in selected_indices: self.filelist.selection_set(index) buttons = tkinter.Frame(body) buttons.pack(side=tkinter_constants.BOTTOM, fill=tkinter_constants.BOTH) self.gbutton = tkinter.Button(buttons, text='Process', command=self.cmdDo) self.gbutton.pack(side=tkinter_constants.LEFT, fill=tkinter_constants.X, expand=1) self.qbutton = tkinter.Button(buttons, text='Quit', command=self.quitApp) self.qbutton.pack(side=tkinter_constants.RIGHT, fill=tkinter_constants.X, expand=1) self.parent.geometry(self.misc_prefs['windowGeometry']) if self.update: self.update_msgbox()
def dumpheader(self): # first 16 bytes are not part of the official mobiheader # but we will treat it as such # so section 0 is 16 (decimal) + self.length in total == at least 0x108 bytes for Mobi 8 headers print( "Dumping section %d, Mobipocket Header version: %d, total length %d" % (self.start, self.version, self.length + 16)) self.hdr = {} # set it up for the proper header version if self.version == 0: self.mobi_header = MobiHeader.palmdoc_header self.mobi_header_sorted_keys = MobiHeader.palmdoc_header_sorted_keys elif self.version < 8: self.mobi_header = MobiHeader.mobi6_header self.mobi_header_sorted_keys = MobiHeader.mobi6_header_sorted_keys else: self.mobi_header = MobiHeader.mobi8_header self.mobi_header_sorted_keys = MobiHeader.mobi8_header_sorted_keys # parse the header information for key in self.mobi_header_sorted_keys: (pos, format, tot_len) = self.mobi_header[key] if pos < (self.length + 16): val, = struct.unpack_from(format, self.header, pos) self.hdr[key] = val if 'title_offset' in self.hdr: title_offset = self.hdr['title_offset'] title_length = self.hdr['title_length'] else: title_offset = 0 title_length = 0 if title_offset == 0: title_offset = len(self.header) title_length = 0 self.title = self.sect.palmname.decode('latin-1', errors='replace') else: self.title = self.header[title_offset:title_offset + title_length].decode(self.codec, errors='replace') # title record always padded with two nul bytes and then padded with nuls to next 4 byte boundary title_length = ((title_length + 2 + 3) >> 2) << 2 self.extra1 = self.header[self.exth_offset + self.exth_length:title_offset] self.extra2 = self.header[title_offset + title_length:] print("Mobipocket header from section %d" % self.start) print(" Offset Value Hex Dec Description") for key in self.mobi_header_sorted_keys: (pos, format, tot_len) = self.mobi_header[key] if pos < (self.length + 16): if key != 'magic': fmt_string = "0x{0:0>3X} ({0:3d}){1: >" + str( 9 - 2 * tot_len) + "s}0x{2:0>" + str( 2 * tot_len) + "X} {2:10d} {3:s}" else: self.hdr[key] = unicode_str(self.hdr[key]) fmt_string = "0x{0:0>3X} ({0:3d}){2:>11s} {3:s}" print(fmt_string.format(pos, " ", self.hdr[key], key)) print("") if self.exth_length > 0: print("EXTH metadata, offset %d, padded length %d" % (self.exth_offset, self.exth_length)) self.dump_exth() print("") if len(self.extra1) > 0: print("Extra data between EXTH and Title, length %d" % len(self.extra1)) print(hexlify(self.extra1)) print("") if title_length > 0: print("Title in header at offset %d, padded length %d: '%s'" % (title_offset, title_length, self.title)) print("") if len(self.extra2) > 0: print("Extra data between Title and end of header, length %d" % len(self.extra2)) print(hexlify(self.extra2)) print("")
def build_bookpath(self, href, starting_dir): href = unicode_str(href) href = unquoteurl(href) starting_dir = unicode_str(starting_dir) return buildBookPath(href, starting_dir)
def map_mediatype_to_group(self, mtype, ow): mtype = unicode_str(mtype) return mime_group_map.get(mtype, ow)
def getmime(self, href): href = unicode_str(href) filename = os.path.basename(href) ext = os.path.splitext(filename)[1] ext = ext.lower() return ext_mime_map.get(ext, "")
def setspine_ppd(self, ppd): ppd = unicode_str(ppd) if ppd not in ['rtl', 'ltr', None]: raise WrapperException('incorrect page-progression direction') self.spine_ppd = ppd self.modified['OEBPS/content.opf'] = 'file'
def setmetadataxml(self, new_metadata): self.metadataxml = unicode_str(new_metadata) self.modified['OEBPS/content.opf'] = 'file'
def setpackagetag(self, new_packagetag): self.package_tag = unicode_str(new_packagetag) self.modified['OEBPS/content.opf'] = 'file'
def setmetadataxml(self, new_metadata): self.metadataxml = unicode_str(new_metadata) self.modified[self.opfbookpath] = 'file'
def map_group_to_folders(self, group, ow): group = unicode_str(group) return self.group_paths.get(group, ow)
def get_relativepath(self, from_bookpath, to_bookpath): from_bookpath = unicode_str(from_bookpath) to_bookpath = unicode_str(to_bookpath) return buildRelativePath(from_bookpath, to_bookpath)
def map_id_to_fallback(self, id, ow): id = unicode_str(id) return self.id_to_fall.get(id, ow)
def get_startingdir(self, bookpath): bookpath = unicode_str(bookpath) return startingDir(bookpath)
def colorMode(self): return unicode_str(self.colormode)
def map_href_to_id(self, href, ow): href = unicode_str(href) return self.href_to_id.get(href,ow)
def map_id_to_overlay(self, id, ow): id = unicode_str(id) return self.id_to_over.get(id, ow)
def map_id_to_mime(self, id, ow): id = unicode_str(id) return self.id_to_mime.get(id, ow)
def main(argv=unicode_argv()): if len(argv) != 5: failed(None, msg="Launcher: improper number of arguments passed to launcher.py") return -1 ebook_root = argv[1] outdir = argv[2] script_type = argv[3] target_file = argv[4] script_home = os.path.dirname(target_file) script_module = os.path.splitext(os.path.basename(target_file))[0] # do basic sanity checking anyway if script_type not in SUPPORTED_SCRIPT_TYPES: failed(None, msg="Launcher: script type %s is not supported" % script_type) return -1 ok = unipath.exists(ebook_root) and unipath.isdir(ebook_root) ok = ok and unipath.exists(outdir) and unipath.isdir(outdir) ok = ok and unipath.exists(script_home) and unipath.isdir(script_home) ok = ok and unipath.exists(target_file) and unipath.isfile(target_file) if not ok: failed(None, msg="Launcher: missing or incorrect paths passed in") return -1 # update sys with path to target module home directory if script_home not in sys.path: sys.path.append(script_home) # load and parse opf if present op = None opf_path = os.path.join(ebook_root, "OEBPS", "content.opf") if unipath.exists(opf_path) and unipath.isfile(opf_path): op = Opf_Parser(opf_path) # create a wrapper for record keeping and safety rk = Wrapper(ebook_root, outdir, op) # get the correct container if script_type == "edit": bc = BookContainer(rk) elif script_type == "input": bc = InputContainer(rk) else: bc = OutputContainer(rk) # start the target script ps = ProcessScript(script_type, script_module, bc) ps.launch() # get standard error and standard out from the target script successmsg = "" for data in ps.stdouttext: successmsg += unicode_str(data) successmsg = escapeit(successmsg) errorlog = "" for data in ps.stderrtext: errorlog += unicode_str(data) errorlog = escapeit(errorlog) # get the target's script wrapper xml resultxml = "".join(ps.wrapout) resultxml += "<msg>\n" if ps.exitcode == 0: resultxml += successmsg if _DEBUG: resultxml += errorlog else: if _DEBUG: resultxml += successmsg resultxml += errorlog resultxml += "</msg>\n</wrapper>\n" # write it to stdout and exit if PY3: sys.stdout.buffer.write(utf8_str(resultxml)) else: sys.stdout.write(utf8_str(resultxml)) return 0
def main(argv=unicode_argv()): if len(argv) != 5: failed( None, msg="Launcher: improper number of arguments passed to launcher.py") return -1 ebook_root = argv[1] outdir = argv[2] script_type = argv[3] target_file = argv[4] script_home = os.path.dirname(target_file) script_module = os.path.splitext(os.path.basename(target_file))[0] # do basic sanity checking anyway if script_type not in SUPPORTED_SCRIPT_TYPES: failed(None, msg="Launcher: script type %s is not supported" % script_type) return -1 ok = unipath.exists(ebook_root) and unipath.isdir(ebook_root) ok = ok and unipath.exists(outdir) and unipath.isdir(outdir) ok = ok and unipath.exists(script_home) and unipath.isdir(script_home) ok = ok and unipath.exists(target_file) and unipath.isfile(target_file) if not ok: failed(None, msg="Launcher: missing or incorrect paths passed in") return -1 # update sys with path to target module home directory if script_home not in sys.path: sys.path.append(script_home) # load and parse opf if present op = None opf_path = os.path.join(ebook_root, 'OEBPS', 'content.opf') if unipath.exists(opf_path) and unipath.isfile(opf_path): op = Opf_Parser(opf_path) # create a wrapper for record keeping and safety rk = Wrapper(ebook_root, outdir, op) # get the correct container if script_type == 'edit': bc = BookContainer(rk) elif script_type == "input": bc = InputContainer(rk) else: bc = OutputContainer(rk) # start the target script ps = ProcessScript(script_type, script_module, bc) ps.launch() # get standard error and standard out from the target script successmsg = '' for data in ps.stdouttext: successmsg += unicode_str(data) successmsg = escapeit(successmsg) errorlog = '' for data in ps.stderrtext: errorlog += unicode_str(data) errorlog = escapeit(errorlog) # get the target's script wrapper xml resultxml = "".join(ps.wrapout) resultxml += "<msg>\n" if ps.exitcode == 0: resultxml += successmsg if _DEBUG: resultxml += errorlog else: if _DEBUG: resultxml += successmsg resultxml += errorlog resultxml += '</msg>\n</wrapper>\n' # write it to stdout and exit if PY3: sys.stdout.buffer.write(utf8_str(resultxml)) else: sys.stdout.write(utf8_str(resultxml)) return 0