archmage-0.3.1/0000755000076700000240000000000012475662171014372 5ustar dottedmagstaff00000000000000archmage-0.3.1/archmage.10000644000076700000240000000477012475422714016230 0ustar dottedmagstaff00000000000000.\" Hey, EMACS: -*- nroff -*- .\" First parameter, NAME, should be all caps .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection .\" other parameters are allowed: see man(7), man(1) .TH ARCHMAGE 1 "February 24, 2006" .\" Please adjust this date whenever revising the manpage. .\" .\" Some roff macros, for reference: .\" .nh disable hyphenation .\" .hy enable hyphenation .\" .ad l left justify .\" .ad b justify to both left and right margins .\" .nf disable filling .\" .fi enable filling .\" .br insert line break .\" .sp insert n+1 empty lines .\" for manpage-specific macros, see man(7) .SH NAME archmage \- CHM(Compiled HTML) Decompressor. .SH SYNOPSIS .B archmage .I chmfile directory .br .B archmage \-p port .I chmfile .SH DESCRIPTION This manual page documents briefly the .B archmage command. This manual page was written for the Debian distribution because the original program does not have a manual page. .PP .\" TeX users may be more comfortable with the \fB\fP and .\" \fI\fP escape sequences to invode bold face and italics, .\" respectively. \fBarCHMage\fP 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 based on python-chm binding to chmlib from GnoCHM project. .SH USAGE .PP There is three ways to use arCHMage package now: .PP 1) Extract .chm to directory (directory will be created): archmage .PP 2) Run as http-server, which will publish chm file contents on specified port: archmage \-p .PP 3) 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 .br PythonHandler archmod.mod_chm Restart apache. .PP 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 .PP or you can view chm file on the fly if you point your browser to http://yourserver/sample.chm/ (note trailing slash) .SH SEE ALSO .PP arCHMage Home Page: http://archmage.sf.net .SH AUTHOR .PP arCHMage was written by Eugeny Korekin .PP This manual page was written by Basil Shubin , for the Debian GNU/Linux system (but may be used by others). archmage-0.3.1/archmage.egg-info/0000755000076700000240000000000012475662171017633 5ustar dottedmagstaff00000000000000archmage-0.3.1/archmage.egg-info/dependency_links.txt0000644000076700000240000000000112475662171023701 0ustar dottedmagstaff00000000000000 archmage-0.3.1/archmage.egg-info/entry_points.txt0000644000076700000240000000005712475662171023133 0ustar dottedmagstaff00000000000000[console_scripts] archmage = archmod.cli:main archmage-0.3.1/archmage.egg-info/PKG-INFO0000644000076700000240000000122712475662171020732 0ustar dottedmagstaff00000000000000Metadata-Version: 1.1 Name: archmage Version: 0.3.1 Summary: CHM decompressor Home-page: https://github.com/dottedmag/archmage Author: Mikhail Gusarov Author-email: dottedmag@dottedmag.net License: GPLv2+ Description: arCHMage is a reader and decompressor for CHM format Keywords: chm,HTML Help,Compiled HTML,Compressed HTML Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Environment :: Web Environment Classifier: Intended Audience :: End Users/Desktop Classifier: License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+) Classifier: Topic :: Text Processing :: Filters archmage-0.3.1/archmage.egg-info/requires.txt0000644000076700000240000000002412475662171022227 0ustar dottedmagstaff00000000000000pychm BeautifulSoup archmage-0.3.1/archmage.egg-info/SOURCES.txt0000644000076700000240000000364412475662171021526 0ustar dottedmagstaff00000000000000AUTHORS COPYING MANIFEST.in NEWS RELEASE-VERSION archmage.1 setup.py version.py archmage.egg-info/PKG-INFO archmage.egg-info/SOURCES.txt archmage.egg-info/dependency_links.txt archmage.egg-info/entry_points.txt archmage.egg-info/requires.txt archmage.egg-info/top_level.txt archmod/CHM.py archmod/CHMParser.py archmod/CHMServer.py archmod/Cached.py archmod/__init__.py archmod/arch.conf archmod/chmtotext.py archmod/cli.py archmod/htmldoc.py archmod/mod_chm.py archmod/templates/arch_contents.html archmod/templates/arch_css.css archmod/templates/arch_frameset.html archmod/templates/arch_header.html archmod/templates/index.html archmod/templates/icons/0.gif archmod/templates/icons/1.gif archmod/templates/icons/10.gif archmod/templates/icons/11.gif archmod/templates/icons/12.gif archmod/templates/icons/13.gif archmod/templates/icons/14.gif archmod/templates/icons/15.gif archmod/templates/icons/16.gif archmod/templates/icons/17.gif archmod/templates/icons/18.gif archmod/templates/icons/19.gif archmod/templates/icons/2.gif archmod/templates/icons/20.gif archmod/templates/icons/21.gif archmod/templates/icons/22.gif archmod/templates/icons/23.gif archmod/templates/icons/24.gif archmod/templates/icons/25.gif archmod/templates/icons/26.gif archmod/templates/icons/27.gif archmod/templates/icons/3.gif archmod/templates/icons/35.gif archmod/templates/icons/37.gif archmod/templates/icons/39.gif archmod/templates/icons/4.gif archmod/templates/icons/5.gif archmod/templates/icons/6.gif archmod/templates/icons/7.gif archmod/templates/icons/8.gif archmod/templates/icons/9.gif archmod/templates/icons/90.gif archmod/templates/icons/91.gif archmod/templates/icons/92.gif archmod/templates/icons/93.gif archmod/templates/icons/94.gif archmod/templates/icons/95.gif archmod/templates/icons/96.gif archmod/templates/icons/97.gif archmod/templates/icons/98.gif archmod/templates/icons/99.gif archmod/templates/icons/next.gif archmod/templates/icons/prev.gifarchmage-0.3.1/archmage.egg-info/top_level.txt0000644000076700000240000000001012475662171022354 0ustar dottedmagstaff00000000000000archmod archmage-0.3.1/archmod/0000755000076700000240000000000012475662171016007 5ustar dottedmagstaff00000000000000archmage-0.3.1/archmod/__init__.py0000644000076700000240000000572412475433307020125 0ustar dottedmagstaff00000000000000# -*- coding: utf-8 -*- # # archmage -- CHM decompressor # Copyright (c) 2003 Eugeny Korekin # Copyright (c) 2005-2009 Basil Shubin # # 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., 51 Franklin # Street, Fifth Floor, Boston, MA 02110-1301, USA. # __all__ = ['CHM', 'CHMServer', 'mod_chm'] __version__ = '0.2.4' import sys, os, pkg_resources # 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 = pkg_resources.resource_filename('archmod', '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.3.1/archmod/arch.conf0000644000076700000240000001013012475422374017565 0ustar dottedmagstaff00000000000000# 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. from os.path import basename, join import pkg_resources templates_dir = pkg_resources.resource_filename('archmod', 'templates/') # Directory with icons icons_dir = join(templates_dir, '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. 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 = 4 archmage-0.3.1/archmod/Cached.py0000644000076700000240000000351112475433303017521 0ustar dottedmagstaff00000000000000# -*- coding: utf-8 -*- # # archmage -- CHM decompressor # Copyright (c) 2009 Basil Shubin # # 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., 51 Franklin # Street, Fifth Floor, Boston, MA 02110-1301, USA. # class 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.3.1/archmod/CHM.py0000644000076700000240000003743712475661750017010 0ustar dottedmagstaff00000000000000# -*- coding: utf-8 -*- # # archmage -- CHM decompressor # Copyright (c) 2003 Eugeny Korekin # Copyright (c) 2005-2009 Basil Shubin # # 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., 51 Franklin # Street, Fifth Floor, Boston, MA 02110-1301, USA. # 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 PARENT_RE = re.compile(r'(^|/|\\)\.\.(/|\\|$)') 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' try: self.topicstree = self.get_entry(self.topics) except AttributeError: self.topicstree = None self.contents = SitemapFile(self.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': lister = PageLister() lister.feed(self.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': counter = TOCCounter() counter.feed(self.topicstree) if counter.count > self.maxtoclvl: return self.maxtoclvl else: return counter.count 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: try: res = eval(re.group(1)) except: res = '' 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 if PARENT_RE.search(e): raise RuntimeError('Giving up on malicious name: %s' % e) 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) 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.3.1/archmod/CHMParser.py0000644000076700000240000001676212475655440020162 0ustar dottedmagstaff00000000000000# -*- coding: utf-8 -*- # # archmage -- CHM decompressor # Copyright (c) 2009 Basil Shubin # # 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., 51 Franklin # Street, Fifth Floor, Boston, MA 02110-1301, USA. # 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 ;-) if lines: 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 else: self.lines = None def parse(self): p = SitemapParser() if self.lines: 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) archmage-0.3.1/archmod/CHMServer.py0000644000076700000240000000377012475433224020161 0ustar dottedmagstaff00000000000000# -*- coding: utf-8 -*- # # archmage -- CHM decompressor # Copyright (c) 2003 Eugeny Korekin # Copyright (c) 2005-2009 Basil Shubin # # 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., 51 Franklin # Street, Fifth Floor, Boston, MA 02110-1301, USA. # 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.3.1/archmod/chmtotext.py0000644000076700000240000000230412475433345020376 0ustar dottedmagstaff00000000000000# -*- coding: utf-8 -*- # # archmage -- CHM decompressor # Copyright (c) 2005-2009 Basil Shubin # # 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., 51 Franklin # Street, Fifth Floor, Boston, MA 02110-1301, USA. # """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.3.1/archmod/cli.py0000755000076700000240000001361112475433364017135 0ustar dottedmagstaff00000000000000# -*- coding: utf-8 -*- # # archmage -- CHM decompressor # Copyright (c) 2003 Eugeny Korekin # Copyright (c) 2005-2009 Basil Shubin # # 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., 51 Franklin # Street, Fifth Floor, Boston, MA 02110-1301, USA. # """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) archmage-0.3.1/archmod/htmldoc.py0000644000076700000240000000360612475433401020010 0ustar dottedmagstaff00000000000000# -*- coding: utf-8 -*- # # archmage -- CHM decompressor # Copyright (c) 2009 Basil Shubin # # 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., 51 Franklin # Street, Fifth Floor, Boston, MA 02110-1301, USA. # """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.3.1/archmod/mod_chm.py0000644000076700000240000000355012475433413017765 0ustar dottedmagstaff00000000000000# -*- coding: utf-8 -*- # # archmage -- CHM decompressor # Copyright (c) 2003 Eugeny Korekin # Copyright (c) 2005-2009 Basil Shubin # # 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., 51 Franklin # Street, Fifth Floor, Boston, MA 02110-1301, USA. # 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.3.1/archmod/templates/0000755000076700000240000000000012475662171020005 5ustar dottedmagstaff00000000000000archmage-0.3.1/archmod/templates/arch_contents.html0000644000076700000240000001155212473350034023517 0ustar dottedmagstaff00000000000000 <%title%> archmage-0.3.1/archmod/templates/arch_css.css0000644000076700000240000000011612473350034022270 0ustar dottedmagstaff00000000000000.small { font-size: x-small; } .htable { margin: 0; border: none; padding: 0 }archmage-0.3.1/archmod/templates/arch_frameset.html0000644000076700000240000000145612473350034023472 0ustar dottedmagstaff00000000000000 <%title%> archmage-0.3.1/archmod/templates/arch_header.html0000644000076700000240000000052712473350034023112 0ustar dottedmagstaff00000000000000 <%title%>
    <%title%>
    archmage-0.3.1/archmod/templates/icons/0000755000076700000240000000000012475662171021120 5ustar dottedmagstaff00000000000000archmage-0.3.1/archmod/templates/icons/0.gif0000644000076700000240000000006712473350034021737 0ustar dottedmagstaff00000000000000GIF89a!,ڋ>;archmage-0.3.1/archmod/templates/icons/1.gif0000644000076700000240000000017212473350034021735 0ustar dottedmagstaff00000000000000GIF89a"!,?XܮCZ[Wh^ gYl|}^ Tp<&=ӡ";archmage-0.3.1/archmod/templates/icons/10.gif0000644000076700000240000000021712473350034022015 0ustar dottedmagstaff00000000000000GIF89a"!,Tx*LBkq2 B q&l9@HP(/5@fTKJB;Ldz'6WMNDžz";archmage-0.3.1/archmod/templates/icons/11.gif0000644000076700000240000000020412473350034022012 0ustar dottedmagstaff00000000000000GIF89a"!,Ih+0FgD l) X0 퓦Zx1|'(zr6;D.!Zx%kLV$;archmage-0.3.1/archmod/templates/icons/12.gif0000644000076700000240000000021512473350034022015 0ustar dottedmagstaff00000000000000GIF89a"!,Rx*LB3xK&@ 8!da]s!!PHHgsCbTxNe6U<#Pi%az}tߊ;archmage-0.3.1/archmod/templates/icons/13.gif0000644000076700000240000000026312473350034022021 0ustar dottedmagstaff00000000000000GIF89a3! ,`0I "`%GaC0$f0&E| (HT ?$.!`Զ5ɁTŹuzM`Ϸ礀;archmage-0.3.1/archmod/templates/icons/14.gif0000644000076700000240000000027312473350034022023 0ustar dottedmagstaff00000000000000GIF89a3! ,hP0=/Vmd$^#kI~p H  @` 25X%T`PzXX )H: 6N&lFGw.  iUV";archmage-0.3.1/archmod/templates/icons/15.gif0000644000076700000240000000026712473350034022027 0ustar dottedmagstaff00000000000000GIF89a3! ,d0I "`%DQGaC0$f0 &E!|(ET ,*caK4WҶ0?,$l9R;archmage-0.3.1/archmod/templates/icons/16.gif0000644000076700000240000000027612473350034022030 0ustar dottedmagstaff00000000000000GIF89a3! ,kP0-Vmdp^["kI~p $H BAP$X%yhҪXX;@@: 6.ߴ: \@'`;x r;V";archmage-0.3.1/archmod/templates/icons/17.gif0000644000076700000240000000020412473350034022020 0ustar dottedmagstaff00000000000000GIF89a"!,IX+0FWD!te5f MV|bFW;;׺ J^);archmage-0.3.1/archmod/templates/icons/18.gif0000644000076700000240000000021512473350034022023 0ustar dottedmagstaff00000000000000GIF89a"!,Rh*H*fPWB7M@@ *ghf^s3^Bls<ӟ8-nJmʌ6zTߊ;archmage-0.3.1/archmod/templates/icons/19.gif0000644000076700000240000000020412473350034022022 0ustar dottedmagstaff00000000000000GIF89a"!,Ih;0FgF2ti@ A&>',Ȭkt_7Le2BvJ\Xk+: xjLV$;archmage-0.3.1/archmod/templates/icons/2.gif0000644000076700000240000000021412473350034021733 0ustar dottedmagstaff00000000000000GIF89a"!,Qh6GҍlM_1@y}c f`/rv K+ 1Fft鶼K@.[z ;archmage-0.3.1/archmod/templates/icons/20.gif0000644000076700000240000000021612473350034022015 0ustar dottedmagstaff00000000000000GIF89a"!,Sx*Xjg`'WBGMJNg@8pZLsRtz͞pE;archmage-0.3.1/archmod/templates/icons/21.gif0000644000076700000240000000021412473350034022014 0ustar dottedmagstaff00000000000000GIF89a"!,Qh=0FgF1t^@ hzq [jrֺAh^q#C}ƜP)KqU℄px J޴wP ;archmage-0.3.1/archmod/templates/icons/22.gif0000644000076700000240000000022212473350034022014 0ustar dottedmagstaff00000000000000GIF89a"!,WxLAG pid"0 0P'\6QtX wKѩlOb,ea6L=d ;archmage-0.3.1/archmod/templates/icons/23.gif0000644000076700000240000000022512473350034022020 0ustar dottedmagstaff00000000000000GIF89a"!,Zx<@ZCsDJ@ <rr)Y5ˠ#hZarPXXe>i! R8|>xA;archmage-0.3.1/archmod/templates/icons/24.gif0000644000076700000240000000026712473350034022027 0ustar dottedmagstaff00000000000000GIF89a3!,dI+A8 18f0|6ha @XT` xԔ H(d+`{67;{O:;archmage-0.3.1/archmod/templates/icons/25.gif0000644000076700000240000000021112473350034022015 0ustar dottedmagstaff00000000000000GIF89a"!,NX-0FWD!t^@ j*Rfqk|]/]|8$č Q*}҂j-\j-+W ;archmage-0.3.1/archmod/templates/icons/26.gif0000644000076700000240000000022412473350034022022 0ustar dottedmagstaff00000000000000GIF89a"!,Yhi%@8\'nتU<<<<#;archmage-0.3.1/archmod/templates/icons/3.gif0000644000076700000240000000021012473350034021730 0ustar dottedmagstaff00000000000000GIF89a"!,Mh,F\rP]!m[**@0'g.;5R 0 P q@b&)ǰs#;archmage-0.3.1/archmod/templates/icons/35.gif0000644000076700000240000000023712473350034022026 0ustar dottedmagstaff00000000000000GIF89a! ,Lv3ȑIt#jx r=mwzґpDb>]kD+uA.zE;archmage-0.3.1/archmod/templates/icons/37.gif0000644000076700000240000000026012473350034022024 0ustar dottedmagstaff00000000000000GIF89a! ,]Ɇ{(3%O\ׁK9iG"@= 2HpqOףY1IEw͟qT,-k^T*(fFmߟ';archmage-0.3.1/archmod/templates/icons/39.gif0000644000076700000240000000025612473350034022033 0ustar dottedmagstaff00000000000000GIF89a! ,[v3ȑIׁ}>MvI@µXn(6o?%5lXC[Ez9 G;archmage-0.3.1/archmod/templates/icons/4.gif0000644000076700000240000000022312473350034021735 0ustar dottedmagstaff00000000000000GIF89a"!,Xx,G@$V qg`& I|B NKW}`$F;archmage-0.3.1/archmod/templates/icons/91.gif0000644000076700000240000000010712473350034022024 0ustar dottedmagstaff00000000000000GIF89a!,- <%title%> archmage-0.3.1/AUTHORS0000644000076700000240000000025112473351204015426 0ustar dottedmagstaff00000000000000Copyright (c) 2003 Eugeny Korekin Copyright (c) 2005-2009 Basil Shubin Copyright (c) 2015 Mikhail Gusarov archmage-0.3.1/COPYING0000644000076700000240000004310312473350034015414 0ustar dottedmagstaff00000000000000 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.3.1/MANIFEST.in0000644000076700000240000000025312475655531016132 0ustar dottedmagstaff00000000000000include archmod/arch.conf recursive-include archmod/templates *.html *.css *.gif include AUTHORS COPYING INSTALL NEWS README archmage.1 include RELEASE-VERSION version.py archmage-0.3.1/NEWS0000644000076700000240000000246112475662112015067 0ustar dottedmagstaff00000000000000arCHMage 0.3.1 ============== Bug fixes: * [CVE-2015-1589] Fixed directory traversal bug arCHMage 0.3 ============ Changes: * Global /etc/archmage/arch.conf configuration file has been moved to the package contents and is no longer customizable Bug fixes: * [Debian #776097] Fixed parsing CHM files with no topic tree arCHMage 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.3.1/PKG-INFO0000644000076700000240000000122712475662171015471 0ustar dottedmagstaff00000000000000Metadata-Version: 1.1 Name: archmage Version: 0.3.1 Summary: CHM decompressor Home-page: https://github.com/dottedmag/archmage Author: Mikhail Gusarov Author-email: dottedmag@dottedmag.net License: GPLv2+ Description: arCHMage is a reader and decompressor for CHM format Keywords: chm,HTML Help,Compiled HTML,Compressed HTML Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Environment :: Web Environment Classifier: Intended Audience :: End Users/Desktop Classifier: License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+) Classifier: Topic :: Text Processing :: Filters archmage-0.3.1/RELEASE-VERSION0000644000076700000240000000000612475662171016514 0ustar dottedmagstaff000000000000000.3.1 archmage-0.3.1/setup.cfg0000644000076700000240000000007312475662171016213 0ustar dottedmagstaff00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 archmage-0.3.1/setup.py0000644000076700000240000000222512475655440016106 0ustar dottedmagstaff00000000000000#!/usr/bin/env python from setuptools import setup, find_packages import version long_desc='''arCHMage is a reader and decompressor for CHM format''' classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: GNU General Public License v2 or later (GPLv2+)', 'Topic :: Text Processing :: Filters', ] setup( name='archmage', version=version.getVersion(), description='CHM decompressor', maintainer='Mikhail Gusarov', maintainer_email='dottedmag@dottedmag.net', url='https://github.com/dottedmag/archmage', license='GPLv2+', keywords=['chm', 'HTML Help', 'Compiled HTML', 'Compressed HTML'], classifiers=classifiers, long_description=long_desc, packages=find_packages(), install_requires=[ 'pychm', 'BeautifulSoup', ], entry_points={ 'console_scripts': ['archmage = archmod.cli:main'], }, package_data={ 'archmod': ['*.conf', 'templates/*.html', 'templates/*.css', 'templates/icons/*.gif'], } ) archmage-0.3.1/version.py0000644000076700000240000000675212475430771016442 0ustar dottedmagstaff00000000000000# -*- coding: utf-8 -*- """Calculates the current version number. If possible, uses output of “git describe” modified to conform to the visioning scheme that setuptools uses (see PEP 386). Releases must be labelled with annotated tags (signed tags are annotated) of the following format: v(.)+ [ {a|b|c|rc} (.)* ] If “git describe” returns an error (likely because we're in an unpacked copy of a release tarball, rather than a git working copy), or returns a tag that does not match the above format, version is read from RELEASE-VERSION file. To use this script, simply import it your setup.py file, and use the results of getVersion() as your package version: import version setup( version=version.getVersion(), . . . ) This will automatically update the RELEASE-VERSION file. The RELEASE-VERSION file should *not* be checked into git but it *should* be included in sdist tarballs (as should version.py file). To do this, run: echo include RELEASE-VERSION version.py >>MANIFEST.in echo RELEASE-VERSION >>.gitignore With that setup, a new release can be labelled by simply invoking: git tag -s v1.0 """ __author__ = ('Douglas Creager ', 'Michal Nazarewicz ') __license__ = 'This file is placed into the public domain.' __maintainer__ = 'Michal Nazarewicz' __email__ = 'mina86@mina86.com' __all__ = ('getVersion') import re import subprocess import sys RELEASE_VERSION_FILE = 'RELEASE-VERSION' # http://www.python.org/dev/peps/pep-0386/ _PEP386_SHORT_VERSION_RE = r'\d+(?:\.\d+)+(?:(?:[abc]|rc)\d+(?:\.\d+)*)?' _PEP386_VERSION_RE = r'^%s(?:\.post\d+)?(?:\.dev\d+)?$' % ( _PEP386_SHORT_VERSION_RE) _GIT_DESCRIPTION_RE = r'^(?P%s)-(?P\d+)-g(?P[\da-f]+)$' % ( _PEP386_SHORT_VERSION_RE) def readGitVersion(): try: proc = subprocess.Popen(('git', 'describe', '--long', '--match', '[0-9]*.*'), stdout=subprocess.PIPE, stderr=subprocess.PIPE) data, _ = proc.communicate() if proc.returncode: return None ver = data.splitlines()[0].strip() except: return None if not ver: return None m = re.search(_GIT_DESCRIPTION_RE, ver) if not m: sys.stderr.write('version: git description (%s) is invalid, ' 'ignoring\n' % ver) return None commits = int(m.group('commits')) if not commits: return m.group('ver') else: return '%s.post%d.dev%d' % ( m.group('ver'), commits, int(m.group('sha'), 16)) def readReleaseVersion(): try: fd = open(RELEASE_VERSION_FILE) try: ver = fd.readline().strip() finally: fd.close() if not re.search(_PEP386_VERSION_RE, ver): sys.stderr.write('version: release version (%s) is invalid, ' 'will use it anyway\n' % ver) return ver except: return None def writeReleaseVersion(version): fd = open(RELEASE_VERSION_FILE, 'w') fd.write('%s\n' % version) fd.close() def getVersion(): release_version = readReleaseVersion() version = readGitVersion() or release_version if not version: raise ValueError('Cannot find the version number') if version != release_version: writeReleaseVersion(version) return version if __name__ == '__main__': print(getVersion())