archmage-0.2.4/0000755000175000017500000000000011224331474012253 5ustar bashubashuarchmage-0.2.4/AUTHORS0000644000175000017500000000015411152737570013332 0ustar bashubashuCopyright (c) 2003 Eugeny Korekin Copyright (c) 2005-2009 Basil Shubin archmage-0.2.4/arch.conf0000644000175000017500000001005511174315501014035 0ustar bashubashu# Directory for templates, all files in that directory will be parsed # and <%.+%> occurencies will be replaced with values from that # file. For example, <%title%>, will be substituted by value of title # variable. # There is also some special variables, which have default values: # contents - list, which represents chm file contents and deftopic - # name of default page. templates_dir = '/usr/share/archmage/templates/' # Directory with icons icons_dir = '/usr/share/archmage/templates/icons/' # List of auxiliary files, stored inside CHM file. # Those files would not be extracted. auxes = ('/#IDXHDR', '/#ITBITS', '/#STRINGS', '/#SYSTEM', '/#TOPICS', '/#URLSTR', '/#URLTBL', '/#WINDOWS', '/$FIftiMain', '/$OBJINST', '/$WWAssociativeLinks', '/$WWKeywordLinks', ':') # Title. That is value, which you want to see in browser title. # 'sourcename' is the name of source file. from os.path import basename title = basename(sourcename) # Background and foreground colors for header. bcolor = '#63baff' fcolor = 'white' # Filenames inside chm stored in utf-8, but links can be in some # national codepage. If you set fs_encoding such links would be # converted to it. # # Default: fs_encoding = 'utf-8' fs_encoding = 'utf-8' # If your filesystem is case-sensitive, links in the html can point to # files that have differences in the case you need to set # filename_case to 1 in that case :-) # # Default: filename_case=1 filename_case = 1 # If you want to add javascript code for restore framing to every # page, set addframing. # # Default: restore_framing=1 restore_framing = 1 # Path to htmldoc executable # htmldoc_exec = '/usr/bin/htmldoc' # CHM2TEXT converting. Use following command to convert CHM content to plain # text file. Make sure that below apps are available on your system. #chmtotext = 'lynx -dump -stdin' chmtotext = '/usr/bin/elinks -dump' # CHM2HTML converting. Use following command to convert CHM content to a single # HTML file. Make sure that htmldoc is available on your system. chmtohtml = '-t html -f "%(output)s" --book %(toc)s --no-numbered --toctitle "Table of Contents" --title --linkstyle underline --fontsize 11.0 --fontspacing 1.2 --headingfont Helvetica --bodyfont Times --headfootsize 11.0 --headfootfont Helvetica --charset iso-8859-1 --browserwidth 680 --no-strict --no-overflow --quiet' # CHM2PDF converting. Use following command to convert CHM content to a single # PDF file. Make sure that htmldoc is available on your system. chmtopdf = '-t pdf14 -f "%(output)s" --book %(toc)s --no-numbered --toctitle "Table of Contents" --title --textcolor "#000000" --linkcolor "#0000ff" --linkstyle plain --size Universal --left 1.00in --right 0.50in --top 0.50in --bottom 0.50in --header .t. --header1 ... --footer h.1 --nup 1 --tocheader .t. --tocfooter ..i --portrait --color --no-pscommands --no-xrxcomments --compression=1 --jpeg=0 --fontsize 11.0 --fontspacing 1.2 --headingfont Helvetica --bodyfont Times --headfootsize 11.0 --headfootfont Helvetica --charset iso-8859-1 --links --embedfonts --pagemode outline --pagelayout single --firstpage c1 --pageeffect none --pageduration 10 --effectduration 1.0 --no-encryption --permissions all --owner-password "" --user-password "" --browserwidth 680 --no-strict --no-overflow --quiet' # CHM2PS converting. Use following command to convert CHM content to a single # PostScript file. Make sure that htmldoc is available on your system. #chmtops = '-t ps2 -f "%(output)s" --book %(toc)s --no-numbered --toctitle "Table of Contents" --title --textcolor "#000000" --linkcolor "#0000ff" --linkstyle underline --size A4 --left 1.00in --right 0.50in --top 0.50in --bottom 0.50in --header .t. --header1 ... --footer h.1 --nup 1 --tocheader .t. --tocfooter ..i --portrait --color --no-pscommands --no-xrxcomments --compression=1 --jpeg=0 --fontsize 11.0 --fontspacing 1.2 --headingfont Helvetica --bodyfont Times --headfootsize 11.0 --headfootfont Helvetica --charset iso-8859-1 --browserwidth 680 --no-strict --no-overflow --quiet' # Maximum Table of Content levels for htmldoc utility. # # Default: maxtoclvl = 4 maxtoclvl = 4archmage-0.2.4/TODO0000644000175000017500000000014011152737570012745 0ustar bashubashu* Entire code refactoring * Update manpage * CHM to PDF or ODT converter !!! * Any other ideas? archmage-0.2.4/archmage.1.gz0000644000175000017500000000247110677670635014547 0ustar bashubashu sFarchmage.1VnF}.bZDiaD˨/-`XCscr]Zaglos9slO? 4ḯe)$E@rnL7|eI5zŹ5Kl}y{hӘ㸙2y6TxR..38ǿG$]/hvw]>p:zz޾yAYyD*>u'TSTl )?ibV=p*Caa4*w֏Scq4JM#^e5SշHU3翵PՃEe ~ w,elU*{oa_*u]_@zu- +̱z |K'iCM ֖ԉo9ץT>w5IWDj`MBsl ZFt5cKכri眤a 3d^OZj-0!竳˥7YbS5ITؼk.4u/yPDq(OC`͝s. "\u[tVؓ*eLJH!Dpk, А6no4# ' Cq8/"㾼|}ߋ ya19QU-qЮVF>MN9p%&Bx-s)amEA # ҁgJ573ӵY KnD[z4vc}yv%n$5fFSM׆uF ]+ЬOyTl[E}$QzOتQ1E?@^t|`98 \@l%~J'{AB;jdo*WC̶j+Ʉ8vLӫ2b'9}L݈Io;sR)!'naGCuҰ }$b"R`D[93&[˝id Xa {kmwq %b~\|^i}&yC2ga'(MAV@ archmage-0.2.4/NEWS0000644000175000017500000000175311223040660012751 0ustar bashubashuarCHMage 0.2.4 ============== Bug fixes: * [SF #2812715] Incorrect arch_contents.html generation on irrlicht.chm arCHMage 0.2.3 ============== Bug fixes: * Fixing caching bug (affects on mod_chm module) arCHMage 0.2.2 ============== Bug fixes: * [SF #2802208] Garbled data attached to output arCHMage 0.2.1 ============== Bug fixes: * HTMLDOC doesn't working with missing

...

tag arCHMage 0.2 ============ Changes/New features: * CHM -> Single HTML conversion * CHM -> PDF conversion * CHM -> Plain Text conversion * Changed option - 'dump' for dumping HTML data from CHM file into standard output. * Huge code re-factoring and lot of small changes/fixes... Bug fixes: * [SF #1767529] IOError exception using CHM dump option * [SF #1955872] import error * [SF #1805070] TOC is broken after decompilation * [SF #1767522] CHM -> single HTML conversion arCHMage 0.1.9 ============== Changes/New features: * New option - 'dump' for dumping HTML data from CHM file as Plain Text archmage-0.2.4/README0000644000175000017500000000524411222400267013133 0ustar bashubashuAbout arCHMage ============== arCHMage is an extensible reader and decompiler for files in the CHM format. This is the format used by Microsoft HTML Help, and is also known as Compiled HTML. arCHMage is written in the Python programming language and uses PyCHM - python bindings for CHMLib from GnoCHM project. Originally this utility was written by Eugeny Korekin, but since 2005 it has been maintained and developed by Basil Shubin. Features List ============= * Extracting CHM content * Dump HTML data from CHM file into standard output * Converting CHM file into another file formats (using external tools): Plain Text, Single HTML, PDF * Running as standalone http-server * Extension for Apache Web Server - mod_chm System Requirements =================== arCHMage requires the following libraries: * Python 2.3 or later * PyCHM * CHMLib * Beautiful Soup (Python HTML/XML parser) Other (optional) dependencies: * Lynx or ELinks - converting HTML to Plain Text * htmldoc - converting to single html, pdf formats * mod_python - Apache/Python Integration Installation ============ See INSTALL file for more details. Simple Usage HOWTO ================== There is several ways to use arCHMage package now: 1) Extract CHM file content in to directory (directory will be created): archmage -x [directory] Note: Decompilation will fail, if destination directory already exist. 2) Dump HTML data from CHM file: archmage -d Note: All data dumped in to standard output. 3) Convert CHM file into another file formats: archmage -c [output file] Available formats: html - Single HTML file text - Plain Text file pdf - Adobe PDF file format Note: To use this feature you must have htmldoc installed. See /etc/arch.conf for details. 4) Run as http-server, which will publish chm file contents on specified port. archmage -p Note: You can first decompress chm file into directory and use this directory instead chm file, i.e: archmage -p 5) Tune your apache to publish chm file contents if there is trailing slash in request to that file (you will need working mod_python for that): Add that lines to your httpd.conf: AddHandler python-program .chm PythonHandler archmod.mod_chm Restart apache. Let's suppose, you have file sample.chm in DocumentRoot of your apache. After that tuning you can receive raw chm file, if you point your browser to http://yourserver/sample.chm or you can view chm file on the fly if you point your browser to http://yourserver/sample.chm/ (note trailing slash) archmage-0.2.4/setup.py0000644000175000017500000000666111223040660013767 0ustar bashubashu#!/usr/bin/env python from distutils.core import setup, Extension setup (name = "archmage", fullname = "arCHMage", version = "0.2.4", description = "CHM(Compiled HTML) Decompressor", maintainer = "Basil Shubin", maintainer_email = "bashu@users.sourceforge.net", author = "Eugeny Korekin", author_email = "az@ftc.ru", url = "archmage.sf.net", license = "GPL", keywords = ["chm", "HTML Help", "Compiled HTML", "Compressed HTML"], long_description = "arCHMage is an extensible reader and decompiler for files in the CHM format. arCHMage is written in the Python programming language and uses PyCHM - python bindings for CHMLIB from GnoCHM project.", py_modules = ["archmod.CHM", "archmod.CHMParser", "archmod.CHMServer", "archmod.Cached", "archmod.mod_chm", "archmod.chmtotext", "archmod.htmldoc"], scripts = ["archmage"], data_files = [("/etc/archmage", ["arch.conf"]), ("share/man/man1", ["archmage.1.gz"]), ("share/archmage/templates", ["templates/arch_contents.html", "templates/arch_frameset.html", "templates/arch_header.html", "templates/index.html", "templates/arch_css.css"]), ("share/archmage/templates/icons", ["templates/icons/next.gif", "templates/icons/0.gif", "templates/icons/1.gif", "templates/icons/11.gif", "templates/icons/12.gif", "templates/icons/17.gif", "templates/icons/2.gif", "templates/icons/22.gif", "templates/icons/90.gif", "templates/icons/91.gif", "templates/icons/92.gif", "templates/icons/93.gif", "templates/icons/94.gif", "templates/icons/95.gif", "templates/icons/96.gif", "templates/icons/97.gif", "templates/icons/98.gif", "templates/icons/99.gif", "templates/icons/10.gif", "templates/icons/prev.gif", "templates/icons/13.gif", "templates/icons/14.gif", "templates/icons/15.gif", "templates/icons/16.gif", "templates/icons/18.gif", "templates/icons/19.gif", "templates/icons/20.gif", "templates/icons/21.gif", "templates/icons/23.gif", "templates/icons/24.gif", "templates/icons/25.gif", "templates/icons/26.gif", "templates/icons/27.gif", "templates/icons/35.gif", "templates/icons/37.gif", "templates/icons/39.gif", "templates/icons/3.gif", "templates/icons/4.gif", "templates/icons/5.gif", "templates/icons/6.gif", "templates/icons/7.gif", "templates/icons/8.gif", "templates/icons/9.gif"])] ) archmage-0.2.4/archmod/0000755000175000017500000000000011224331474013670 5ustar bashubashuarchmage-0.2.4/archmod/CHMServer.py0000644000175000017500000000200511172346172016040 0ustar bashubashu# -*- coding: utf-8 -*- import urllib import mimetypes from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler import archmod class CHMServer(HTTPServer): """HTTP Server that handle Compressed HTML""" def __init__(self, CHM, name='', port=8000): self.address = (name, port) self.httpd = HTTPServer(self.address, CHMRequestHandler) self.httpd.CHM = CHM self.address = (name, port) def run(self): self.httpd.serve_forever() class CHMRequestHandler(BaseHTTPRequestHandler): """This class handle HTTP request for CHMServer""" def do_GET(self): pagename = urllib.unquote(self.path.split('?')[0]) if pagename == '/': mimetype = 'text/html' else: mimetype = mimetypes.guess_type(pagename)[0] self.send_response(200) self.send_header('Content-type', mimetype) self.end_headers() # get html data from CHM instance and write it into output try: self.wfile.write(self.server.CHM.get_entry(pagename)) except NameError, msg: archmod.message(archmod.ERROR, 'NameError: %s' % msg) archmage-0.2.4/archmod/mod_chm.py0000644000175000017500000000151511213170375015651 0ustar bashubashu# -*- coding: utf-8 -*- from mod_python import apache from mimetypes import guess_type from archmod.CHM import CHMFile chmfile = None chmname = None def handler(req): source = req.filename pagename = req.path_info global chmfile, chmname if chmname != source: chmfile = CHMFile(source) chmname = source if pagename: try: page = chmfile.get_entry(pagename) except: return apache.HTTP_NOT_FOUND if pagename == '/': mimetype = 'text/html' else: mimetype = guess_type(pagename)[0] or 'application/octet-stream' req.content_type = mimetype req.send_http_header() req.write(page) else: mimetype = 'application/chm' req.content_type = mimetype req.send_http_header() file = open(source, 'rb') while 1: tmp = file.read(4096) if len(tmp) == 0: break req.write(tmp) return apache.OK archmage-0.2.4/archmod/__init__.py0000644000175000017500000000351611223040660015777 0ustar bashubashu__all__ = ['CHM', 'CHMServer', 'mod_chm'] __version__ = '0.2.4' import sys, os # Return codes OK = 0 ERROR = 1 # Global variables EXTRACT = 1 # Extract CHM content HTTPSERVER = 2 # Act as standalone HTTP server DUMPHTML = 3 # Dump CHM file as plain text CHM2TXT = 4 # Convert CHM file into Single Text file CHM2HTML = 5 # Convert CHM file into Single HTML file CHM2PDF = 6 # Convert CHM file into PDF Document #CHM2PS = 7 # Convert CHM file into PDF Document # Special characters COMMASPACE = ', ' LF = '\n' CR = '\r' # what config file to use - local or a system wide? user_config = os.path.join(os.path.expanduser('~'), '.arch.conf') if os.path.exists(user_config): config = user_config else: config = '/etc/archmage/arch.conf' # Miscellaneous auxiliary functions def message(code=OK, msg=''): outfp = sys.stdout if code == ERROR: outfp = sys.stderr if msg: print >> outfp, msg def file2dir(filename): """Convert file filename.chm to filename_html directory""" dirname = filename.rsplit('.', 1)[0] + '_' + 'html' return dirname def output_format(mode): if mode == 'text': return CHM2TXT elif mode == 'html': return CHM2HTML elif mode == 'pdf': return CHM2PDF # elif mode == 'ps': # return CHM2PS else: sys.exit('Invalid output file format: %s' % mode) def output_file(filename, mode): """Convert filename.chm to filename.output""" if mode == CHM2TXT: file_ext = 'txt' elif mode == CHM2HTML: file_ext = 'html' elif mode == CHM2PDF: file_ext = 'pdf' # elif mode == CHM2PS: # file_ext = 'ps' else: file_ext = 'output' output_filename = filename.rsplit('.', 1)[0] + '.' + file_ext return output_filename # Our own listdir method :) def listdir(dir): def f(res, dir, files): for e in files: d = '/'.join(dir.split('/')[1:]) if d: d += '/' res.append(d + e) res = [] os.path.walk(dir, f, res) return res archmage-0.2.4/archmod/Cached.py0000644000175000017500000000204711213717073015415 0ustar bashubashuclass Cached(object): """Provides caching storage for data access decoration. Usage: class CachedClass(Cached): def _getitem(self, name): # implement data getting routine, such as db access CachedClass().attribute1 # returns value as if _getitem('attribute1') was called CachedClass().attribute2 # returns value as if _getitem('attribute2') was called CachedClass().__doc__ # returns real docstring """ def __new__(classtype, *args, **kwargs): __instance = object.__new__(classtype, *args, **kwargs) __instance.cache = {} return __instance # to be implemented by contract in the descendant classes def _getitem(self, name): raise Exception(NotImplemented) def __getattribute__(self, name): try: return object.__getattribute__(self, name) except: if not self.cache.has_key(name): self.cache[name] = self._getitem(name) return self.cache[name] archmage-0.2.4/archmod/htmldoc.py0000644000175000017500000000204311223042213015660 0ustar bashubashu# -*- coding: utf-8 -*- # # Copyright (c) 2009 Basil Shubin """Generic converter function""" import os import string import tempfile import subprocess import archmod def htmldoc(input, cmd, options, toclevels, output): """CHM to other format converter input - list of input html files cmd - full path to htmldoc command options - htmldoc options from arch.conf toclevels - number of ToC levels as htmldoc option output - output file (single html, ps, pdf and etc) """ if toclevels: toc = ('--toclevels %s' % (toclevels)) else: toc = ('--no-toc') options = options % {'output' : output, 'toc' : toc} if input: # Create a htmldoc file for batch processing f = tempfile.NamedTemporaryFile(delete=False) f.write('#HTMLDOC 1.8.27' + archmod.LF) f.write(options + archmod.LF) f.write(string.join(input, archmod.LF)) f.close() # Prepare command line to execute command = '%s --batch %s' % (cmd, f.name) subprocess.call(command, shell=True) # Unlink temporary htmldoc file os.unlink(f.name)archmage-0.2.4/archmod/chmtotext.py0000644000175000017500000000072411152745231016264 0ustar bashubashu# -*- coding: utf-8 -*- # # Copyright (c) 2005-2009 Basil Shubin """CHM to Text converter (using external tool: lynx or elinks)""" import sys import signal from subprocess import Popen, PIPE signal.signal(signal.SIGPIPE, signal.SIG_DFL) def chmtotext(input, cmd, output=sys.stdout): """CHM to Text converter""" proc = Popen(cmd, stdin=PIPE, stdout=PIPE, shell=True) proc.stdin.write(input) print >> output, proc.communicate()[0] archmage-0.2.4/archmod/CHM.py0000644000175000017500000003422411223042142014644 0ustar bashubashu# -*- coding: utf-8 -*- # # Copyright (c) 2003 Eugeny Korekin # Copyright (c) 2005-2009 Basil Shubin import os import sys import re import shutil import errno import string import tempfile import archmod from archmod.CHMParser import SitemapFile, PageLister, ImageCatcher, TOCCounter, HeadersCounter from archmod.Cached import Cached # import PyCHM bindings try: from chm import chmlib except ImportError, msg: sys.exit('ImportError: %s\nPlease check README file for system requirements.' % msg) # External file converters from archmod.chmtotext import chmtotext from archmod.htmldoc import htmldoc class CHMDir(Cached): """Class that represent CHM content from directory""" def __init__(self, name): # Name of source directory with CHM content self.sourcename = name # Import variables from config file into namespace execfile(archmod.config, self.__dict__) # build regexp from the list of auxiliary files self.aux_re = '|'.join([ re.escape(s) for s in self.auxes ]) # Get and parse 'Table of Contents' topicstree = self.get_entry(self.topics) self.contents = SitemapFile(topicstree).parse() def _getitem(self, name): # Get all entries if name == 'entries': entries = [] for fname in archmod.listdir(self.sourcename): name = '/' + fname if os.path.isdir(self.sourcename + name): name += '/' entries.append(name) return entries # retrieves the list of HTML files contained into the CHM file, **in order** (that's the important bit). # (actually performed by the PageLister class) if name == 'html_files': topicstree = self.get_entry(self.topics) lister = PageLister() lister.feed(topicstree) return lister.pages # retrieves the list of images urls contained into the CHM file. # (actually performed by the ImageCatcher class) if name == 'image_urls': image_urls = [] image_catcher = ImageCatcher() for file in self.html_files: image_catcher.feed(CHMEntry(self, file).correct()) for image_url in image_catcher.imgurls: if not image_urls.count(image_url): image_urls.append(image_url) return image_urls # retrieves a dictionary of actual file entries and corresponding urls into the CHM file if name == 'image_files': image_files = {} for image_url in self.image_urls: for entry in self.entries: if re.search(image_url, entry.lower()) and not image_files.has_key(entry.lower()): image_files.update({entry : image_url}) return image_files # Get topics file if name == 'topics': for e in self.entries: if e.lower().endswith('.hhc'): return e if name == 'deftopic': # use first page as deftopic. Note: without heading slash if self.html_files[0].startswith('/'): return self.html_files[0].replace('/', '', 1).lower() return self.html_files[0].lower() # Get index file if name == 'index': for e in self.entries: if e.lower().endswith('.hhk'): return e # Get frontpage name if name == 'frontpage': frontpage = os.path.join('/', 'index.html') index = 2 # index2.html and etc. for filename in self.entries: if frontpage == filename: frontpage = os.path.join('/', ('index%s.html' % index)) index += 1 return frontpage # Get all templates files if name == 'templates': templates = [] for file in os.listdir(self.templates_dir): if os.path.isfile(os.path.join(self.templates_dir, file)): if os.path.join('/', file) not in self.entries: templates.append(os.path.join('/', file)) return templates # Get ToC levels if name == 'toclevels': topicstree = self.get_entry(self.topics) counter = TOCCounter() counter.feed(topicstree) if counter.count > self.maxtoclvl: return self.maxtoclvl else: return counter.count # HTMLDOC doesn't working with missing

...

tag, # so we need to fix it (for first page only) # XXX: Seems to be an ugly solution... if name == 'html_header_tags': html_header_tags = {'h1': 0, 'h2' : 0, 'h3' : 0, 'h4' : 0, 'h5' : 0, 'h6' :0} for html_file in self.html_files: counter = HeadersCounter() counter.feed(CHMEntry(self, html_file).read()) tmp_dict = {'h1': html_header_tags['h1'] + counter.h1, 'h2': html_header_tags['h2'] + counter.h2, 'h3': html_header_tags['h3'] + counter.h3, 'h4': html_header_tags['h4'] + counter.h4, 'h5': html_header_tags['h5'] + counter.h5, 'h6': html_header_tags['h6'] + counter.h6} html_header_tags.update(tmp_dict) return html_header_tags # Number of missing H[1-6] tags # XXX: Find a better solution! if name == 'html_header_tags_missing': if self.html_header_tags['h6'] == 0: missing = 6 if self.html_header_tags['h5'] == 0: missing = 5 if self.html_header_tags['h4'] == 0: missing = 4 if self.html_header_tags['h3'] == 0: missing = 3 if self.html_header_tags['h2'] == 0: missing = 2 if self.html_header_tags['h1'] == 0: missing = 1 else: missing = 0 return missing raise AttributeError(name) def get_entry(self, name): """Get CHM entry by name""" # show index page or any other substitute if name == '/': name = self.frontpage if name in self.templates or name == self.frontpage: return self.get_template(name) if name.lower() in [ os.path.join('/icons', icon.lower()) for icon in os.listdir(self.icons_dir) ]: return open(os.path.join(self.icons_dir, os.path.basename(name))).read() for e in self.entries: if e.lower() == name.lower(): return CHMEntry(self, e, frontpage=self.frontpage).get() else: archmod.message(archmod.ERROR, 'NameError: There is no %s' % name) def sub_mytag(self, re): """Replacing tagname with attribute""" try: res = eval('self.' + re.group(1)) except: res = eval(re.group(1)) return res def get_template(self, name): """Get template file by it's name""" if name == self.frontpage: tpl = open(os.path.join(self.templates_dir, os.path.basename('index.html'))).read() else: tpl = open(os.path.join(self.templates_dir, os.path.basename(name))).read() return re.sub('\<%(.+?)%\>', self.sub_mytag, tpl) def process_templates(self, destdir="."): """Process templates""" for template in self.templates: open(os.path.join(destdir, os.path.basename(template)), 'w').write(self.get_template(template)) if self.frontpage not in self.templates: open(os.path.join(destdir, os.path.basename(self.frontpage)), 'w').write(self.get_template('index.html')) if not os.path.exists(os.path.join(destdir, 'icons/')): shutil.copytree(os.path.join(self.icons_dir), os.path.join(destdir, 'icons/')) def extract_entry(self, entry, output_file, destdir=".", correct=False): # process output entry, remove first '/' in entry name fname = string.lower(output_file).replace('/', '', 1) # get directory name for file fname if any dname = os.path.dirname(os.path.join(destdir, fname)) # if dname is a directory and it's not exist, than create it if dname and not os.path.exists(dname): os.makedirs(dname) # otherwise write a file from CHM entry if not os.path.isdir(os.path.join(destdir, fname)): # filename encoding conversion if self.fs_encoding: fname = fname.decode('utf-8').encode(self.fs_encoding) # write CHM entry content into the file, corrected or as is if correct: open(os.path.join(destdir, fname), 'w').writelines(CHMEntry(self, entry).correct()) else: open(os.path.join(destdir, fname), 'w').writelines(CHMEntry(self, entry).get()) def extract_entries(self, entries=[], destdir=".", correct=False): """Extract raw CHM entries into the files""" for e in entries: # if entry is auxiliary file, than skip it if re.match(self.aux_re, e): continue self.extract_entry(e, output_file=e, destdir=destdir, correct=correct) def extract(self, destdir): """Extract CHM file content into FS""" try: # Create destination directory os.mkdir(destdir) # make raw content extraction self.extract_entries(entries=self.entries, destdir=destdir) # process templates self.process_templates(destdir=destdir) except OSError, error: if error[0] == errno.EEXIST: sys.exit('%s is already exists' % destdir) def dump_html(self, output=sys.stdout): """Dump HTML data from CHM file into standard output""" for e in self.html_files: # if entry is auxiliary file, than skip it if re.match(self.aux_re, e): continue print >> output, CHMEntry(self, e).get() def chm2text(self, output=sys.stdout): """Convert CHM into Single Text file""" for e in self.html_files: # if entry is auxiliary file, than skip it if re.match(self.aux_re, e): continue # to use this function you should have 'lynx' or 'elinks' installed chmtotext(input=CHMEntry(self, e).get(), cmd=self.chmtotext, output=output) def htmldoc(self, output, format=archmod.CHM2HTML): """CHM to other file formats converter using htmldoc""" # Extract CHM content into temporary directory output = output.replace(' ', '_') tempdir = tempfile.mkdtemp(prefix=output.rsplit('.', 1)[0]) self.extract_entries(entries=self.html_files, destdir=tempdir, correct=True) # List of temporary files files = [ os.path.abspath(tempdir + file.lower()) for file in self.html_files ] if format == archmod.CHM2HTML: options = self.chmtohtml # change output from single html file to a directory with html file and images if self.image_files: dirname = archmod.file2dir(output) if os.path.exists(dirname): sys.exit('%s is already exists' % dirname) # Extract image files os.mkdir(dirname) # Extract all images for key, value in self.image_files.items(): self.extract_entry(entry=key, output_file=value, destdir=dirname) # Fix output file name output = os.path.join(dirname, output) elif format == archmod.CHM2PDF: options = self.chmtopdf if self.image_files: # Extract all images for key, value in self.image_files.items(): self.extract_entry(entry=key, output_file=key.lower(), destdir=tempdir) htmldoc(files, self.htmldoc_exec, options, self.toclevels, output) # Remove temporary files shutil.rmtree(path=tempdir) class CHMFile(CHMDir): """CHM file class derived from CHMDir""" def _getitem(self, name): # Overriding CHMDir.entries attribute if name == 'entries': entries = [] # get CHM file content and process it for name in self._get_names(self._handler): if (name == '/'): continue entries.append(name) return entries if name == '_handler': return chmlib.chm_open(self.sourcename) return super(CHMFile, self)._getitem(name) def __delattr__(self, name): # Closes CHM file handler on class destroying if name == '_handler': chmlib.chm_close(self._handler) return super(CHMFile, self).__delattr__(name) def _get_names(self, chmfile): """Get object's names inside CHM file""" def get_name(chmfile, ui, content): content.append(ui.path) return chmlib.CHM_ENUMERATOR_CONTINUE chmdir = [] if (chmlib.chm_enumerate(chmfile, chmlib.CHM_ENUMERATE_ALL, get_name, chmdir)) == 0: sys.exit('UnknownError: CHMLIB or PyCHM bug?') return chmdir class CHMEntry(object): """Class for CHM file entry""" def __init__(self, parent, name, frontpage='index.html'): # parent CHM file self.parent = parent # object inside CHM file self.name = name # frontpage name to substitute self.frontpage = os.path.basename(frontpage) def read(self): """Read CHM entry content""" # Check where parent instance is CHMFile or CHMDir if isinstance(self.parent, CHMFile): result, ui = chmlib.chm_resolve_object(self.parent._handler, self.name) if (result != chmlib.CHM_RESOLVE_SUCCESS): return None size, content = chmlib.chm_retrieve_object(self.parent._handler, ui, 0l, ui.length) if (size == 0): return None return content else: return open(self.parent.sourcename + self.name).read() def lower_links(self, text): """Links to lower case""" return re.sub('(?i)(href|src)\s*=\s*([^\s|>]+)', lambda m:m.group(0).lower(), text) def add_restoreframing_js(self, name, text): name = re.sub('/+', '/', name) depth = name.count('/') js = """""" % ( '../' * depth, self.frontpage, name ) return re.sub('(?i)<\s*body\s*>', js, text) def correct(self): """Get correct CHM entry content""" data = self.read() # If entry is a html page? if re.search('(?i)\.html?$', self.name) and data is not None: # lower-casing links if needed if self.parent.filename_case: data = self.lower_links(data) # Delete unwanted HTML elements. data = re.sub('
', '', data) data = re.sub('\[ Team LiB \]<\/a>', '', data) data = re.sub('', '', data) data = re.sub(']*><\/a>', '' ,data) data = re.sub(']*><\/a>', '', data) data = re.sub(']*><\/a>', '', data) data = re.sub('"[^"]*previous\.gif"', '""', data) data = re.sub('"[^"]*prev\.gif"', '""', data) data = re.sub('"[^"]*next\.gif"', '""', data) # HTMLDOC doesn't working with missing

...

tag, # so we need to fix it # TODO: Seems to be an ugly solution... if not self.parent.html_header_tags['h1']: for header in xrange(self.parent.html_header_tags_missing + 1, 7): data = re.sub(r'<[hH]%s' % str(header), r'' % str(header), r'' % str(header - self.parent.html_header_tags_missing), data) if data is not None: return data else: return '' def get(self): """Get CHM entry content""" # read entry content data = self.read() # If entry is a html page? if re.search('(?i)\.html?$', self.name) and data is not None: # lower-casing links if needed if self.parent.filename_case: data = self.lower_links(data) # restore framing if that option is set in config file if self.parent.restore_framing: data = self.add_restoreframing_js(self.name[1:], data) if data is not None: return data else: return '' archmage-0.2.4/archmod/CHMParser.py0000644000175000017500000001336011222417024016023 0ustar bashubashu# -*- coding: utf-8 -*- import re import mimetypes import sgmllib, urllib2 from BeautifulSoup import BeautifulSoup from HTMLParser import HTMLParser, HTMLParseError from urlparse import urlparse from archmod import COMMASPACE, LF, CR START_TAG = '[' END_TAG = ']' class SitemapFile(object): """Sitemap file class""" def __init__(self, lines): # XXX: Cooking tasty beautiful soup ;-) soup = BeautifulSoup(lines) lines = soup.prettify() # XXX: Removing empty tags lines = re.sub(re.compile(r'
    \s*
', re.I | re.M), '', lines) lines = re.sub(re.compile(r'
  • \s*
  • ', re.I | re.M), '', lines) self.lines = lines def parse(self): p = SitemapParser() p.feed(self.lines) # parsed text + last bracket return (p.parsed + LF + END_TAG) class TagStack(list): """from book of David Mertz 'Text Processing in Python'""" def append(self, tag): # Remove every paragraph-level tag if this is one if tag.lower() in ('p', 'blockquote'): self = TagStack([ t for t in super if t not in ('p', 'blockquote') ]) super(TagStack, self).append(tag) def pop(self, tag): # 'Pop' by tag from nearest position, not only last item self.reverse() try: pos = self.index(tag) except ValueError: raise HTMLParseError, 'Tag not on stack' self[:] = self[pos + 1:] self.reverse() class SitemapParser(sgmllib.SGMLParser): """Class for parsing files in SiteMap format, such as .hhc""" def __init__(self): self.tagstack = TagStack() self.in_obj = False self.name = self.local = self.param = "" self.imagenumber = 1 self.parsed = "" sgmllib.SGMLParser.__init__(self) def unknown_starttag(self, tag, attrs): # first ul, start processing from here if tag == 'ul' and not self.tagstack: self.tagstack.append(tag) # First bracket self.parsed += LF + START_TAG # if inside ul elif self.tagstack: if tag == 'li': # append closing bracket if needed if self.tagstack[-1] != 'ul': self.parsed += END_TAG self.tagstack.pop('li') indent = ' ' * len(self.tagstack) if self.parsed != LF + START_TAG: self.parsed += COMMASPACE self.parsed += LF + indent + START_TAG if tag == 'object': for x, y in attrs: if x.lower() == 'type' and y.lower() == 'text/sitemap': self.in_obj = True if tag.lower() == 'param' and self.in_obj: for x, y in attrs: if x.lower() == 'name': self.param = y.lower() elif x.lower() == 'value': if self.param == 'name' and not len(self.name): # XXX: Remove LF and/or CR signs from name self.name = y.replace(LF, '').replace(CR, '') # XXX: Un-escaping double quotes :-) self.name = self.name.replace('"', '\\"') elif self.param == 'local': # XXX: Change incorrect slashes in url self.local = y.lower().replace('\\', '/').replace('..\\', '') elif self.param == 'imagenumber': self.imagenumber = y self.tagstack.append(tag) def unknown_endtag(self, tag): # if inside ul if self.tagstack: if tag == 'ul': self.parsed += END_TAG if tag == 'object' and self.in_obj: # "Link Name", "URL", "Icon" self.parsed += "\"%s\", \"%s\", \"%s\"" % (self.name, self.local, self.imagenumber) # Set to default values self.in_obj = False self.name = self.local = "" self.imagenumber = 1 if tag != 'li': self.tagstack.pop(tag) class PageLister(sgmllib.SGMLParser): """ Parser of the chm.chm GetTopicsTree() method that retrieves the URL of the HTML page embedded in the CHM file. """ def reset(self): sgmllib.SGMLParser.reset(self) self.pages = [] def start_param(self, attrs): urlparam_flag = False for key, value in attrs: if key == 'name' and value.lower() == 'local': urlparam_flag = True if urlparam_flag and key == 'value': # Sometime url has incorrect slashes value = urllib2.unquote(urlparse(value.replace('\\', '/')).geturl()) value = '/' + re.sub("#.*$", '', value) # Avoid duplicates if not self.pages.count(value): self.pages.append(value) class ImageCatcher(sgmllib.SGMLParser): """ Finds image urls in the current html page, so to take them out from the chm file. """ def reset(self): sgmllib.SGMLParser.reset(self) self.imgurls = [] def start_img(self, attrs): for key, value in attrs: if key.lower() == 'src': # Avoid duplicates in the list of image URLs. if not self.imgurls.count('/' + value): self.imgurls.append('/' + value) def start_a(self, attrs): for key, value in attrs: if key.lower() == 'href': url = urlparse(value) value = urllib2.unquote(url.geturl()) # Remove unwanted crap value = '/' + re.sub("#.*$", '', value) # Check file's mimetype type = mimetypes.guess_type(value)[0] # Avoid duplicates in the list of image URLs. if not url.scheme and not self.imgurls.count(value) and \ type and re.search('image/.*', type): self.imgurls.append(value) class TOCCounter(HTMLParser): """Count Table of Contents levels""" count = 0 def __init__(self): self.tagstack = TagStack() HTMLParser.__init__(self) def handle_starttag(self, tag, attrs): self.tagstack.append(tag) def handle_endtag(self, tag): if self.tagstack: if tag.lower() == 'object': if self.count < self.tagstack.count('param'): self.count = self.tagstack.count('param') if tag.lower() != 'li': self.tagstack.pop(tag) # XXX: Seems to be an ugly solution... class HeadersCounter(HTMLParser): """Count headers tags""" h1 = h2 = h3 = h4 = h5 = h6 = 0 def handle_starttag(self, tag, attrs): if tag.lower() == 'h1': self.h1 += 1 if tag.lower() == 'h2': self.h2 += 1 if tag.lower() == 'h3': self.h3 += 1 if tag.lower() == 'h4': self.h4 += 1 if tag.lower() == 'h5': self.h5 += 1 if tag.lower() == 'h6': self.h6 += 1 archmage-0.2.4/COPYING0000644000175000017500000004310310677670635013327 0ustar bashubashu GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. archmage-0.2.4/templates/0000755000175000017500000000000011224331476014253 5ustar bashubashuarchmage-0.2.4/templates/icons/0000755000175000017500000000000011224331476015366 5ustar bashubashuarchmage-0.2.4/templates/icons/1.gif0000644000175000017500000000017210677670635016233 0ustar bashubashuGIF89a"!,?XܮCZ[Wh^ gYl|}^ Tp<&=ӡ";archmage-0.2.4/templates/icons/14.gif0000644000175000017500000000027310677670635016321 0ustar bashubashuGIF89a3! ,hP0=/Vmd$^#kI~p H  @` 25X%T`PzXX )H: 6N&lFGw.  iUV";archmage-0.2.4/templates/icons/26.gif0000644000175000017500000000022410677670635016320 0ustar bashubashuGIF89a"!,Yh]kD+uA.zE;archmage-0.2.4/templates/icons/2.gif0000644000175000017500000000021410677670635016231 0ustar bashubashuGIF89a"!,Qh6GҍlM_1@y}c f`/rv K+ 1Fft鶼K@.[z ;archmage-0.2.4/templates/icons/39.gif0000644000175000017500000000025610677670635016331 0ustar bashubashuGIF89a! ,[v3ȑIׁ}>MvI@µXn(6o?%5lXC[Ez9 G;archmage-0.2.4/templates/icons/96.gif0000644000175000017500000000012110677670635016323 0ustar bashubashuGIF89a!,"-bWVt8iOfYLN;archmage-0.2.4/templates/icons/19.gif0000644000175000017500000000020410677670635016320 0ustar bashubashuGIF89a"!,Ih;0FgF2ti@ A&>',Ȭkt_7Le2BvJ\Xk+: xjLV$;archmage-0.2.4/templates/icons/18.gif0000644000175000017500000000021510677670635016321 0ustar bashubashuGIF89a"!,Rh*H*fPWB7M@@ *ghf^s3^Bls<ӟ8-nJmʌ6zTߊ;archmage-0.2.4/templates/icons/12.gif0000644000175000017500000000021510677670635016313 0ustar bashubashuGIF89a"!,Rx*LB3xK&@ 8!da]s!!PHHgsCbTxNe6U<#Pi%az}tߊ;archmage-0.2.4/templates/icons/94.gif0000644000175000017500000000012610677670635016326 0ustar bashubashuGIF89a!,'-bWV yɪjbeI;;archmage-0.2.4/templates/icons/93.gif0000644000175000017500000000012610677670635016325 0ustar bashubashuGIF89a!,'-bWV yɪjbeIz;archmage-0.2.4/templates/icons/24.gif0000644000175000017500000000026710677670635016325 0ustar bashubashuGIF89a3!,dI+A8 18f0|6ha @XT` xԔ H(d+`{67;{O:;archmage-0.2.4/templates/icons/23.gif0000644000175000017500000000022510677670635016316 0ustar bashubashuGIF89a"!,Zx<@ZCsDJ@ <rr)Y5ˠ#hZarPXXe>i! R8|>xA;archmage-0.2.4/templates/icons/91.gif0000644000175000017500000000010710677670635016322 0ustar bashubashuGIF89a!,-;archmage-0.2.4/templates/icons/99.gif0000644000175000017500000000010310677670635016326 0ustar bashubashuGIF89a!,Q R;archmage-0.2.4/templates/icons/21.gif0000644000175000017500000000021410677670635016312 0ustar bashubashuGIF89a"!,Qh=0FgF1t^@ hzq [jrֺAh^q#C}ƜP)KqU℄px J޴wP ;archmage-0.2.4/templates/icons/10.gif0000644000175000017500000000021710677670635016313 0ustar bashubashuGIF89a"!,Tx*LBkq2 B q&l9@HP(/5@fTKJB;Ldz'6WMNDžz";archmage-0.2.4/templates/icons/6.gif0000644000175000017500000000017410677670635016242 0ustar bashubashuGIF89a"!,AX/H U x1MYEw:Σ  7 ;"XzlVFlH;archmage-0.2.4/templates/icons/27.gif0000644000175000017500000000026310677670635016324 0ustar bashubashuGIF89a! ,`v3ȑI|)Nbz , ua8<4B piEv >i%@8\'nتU<<<<#;archmage-0.2.4/templates/icons/13.gif0000644000175000017500000000026310677670635016317 0ustar bashubashuGIF89a3! ,`0I "`%GaC0$f0&E| (HT ?$.!`Զ5ɁTŹuzM`Ϸ礀;archmage-0.2.4/templates/icons/8.gif0000644000175000017500000000021510677670635016240 0ustar bashubashuGIF89a"!,Rh*&6.K+i``J9W `!` a&BOkެ|2n N8l&,z^sކ;archmage-0.2.4/templates/icons/22.gif0000644000175000017500000000022210677670635016312 0ustar bashubashuGIF89a"!,WxLAG pid"0 0P'\6QtX wKѩlOb,ea6L=d ;archmage-0.2.4/templates/icons/97.gif0000644000175000017500000000012410677670635016327 0ustar bashubashuGIF89a!,%.Kkmx`mv8M=x;archmage-0.2.4/templates/icons/90.gif0000644000175000017500000000010510677670635016317 0ustar bashubashuGIF89a!,-}`$F;archmage-0.2.4/templates/icons/9.gif0000644000175000017500000000020510677670635016240 0ustar bashubashuGIF89a"!,Jh+0J'-6* 25FvC[eś+I}l"<ňn|pWD. ;archmage-0.2.4/templates/icons/17.gif0000644000175000017500000000020410677670635016316 0ustar bashubashuGIF89a"!,IX+0FWD!te5f MV|bFW;;׺ J^);archmage-0.2.4/templates/icons/25.gif0000644000175000017500000000021110677670635016313 0ustar bashubashuGIF89a"!,NX-0FWD!t^@ j*Rfqk|]/]|8$č Q*}҂j-\j-+W ;archmage-0.2.4/templates/icons/92.gif0000644000175000017500000000010510677670635016321 0ustar bashubashuGIF89a!,- <%title%> archmage-0.2.4/templates/index.html0000644000175000017500000000212111222673711016243 0ustar bashubashu <%title%> archmage-0.2.4/templates/arch_css.css0000644000175000017500000000011610677670635016566 0ustar bashubashu.small { font-size: x-small; } .htable { margin: 0; border: none; padding: 0 }archmage-0.2.4/templates/arch_header.html0000644000175000017500000000052710677670635017410 0ustar bashubashu <%title%>
    <%title%>
    archmage-0.2.4/templates/arch_contents.html0000644000175000017500000001155210677670635020015 0ustar bashubashu <%title%> archmage-0.2.4/INSTALL0000644000175000017500000000125011152737570013311 0ustar bashubashuSource Tarball ============== First unpack source tarball: # tar xzvf archmage-.tar.gz change working directory: # cd archmage- to install arCHMage run following command: # python setup.py install Debian / Ubuntu =============== You can use prepackaged version from software archive: # apt-get install archmage if you want to use it with apache: # apt-get install libapache-mod-python or to use it with apache2: # apt-get install libapache2-mod-python To have ability to dump HTML data from CHM file as plain text: # apt-get install lynx For converting CHM file into Single HTML, PDF or PostScript file: # apt-get install htmldocarchmage-0.2.4/archmage0000755000175000017500000001162011174257135013755 0ustar bashubashu#!/usr/bin/env python # -*- coding: utf-8 -*- # arCHMage -- extensible reader and decompiler for files in the CHM format. # # Originally written by Eugeny Korekin # Significantly modified by Basil Shubin # # Copyright (c) 2003 Eugeny Korekin # Copyright (c) 2005-2009 Basil Shubin """arCHMage -- extensible reader and decompiler for files in the CHM format. Usage: %(program)s [options] [destdir|destfile] Where: -x / --extract Extracts CHM file into specified directory. If destination directory is omitted, than the new one will be created based on name of CHM file. This options is by default. -c format --convert=format Convert CHM file into specified file format. If destination file is omitted, than the new one will be created based on name of CHM file. Available formats: html - Single HTML file text - Plain Text file pdf - Adobe PDF file format -p number --port=number Acts as HTTP server on specified port number, so you can read CHM file with your favorite browser. You can specify a directory with decompressed content. -d / --dump Dump HTML data from CHM file into standard output. -V / --version Print version number and exit. -h / --help Print this text and exit. """ import os, sys import getopt import archmod from archmod.CHM import CHMFile, CHMDir from archmod.CHMServer import CHMServer program = sys.argv[0] def usage(code=archmod.OK, msg=''): """Show application usage and quit""" archmod.message(code, __doc__ % globals()) archmod.message(code, msg) sys.exit(code) def parseargs(): try: opts, args = getopt.getopt(sys.argv[1:], 'xc:dp:Vh', ['extract', 'convert=', 'dump', 'port=', 'version', 'help']) except getopt.error, msg: usage(archmod.ERROR, msg) class Options: mode = None # EXTRACT or HTTPSERVER or other port = None # HTTP port number chmfile = None # CHM File to view/extract output = None # Output file or directory options = Options() for opt, arg in opts: if opt in ('-h', '--help'): usage() elif opt in ('-V', '--version'): archmod.message(archmod.OK, archmod.__version__) sys.exit(archmod.OK) elif opt in ('-p', '--port'): if options.mode is not None: sys.exit('-x and -p or -c are mutually exclusive') options.mode = archmod.HTTPSERVER try: options.port = int(arg) except ValueError, msg: sys.exit('Invalid port number: %s' % msg) elif opt in ('-c', '--convert'): if options.mode is not None: sys.exit('-x and -p or -c are mutually exclusive') options.mode = archmod.output_format(str(arg)) elif opt in ('-x', '--extract'): if options.mode is not None: sys.exit('-x and -p or -c are mutually exclusive') options.mode = archmod.EXTRACT elif opt in ('-d', '--dump'): if options.mode is not None: sys.exit('-d should be used without any other options') options.mode = archmod.DUMPHTML else: assert False, (opt, arg) # Sanity checks if options.mode is None: # Set default option options.mode = archmod.EXTRACT if not args: sys.exit('No CHM file was specified!') else: # Get CHM file name from command line options.chmfile = args.pop(0) # if CHM content should be extracted if options.mode == archmod.EXTRACT: if not args: options.output = archmod.file2dir(options.chmfile) else: # get output directory from command line options.output = args.pop(0) # or converted into another file format elif options.mode in (archmod.CHM2TXT, archmod.CHM2HTML, archmod.CHM2PDF): if not args: options.output = archmod.output_file(options.chmfile, options.mode) else: # get output filename from command line options.output = args.pop(0) # Any other arguments are invalid if args: sys.exit('Invalid arguments: ' + archmod.COMMASPACE.join(args)) return options def main(): options = parseargs() if not os.path.exists(options.chmfile): sys.exit('No such file: %s' % options.chmfile) # Check where is argument a CHM file or directory with decompressed # content. Depending on results make 'source' instance of CHMFile or # CHMDir class. source = os.path.isfile(options.chmfile) and \ CHMFile(options.chmfile) or CHMDir(options.chmfile) if options.mode == archmod.HTTPSERVER: CHMServer(source, port=options.port).run() elif options.mode == archmod.DUMPHTML: source.dump_html() elif options.mode == archmod.CHM2TXT: if os.path.exists(options.output): sys.exit('%s is already exists' % options.output) source.chm2text(open(options.output, 'w')) elif options.mode in (archmod.CHM2HTML, archmod.CHM2PDF): source.htmldoc(options.output, options.mode) elif options.mode == archmod.EXTRACT: source.extract(options.output) if __name__ == '__main__': main()