def main(): usage = "usage: %prog [options]" parser = OptionParser(usage) parser.add_option("-n", "--new", action="store_true", dest="preserve_new", default=False, help="create new .mo files for languages that are not yet in SVN") (options, args) = parser.parse_args() # Move to the right dir curdir = Path('.').abspath() if curdir.basename() == 'exe': if 'locale' in [p.relpath() for p in curdir.dirs()]: (curdir/'..').chdir() elif curdir.basename() == 'locale': (curdir/'..'/'..').chdir() print 'Running from: %s' % Path('.').abspath() # make sure any old build is not around to be scanned for strings shutil.rmtree('build', ignore_errors=True) shutil.rmtree('debian/python2.4-exe', ignore_errors=True) shutil.rmtree('debian/python2.5-exe', ignore_errors=True) shutil.rmtree('debian/python-exe', ignore_errors=True) try: os.remove('debian') except OSError: pass # Fill out the options option = {} option['forceEnglish'] = 0 option['mo'] = 0 option['po'] = 0 option['verbose'] = 1 option['domain'] = None option['moTarget'] = Path('exe/locale').abspath() option['domain'] = 'exe' if option['verbose']: print "Application domain used is: '%s'" % option['domain'] print 'Generating file list: app.fil' # Generate the list of files to use generateAppFil() # Make the .po files try: makePO(Path('.'),option['domain'],option['verbose']) except IOError, e: printUsage(e[1] + '\n You must write a file app.fil that contains the list of all files to parse.')
class Config: """ The Config class contains the configuration information for eXe. """ # Class attributes optionNames = { 'idevices': ('someone', ), 'system': ('webDir', 'xulDir', 'port', 'dataDir', 'configDir', 'localeDir', 'browserPath'), 'user': ('locale', ), } def __init__(self): """ Initialise """ self.configPath = None self.configParser = ConfigParser(self.onWrite) # Set default values # idevices is the list of hidden idevices selected by the user self.someone = 0 # exePath is the whole path and filename of the exe executable self.exePath = Path(sys.argv[0]).abspath() # webDir is the parent directory for styles,scripts and templates self.webDir = self.exePath.dirname() # xulDir is the parent directory for styles,scripts and templates self.xulDir = self.exePath.dirname() # localeDir is the base directory where all the locales are stored self.localeDir = self.exePath.dirname() / "locale" # port is the port the exe webserver will listen on # (previous default, which earlier users might still use, was 8081) self.port = 51235 # dataDir is the default directory that is shown to the user # to save packages and exports in self.dataDir = Path(".") # configDir is the dir for storing user profiles # and user made idevices and the config file self.configDir = Path(".") # browserPath is the entire pathname to firefox self.browserPath = Path("firefox") # locale is the language of the user self.locale = chooseDefaultLocale(self.localeDir) # internalAnchors indicate which exe_tmp_anchor tags to generate for each tinyMCE field # available values = "enable_all", "disable_autotop", or "disable_all" self.internalAnchors = "enable_all" # styles is the list of style names available for loading self.styles = [] # The documents that we've recently looked at self.recentProjects = [] # canonical (English) names of iDevices not to show in the iDevice pane self.hiddeniDevices = [] # likewise, a canonical (English) names of iDevices not to show in the # iDevice pane but, contrary to the hiddens, these are ones that the # configuration can specify to turn ON: self.deprecatediDevices = [ "flash with text", "flash movie", "mp3", \ "attachment"] # by default, only allow embedding of media types for which a # browser plugin is found: self.assumeMediaPlugins = False # Let our children override our defaults depending # on the OS that we're running on self._overrideDefaultVals() # Try to make the defaults a little intelligent # Under devel trees, webui is the default webdir self.webDir = Path(self.webDir) if not (self.webDir/'scripts').isdir() \ and (self.webDir/'webui').isdir(): self.webDir /= 'webui' # Under devel trees, xului is the default xuldir self.xulDir = Path(self.xulDir) if not (self.xulDir/'scripts').isdir() \ and (self.xulDir/'xului').isdir(): self.xulDir /= 'xului' # Find where the config file will be saved self.__setConfigPath() # Fill in any undefined config options with our defaults self._writeDefaultConfigFile() # Now we are ready to serve the application self.loadSettings() self.setupLogging() self.loadStyles() self.loadLocales() def _overrideDefaultVals(self): """ Override this to override the default config values """ def _getConfigPathOptions(self): """ Override this to give a list of possible config filenames in order of preference """ return ['exe.conf'] def _writeDefaultConfigFile(self): """ [Over]writes 'self.configPath' with a default config file (auto write is on so we don't need to write the file at the end) """ for sectionName, optionNames in self.optionNames.items(): for optionName in optionNames: defaultVal = getattr(self, optionName) self.configParser.setdefault(sectionName, optionName, defaultVal) # Logging can't really be changed from inside the program at the moment... self.configParser.setdefault('logging', 'root', 'INFO') def __setConfigPath(self): """ sets self.configPath to the filename of the config file that we'll use. In descendant classes set self.configFileOptions to a list of directories where the configDir should be in order of preference. If no config files can be found in these dirs, it will force creation of the config file in the top dir """ # If there's an EXECONF environment variable, use it self.configPath = None configFileOptions = map(Path, self._getConfigPathOptions()) if "EXECONF" in os.environ: envconf = Path(os.environ["EXECONF"]) if envconf.isfile(): self.configPath = os.environ["EXECONF"] # Otherwise find the most appropriate existing file if self.configPath is None: for confPath in configFileOptions: if confPath.isfile(): self.configPath = confPath break else: # If no config files exist, create and use the # first one on the list self.configPath = configFileOptions[0] folder = self.configPath.abspath().dirname() if not folder.exists(): folder.makedirs() self.configPath.touch() # Now make our configParser self.configParser.read(self.configPath) self.configParser.autoWrite = True def upgradeFile(self): """ Called before loading the config file, removes or upgrades any old settings. """ if self.configParser.has_section('system'): system = self.configParser.system if system.has_option('appDataDir'): # Older config files had configDir stored as appDataDir self.configDir = Path(system.appDataDir) # We'll just upgrade their config file for them for now... system.configDir = self.configDir del system.appDataDir if system.has_option('greDir'): # No longer used, system should automatically support del system.greDir def loadSettings(self): """ Loads the settings from the exe.conf file. Overrides the defaults set in __init__ """ # Set up the parser so that if a certain value is not in the config # file, it will use the value from our default values def defVal(dummy, option): """If something is not in the config file, just use the default in 'self'""" return getattr(self, option) self.configParser.defaultValue = defVal self.upgradeFile() # System Section if self.configParser.has_section('system'): system = self.configParser.system self.webDir = Path(system.webDir) self.xulDir = Path(system.xulDir) self.localeDir = Path(system.localeDir) self.port = int(system.port) self.browserPath = Path(system.browserPath) self.dataDir = Path(system.dataDir) self.configDir = Path(system.configDir) self.assumeMediaPlugins = False if self.configParser.has_option('system', \ 'assumeMediaPlugins'): value = system.assumeMediaPlugins.strip().lower() if value == "1" or value == "yes" or value == "true" or \ value == "on": self.assumeMediaPlugins = True # If the dataDir points to some other dir, fix it if not self.dataDir.isdir(): self.dataDir = tempfile.gettempdir() # make the webDir absolute, to hide path joins of relative paths self.webDir = self.webDir.expand().abspath() # If the configDir doesn't exist (as it may be a default setting with a # new installation) create it if not self.configDir.exists(): self.configDir.mkdir() # Get the list of recently opened projects self.recentProjects = [] if self.configParser.has_section('recent_projects'): recentProjectsSection = self.configParser.recent_projects for key, path in recentProjectsSection.items(): self.recentProjects.append(path) # Load the list of "hidden" iDevices self.hiddeniDevices = [] if self.configParser.has_section('idevices'): idevicesSection = self.configParser.idevices for key, value in idevicesSection.items(): # emulate standard library's getboolean() value = value.strip().lower() if value == "0" or value == "no" or value == "false" or \ value == "off": self.hiddeniDevices.append(key.lower()) #self.deprecatediDevices = [ "flash with text", "flash movie", ...] # and UN-Load from the list of "deprecated" iDevices if self.configParser.has_section('deprecated'): deprecatedSection = self.configParser.deprecated for key, value in deprecatedSection.items(): # emulate standard library's getboolean() value = value.strip().lower() if value == "1" or value == "yes" or value == "true" or \ value == "on": if key.lower() in self.deprecatediDevices: self.deprecatediDevices.remove(key.lower()) # Load the "user" section if self.configParser.has_section('user'): if self.configParser.user.has_option('internalAnchors'): self.internalAnchors = self.configParser.user.internalAnchors if self.configParser.user.has_option('locale'): self.locale = self.configParser.user.locale return self.locale = chooseDefaultLocale(self.localeDir) def onWrite(self, configParser): """ Called just before the config file is written. We use it to fill out any settings that are stored here and not in the config parser itself """ # Recent projects self.configParser.delete('recent_projects') recentProjectsSection = self.configParser.addSection('recent_projects') for num, path in enumerate(self.recentProjects): recentProjectsSection[str(num)] = path def setupLogging(self): """ setup logging file """ try: hdlr = RotatingFileHandler(self.configDir / 'exe.log', 'a', 500000, 10) hdlr.doRollover() except OSError: # ignore the error we get if the log file is logged hdlr = logging.FileHandler(self.configDir / 'exe.log') format = "%(asctime)s %(name)s %(levelname)s %(message)s" log = logging.getLogger() hdlr.setFormatter(logging.Formatter(format)) log.addHandler(hdlr) loggingLevels = { "DEBUG": logging.DEBUG, "INFO": logging.INFO, "WARNING": logging.WARNING, "ERROR": logging.ERROR, "CRITICAL": logging.CRITICAL } if self.configParser.has_section('logging'): for logger, level in self.configParser._sections["logging"].items( ): if logger == "root": logging.getLogger().setLevel(loggingLevels[level]) else: logging.getLogger(logger).setLevel(loggingLevels[level]) log.info("************** eXe logging started **************") log.info("configPath = %s" % self.configPath) log.info("exePath = %s" % self.exePath) log.info("browserPath = %s" % self.browserPath) log.info("webDir = %s" % self.webDir) log.info("xulDir = %s" % self.xulDir) log.info("localeDir = %s" % self.localeDir) log.info("port = %d" % self.port) log.info("dataDir = %s" % self.dataDir) log.info("configDir = %s" % self.configDir) log.info("locale = %s" % self.locale) log.info("internalAnchors = %s" % self.internalAnchors) def loadStyles(self): """ Scans the eXe style directory and builds a list of styles """ log = logging.getLogger() self.styles = [] styleDir = self.webDir / "style" log.debug("loadStyles from %s" % styleDir) for subDir in styleDir.dirs(): styleSheet = subDir / 'content.css' log.debug(" checking %s" % styleSheet) if styleSheet.exists(): style = subDir.basename() log.debug(" loading style %s" % style) self.styles.append(style) def loadLocales(self): """ Scans the eXe locale directory and builds a list of locales """ log = logging.getLogger() log.debug("loadLocales") gettext.install('exe', self.localeDir, True) self.locales = {} for subDir in self.localeDir.dirs(): if (subDir / 'LC_MESSAGES' / 'exe.mo').exists(): self.locales[subDir.basename()] = \ gettext.translation('exe', self.localeDir, languages=[str(subDir.basename())]) if subDir.basename() == self.locale: locale = subDir.basename() log.debug(" loading locale %s" % locale) self.locales[locale].install(unicode=True) # ===========================================================================
# S c r i p t e x e c u t i o n -- Runs when invoked from the command line -- # ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ # if __name__ == "__main__": usage = "usage: %prog [options]" parser = OptionParser(usage) parser.add_option("-n", "--new", action="store_true", dest="preserve_new", default=False, help="create new .mo files for languages that are not yet in SVN") (options, args) = parser.parse_args() # Move to the right dir curdir = Path('.').abspath() if curdir.basename() == 'exe': if 'locale' in [p.relpath() for p in curdir.dirs()]: (curdir/'..').chdir() elif curdir.basename() == 'locale': (curdir/'..'/'..').chdir() print 'Running from: %s' % Path('.').abspath() # make sure any old build is not around to be scanned for strings shutil.rmtree('build', ignore_errors=True) shutil.rmtree('debian/python2.4-exe', ignore_errors=True) shutil.rmtree('debian/python2.5-exe', ignore_errors=True) shutil.rmtree('debian/python-exe', ignore_errors=True) try: os.remove('debian') except OSError: pass # Fill out the options option = {}
if __name__ == "__main__": usage = "usage: %prog [options]" parser = OptionParser(usage) parser.add_option( "-n", "--new", action="store_true", dest="preserve_new", default=False, help="create new .mo files for languages that are not yet in SVN") (options, args) = parser.parse_args() # Move to the right dir curdir = Path('.').abspath() if curdir.basename() == 'exe': if 'locale' in [p.relpath() for p in curdir.dirs()]: (curdir / '..').chdir() elif curdir.basename() == 'locale': (curdir / '..' / '..').chdir() print 'Running from: %s' % Path('.').abspath() # make sure any old build is not around to be scanned for strings shutil.rmtree('build', ignore_errors=True) shutil.rmtree('debian/python2.4-exe', ignore_errors=True) shutil.rmtree('debian/python2.5-exe', ignore_errors=True) shutil.rmtree('debian/python-exe', ignore_errors=True) try: os.remove('debian') except OSError: pass # Fill out the options option = {}
class Config: """ The Config class contains the configuration information for eXe. """ optionNames = { "system": ("webDir", "xulDir", "port", "dataDir", "configDir", "localeDir", "browserPath"), "user": ("locale",), } def __init__(self): """ Initialise """ self.configPath = None self.configParser = ConfigParser() self.exePath = Path(sys.argv[0]).abspath() self.webDir = self.exePath.dirname() self.xulDir = self.exePath.dirname() self.localeDir = self.exePath.dirname() / "locale" self.port = 51235 self.dataDir = Path(".") self.configDir = Path(".") self.browserPath = Path("firefox") self.locale = chooseDefaultLocale(self.localeDir) self.styles = [] self._overrideDefaultVals() self.webDir = Path(self.webDir) if not (self.webDir / "scripts").isdir() and (self.webDir / "webui").isdir(): self.webDir /= "webui" self.xulDir = Path(self.xulDir) if not (self.xulDir / "scripts").isdir() and (self.xulDir / "xului").isdir(): self.xulDir /= "xului" self.__setConfigPath() self._writeDefaultConfigFile() self.loadSettings() self.setupLogging() self.loadStyles() self.loadLocales() def _overrideDefaultVals(self): """ Override this to override the default config values """ def _getConfigPathOptions(self): """ Override this to give a list of possible config filenames in order of preference """ return ["exe.conf"] def _writeDefaultConfigFile(self): """ [Over]writes 'self.configPath' with a default config file (auto write is on so we don't need to write the file at the end) """ for sectionName, optionNames in self.optionNames.items(): for optionName in optionNames: defaultVal = getattr(self, optionName) self.configParser.setdefault(sectionName, optionName, defaultVal) self.configParser.setdefault("logging", "root", "INFO") def __setConfigPath(self): """ sets self.configPath to the filename of the config file that we'll use. In descendant classes set self.configFileOptions to a list of directories where the configDir should be in order of preference. If no config files can be found in these dirs, it will force creation of the config file in the top dir """ self.configPath = None configFileOptions = map(Path, self._getConfigPathOptions()) if "EXECONF" in os.environ: envconf = Path(os.environ["EXECONF"]) if envconf.isfile(): self.configPath = os.environ["EXECONF"] if self.configPath is None: for confPath in configFileOptions: if confPath.isfile(): self.configPath = confPath break else: self.configPath = configFileOptions[0] folder = self.configPath.abspath().dirname() if not folder.exists(): folder.makedirs() self.configPath.touch() self.configParser.read(self.configPath) self.configParser.autoWrite = True def upgradeFile(self): """ Called before loading the config file, removes or upgrades any old settings. """ if self.configParser.has_section("system"): system = self.configParser.system if system.has_option("appDataDir"): self.configDir = Path(system.appDataDir) system.configDir = self.configDir del system.appDataDir if system.has_option("greDir"): del system.greDir def loadSettings(self): """ Loads the settings from the exe.conf file. Overrides the defaults set in __init__ """ def defVal(dummy, option): """If something is not in the config file, just use the default in 'self'""" return getattr(self, option) self.configParser.defaultValue = defVal self.upgradeFile() if self.configParser.has_section("system"): system = self.configParser.system self.webDir = Path(system.webDir) self.xulDir = Path(system.xulDir) self.localeDir = Path(system.localeDir) self.port = int(system.port) self.browserPath = Path(system.browserPath) self.dataDir = Path(system.dataDir) self.configDir = Path(system.configDir) if not self.dataDir.isdir(): self.dataDir = tempfile.gettempdir() self.webDir = self.webDir.expand().abspath() if not self.configDir.exists(): self.configDir.mkdir() if self.configParser.has_section("user"): if self.configParser.user.has_option("locale"): self.locale = self.configParser.user.locale return self.locale = chooseDefaultLocale(self.localeDir) def setupLogging(self): """ setup logging file """ try: hdlr = RotatingFileHandler(self.configDir / "exe.log", "a", 500000, 10) hdlr.doRollover() except OSError: hdlr = logging.FileHandler(self.configDir / "exe.log") format = "%(asctime)s %(name)s %(levelname)s %(message)s" log = logging.getLogger() hdlr.setFormatter(logging.Formatter(format)) log.addHandler(hdlr) loggingLevels = { "DEBUG": logging.DEBUG, "INFO": logging.INFO, "WARNING": logging.WARNING, "ERROR": logging.ERROR, "CRITICAL": logging.CRITICAL, } if self.configParser.has_section("logging"): for logger, level in self.configParser._sections["logging"].items(): if logger == "root": logging.getLogger().setLevel(loggingLevels[level]) else: logging.getLogger(logger).setLevel(loggingLevels[level]) log.info("************** eXe logging started **************") log.info("configPath = %s" % self.configPath) log.info("exePath = %s" % self.exePath) log.info("browserPath = %s" % self.browserPath) log.info("webDir = %s" % self.webDir) log.info("xulDir = %s" % self.xulDir) log.info("localeDir = %s" % self.localeDir) log.info("port = %d" % self.port) log.info("dataDir = %s" % self.dataDir) log.info("configDir = %s" % self.configDir) log.info("locale = %s" % self.locale) def loadStyles(self): """ Scans the eXe style directory and builds a list of styles """ log = logging.getLogger() self.styles = [] styleDir = self.webDir / "style" log.debug("loadStyles from %s" % styleDir) for subDir in styleDir.dirs(): styleSheet = subDir / "content.css" log.debug(" checking %s" % styleSheet) if styleSheet.exists(): style = subDir.basename() log.debug(" loading style %s" % style) self.styles.append(style) def loadLocales(self): """ Scans the eXe locale directory and builds a list of locales """ log = logging.getLogger() log.debug("loadLocales") gettext.install("exe", self.localeDir, True) self.locales = {} for subDir in self.localeDir.dirs(): if (subDir / "LC_MESSAGES" / "exe.mo").exists(): self.locales[subDir.basename()] = gettext.translation( "exe", self.localeDir, languages=[str(subDir.basename())] ) if subDir.basename() == self.locale: locale = subDir.basename() log.debug(" loading locale %s" % locale) self.locales[locale].install(unicode=True)
def render(self, request): if "sendWhat" in request.args: if request.args['sendWhat'][0] == 'dirs': pathdir = Path(unquote(request.args['node'][0].decode('utf-8'))) l = [] if pathdir == '/' and sys.platform[:3] == "win": for d in get_drives(): try: if is_readable(Path(d)): icon = None else: icon = '../jsui/extjs/resources/themes/images/gray/grid/hmenu-lock.gif' l.append({"realtext": d, "text": d, "id": d + '\\', "icon": icon}) except: pass else: for d in pathdir.dirs(): try: if not d.name.startswith('.') or sys.platform[:3] == "win": if not iswinlink(d.abspath()): if is_readable(d): icon = None else: icon = '../jsui/extjs/resources/themes/images/gray/grid/hmenu-lock.gif' l.append({"realtext": d.name, "text": getname(d), "id": d.abspath(), "icon": icon}) except: pass elif request.args['sendWhat'][0] == 'both': pathdir = Path(unquote(request.args['dir'][0].decode('utf-8'))) items = [] if pathdir == '/' and sys.platform[:3] == "win": for drive in get_drives(): d = Path(drive + '\\') items.append({"name": drive, "realname": drive + '\\', "size": 0, "type": 'directory', "modified": 0, "is_readable": is_readable(d), "is_writable": is_writable(d)}) else: parent = pathdir.parent if (parent == pathdir): realname = '/' else: realname = parent.abspath() items.append({"name": '.', "realname": pathdir.abspath(), "size": pathdir.size, "type": "directory", "modified": int(pathdir.mtime), "is_readable": is_readable(pathdir), "is_writable": is_writable(pathdir)}) items.append({"name": '..', "realname": realname, "size": parent.size, "type": "directory", "modified": int(parent.mtime), "is_readable": is_readable(parent), "is_writable": is_writable(parent)}) try: for d in pathdir.listdir(): try: if not d.name.startswith('.') or sys.platform[:3] == "win": if not iswinlink(d.abspath()): if d.isdir(): pathtype = "directory" elif d.isfile(): if is_readable(d): pathtype = repr(mimetypes.guess_type(d.name, False)[0]) else: pathtype = "file" elif d.islink(): pathtype = "link" else: pathtype = "None" items.append({"name": getname(d), "realname": d.abspath(), "size": d.size, "type": pathtype, "modified": int(d.mtime), "is_readable": is_readable(d), "is_writable": is_writable(d)}) except: pass G.application.config.lastDir = pathdir except: pass l = {"totalCount": len(items), 'results': len(items), 'items': items} return json.dumps(l).encode('utf-8') elif "query" in request.args: query = request.args['query'][0] pathdir = Path(unquote(request.args['dir'][0].decode('utf-8'))) items = [] if pathdir == '/' and sys.platform[:3] == "win": for d in get_drives(): items.append({"name": d, "realname": d + '\\', "size": 0, "type": 'directory', "modified": 0}) else: parent = pathdir.parent if (parent == pathdir): realname = '/' else: realname = parent.abspath() for d in pathdir.listdir(): try: if d.isdir(): pathtype = "directory" elif d.isfile(): if is_readable(d): pathtype = repr(mimetypes.guess_type(d.name, False)[0]) else: pathtype = "file" elif d.islink(): pathtype = "link" else: pathtype = "None" if d.name.startswith(query): items.append({"name": getname(d), "realname": d.abspath(), "size": d.size, "type": pathtype, "modified": int(d.mtime), "is_readable": is_readable(d), "is_writable": is_writable(d)}) except: pass l = {"totalCount": len(items), 'results': len(items), 'items': items} return json.dumps(l).encode('utf-8') return ""
def render(self, request): if "sendWhat" in request.args: if request.args['sendWhat'][0] == 'dirs': pathdir = Path(unquote( request.args['node'][0].decode('utf-8'))) l = [] if pathdir == '/' and sys.platform[:3] == "win": for d in get_drives(): try: if is_readable(Path(d)): icon = None else: icon = '../jsui/extjs/resources/themes/images/gray/grid/hmenu-lock.gif' l.append({ "realtext": d, "text": d, "id": d + '\\', "icon": icon }) except: pass else: for d in pathdir.dirs(): try: if not d.name.startswith( '.') or sys.platform[:3] == "win": if not iswinlink(d.abspath()): if is_readable(d): icon = None else: icon = '../jsui/extjs/resources/themes/images/gray/grid/hmenu-lock.gif' l.append({ "realtext": d.name, "text": getname(d), "id": d.abspath(), "icon": icon }) except: pass elif request.args['sendWhat'][0] == 'both': pathdir = Path(unquote(request.args['dir'][0].decode('utf-8'))) items = [] if pathdir == '/' and sys.platform[:3] == "win": for drive in get_drives(): d = Path(drive + '\\') items.append({ "name": drive, "realname": drive + '\\', "size": 0, "type": 'directory', "modified": 0, "is_readable": is_readable(d), "is_writable": is_writable(d) }) else: parent = pathdir.parent if (parent == pathdir): realname = '/' else: realname = parent.abspath() items.append({ "name": '.', "realname": pathdir.abspath(), "size": pathdir.size, "type": "directory", "modified": int(pathdir.mtime), "is_readable": is_readable(pathdir), "is_writable": is_writable(pathdir) }) items.append({ "name": '..', "realname": realname, "size": parent.size, "type": "directory", "modified": int(parent.mtime), "is_readable": is_readable(parent), "is_writable": is_writable(parent) }) try: for d in pathdir.listdir(): try: if not d.name.startswith( '.') or sys.platform[:3] == "win": if not iswinlink(d.abspath()): if d.isdir(): pathtype = "directory" elif d.isfile(): if is_readable(d): pathtype = repr( mimetypes.guess_type( d.name, False)[0]) else: pathtype = "file" elif d.islink(): pathtype = "link" else: pathtype = "None" items.append({ "name": getname(d), "realname": d.abspath(), "size": d.size, "type": pathtype, "modified": int(d.mtime), "is_readable": is_readable(d), "is_writable": is_writable(d) }) except: pass G.application.config.lastDir = pathdir except: pass l = { "totalCount": len(items), 'results': len(items), 'items': items } return json.dumps(l).encode('utf-8') elif "query" in request.args: query = request.args['query'][0] pathdir = Path(unquote(request.args['dir'][0].decode('utf-8'))) items = [] if pathdir == '/' and sys.platform[:3] == "win": for d in get_drives(): items.append({ "name": d, "realname": d + '\\', "size": 0, "type": 'directory', "modified": 0 }) else: parent = pathdir.parent if (parent == pathdir): realname = '/' else: realname = parent.abspath() for d in pathdir.listdir(): try: if d.isdir(): pathtype = "directory" elif d.isfile(): if is_readable(d): pathtype = repr( mimetypes.guess_type(d.name, False)[0]) else: pathtype = "file" elif d.islink(): pathtype = "link" else: pathtype = "None" if d.name.startswith(query): items.append({ "name": getname(d), "realname": d.abspath(), "size": d.size, "type": pathtype, "modified": int(d.mtime), "is_readable": is_readable(d), "is_writable": is_writable(d) }) except: pass l = { "totalCount": len(items), 'results': len(items), 'items': items } return json.dumps(l).encode('utf-8') return ""
def render(self, request): if "sendWhat" in request.args: if request.args['sendWhat'][0] == 'dirs': #Because this might be absolute and mess up... path_dir_str = unquote(request.args['node'][0].decode('utf-8')) path_dir_str = self.get_dirpath_for_request( request, path_dir_str) pathdir = Path(path_dir_str) l = [] if pathdir == '/' and sys.platform[:3] == "win": for d in get_drives(): try: if is_readable(Path(d)): icon = None else: icon = '../jsui/extjs/resources/themes/images/gray/grid/hmenu-lock.gif' l.append({"realtext": d, "text": d, "id": d + '\\', "icon": icon}) except: pass else: for d in pathdir.dirs(): try: if not d.name.startswith('.') or sys.platform[:3] == "win": if not iswinlink(d.abspath()): if is_readable(d): icon = None else: icon = '../jsui/extjs/resources/themes/images/gray/grid/hmenu-lock.gif' l.append({"realtext": d.name, "text": getname(d), "id": self.abs_to_user_path(d.abspath(), request), "icon": icon}) except: pass elif request.args['sendWhat'][0] == 'both': req_pathdir_str = unquote(request.args['dir'][0].decode('utf-8')) pathdir_str = self.get_dirpath_for_request( request, req_pathdir_str) pathdir = Path(pathdir_str) items = [] if pathdir == '/' and sys.platform[:3] == "win": for drive in get_drives(): d = Path(drive + '\\') items.append({"name": drive, "realname": drive + '\\', "size": 0, "type": 'directory', "modified": 0, "is_readable": is_readable(d), "is_writable": is_writable(d)}) else: parent = pathdir.parent if (parent == pathdir): realname = '/' else: realname = self.abs_to_user_path(parent.abspath(), request) items.append({"name": '.', "realname": self.abs_to_user_path(pathdir.abspath(), request), "size": pathdir.size, "type": "directory", "modified": int(pathdir.mtime), "is_readable": is_readable(pathdir), "is_writable": is_writable(pathdir)}) items.append({"name": '..', "realname": realname, "size": parent.size, "type": "directory", "modified": int(parent.mtime), "is_readable": is_readable(parent), "is_writable": is_writable(parent)}) try: for d in pathdir.listdir(): try: if not d.name.startswith('.') or sys.platform[:3] == "win": if not iswinlink(d.abspath()): if d.isdir(): pathtype = "directory" elif d.isfile(): if is_readable(d): pathtype = repr(mimetypes.guess_type(d.name, False)[0]) else: pathtype = "file" elif d.islink(): pathtype = "link" else: pathtype = "None" items.append({"name": getname(d), "realname": self.abs_to_user_path(d.abspath(), request), "size": d.size, "type": pathtype, "modified": int(d.mtime), "is_readable": is_readable(d), "is_writable": is_writable(d)}) except: pass #this was before just pathdir - check this if G.application.config.appMode != Config.MODE_WEBAPP: G.application.config.lastDir = pathdir else: self.session.webservice_config.lastDir = req_pathdir_str except: pass l = {"totalCount": len(items), 'results': len(items), 'items': items} return json.dumps(l).encode('utf-8') elif "query" in request.args: query = request.args['query'][0] path_dir_str = unquote(request.args['dir'][0].decode('utf-8')) path_dir_str = self.get_dirpath_for_request(request,path_dir_str) pathdir = Path(path_dir_str) items = [] if pathdir == '/' and sys.platform[:3] == "win": for d in get_drives(): items.append({"name": d, "realname": d + '\\', "size": 0, "type": 'directory', "modified": 0}) else: parent = pathdir.parent if (parent == pathdir): realname = '/' else: realname = self.abs_to_user_path(parent.abspath(), request) for d in pathdir.listdir(): try: if d.isdir(): pathtype = "directory" elif d.isfile(): if is_readable(d): pathtype = repr(mimetypes.guess_type(d.name, False)[0]) else: pathtype = "file" elif d.islink(): pathtype = "link" else: pathtype = "None" if d.name.startswith(query): items.append({"name": getname(d), "realname": self.abs_to_user_path(d.abspath(), request), "size": d.size, "type": pathtype, "modified": int(d.mtime), "is_readable": is_readable(d), "is_writable": is_writable(d)}) except: pass l = {"totalCount": len(items), 'results': len(items), 'items': items} return json.dumps(l).encode('utf-8') elif "uploadfileaction" in request.args: filename = request.args["upload_file_name"][0] current_dir = request.args["upload_current_dir"][0] save_path = os.path.join(current_dir, filename) file_path = self.get_dirpath_for_request( request, save_path) file = open(file_path, "wb") file.write(request.args['upload_file'][0]) file.close() result = {"success" : True} return json.dumps(result).encode('utf-8') return ""
class Config: """ The Config class contains the configuration information for eXe. """ optionNames = { 'system': ('webDir', 'xulDir', 'port', 'dataDir', 'configDir', 'localeDir', 'browserPath'), 'user': ('locale',), } def __init__(self): """ Initialise """ self.configPath = None self.configParser = ConfigParser(self.onWrite) self.exePath = Path(sys.argv[0]).abspath() self.webDir = self.exePath.dirname() self.xulDir = self.exePath.dirname() self.localeDir = self.exePath.dirname()/"locale" self.port = 51235 self.dataDir = Path(".") self.configDir = Path(".") self.browserPath = Path("firefox") self.locale = chooseDefaultLocale(self.localeDir) self.styles = [] self.recentProjects = [] self.hiddeniDevices = [] self.deprecatediDevices = [ "flash with text", "flash movie", "mp3", \ "attachment"] self.assumeMediaPlugins = False; self._overrideDefaultVals() self.webDir = Path(self.webDir) if not (self.webDir/'scripts').isdir() \ and (self.webDir/'webui').isdir(): self.webDir /= 'webui' self.xulDir = Path(self.xulDir) if not (self.xulDir/'scripts').isdir() \ and (self.xulDir/'xului').isdir(): self.xulDir /= 'xului' self.__setConfigPath() self._writeDefaultConfigFile() self.loadSettings() self.setupLogging() self.loadStyles() self.loadLocales() def _overrideDefaultVals(self): """ Override this to override the default config values """ def _getConfigPathOptions(self): """ Override this to give a list of possible config filenames in order of preference """ return ['exe.conf'] def _writeDefaultConfigFile(self): """ [Over]writes 'self.configPath' with a default config file (auto write is on so we don't need to write the file at the end) """ for sectionName, optionNames in self.optionNames.items(): for optionName in optionNames: defaultVal = getattr(self, optionName) self.configParser.setdefault(sectionName, optionName, defaultVal) self.configParser.setdefault('logging', 'root', 'INFO') def __setConfigPath(self): """ sets self.configPath to the filename of the config file that we'll use. In descendant classes set self.configFileOptions to a list of directories where the configDir should be in order of preference. If no config files can be found in these dirs, it will force creation of the config file in the top dir """ self.configPath = None configFileOptions = map(Path, self._getConfigPathOptions()) if "EXECONF" in os.environ: envconf = Path(os.environ["EXECONF"]) if envconf.isfile(): self.configPath = os.environ["EXECONF"] if self.configPath is None: for confPath in configFileOptions: if confPath.isfile(): self.configPath = confPath break else: self.configPath = configFileOptions[0] folder = self.configPath.abspath().dirname() if not folder.exists(): folder.makedirs() self.configPath.touch() self.configParser.read(self.configPath) self.configParser.autoWrite = True def upgradeFile(self): """ Called before loading the config file, removes or upgrades any old settings. """ if self.configParser.has_section('system'): system = self.configParser.system if system.has_option('appDataDir'): self.configDir = Path(system.appDataDir) system.configDir = self.configDir del system.appDataDir if system.has_option('greDir'): del system.greDir def loadSettings(self): """ Loads the settings from the exe.conf file. Overrides the defaults set in __init__ """ def defVal(dummy, option): """If something is not in the config file, just use the default in 'self'""" return getattr(self, option) self.configParser.defaultValue = defVal self.upgradeFile() if self.configParser.has_section('system'): system = self.configParser.system self.webDir = Path(system.webDir) self.xulDir = Path(system.xulDir) self.localeDir = Path(system.localeDir) self.port = int(system.port) self.browserPath = Path(system.browserPath) self.dataDir = Path(system.dataDir) self.configDir = Path(system.configDir) self.assumeMediaPlugins = False; if self.configParser.has_option('system', \ 'assumeMediaPlugins'): value = system.assumeMediaPlugins.strip().lower() if value == "1" or value == "yes" or value == "true" or \ value == "on": self.assumeMediaPlugins = True; if not self.dataDir.isdir(): self.dataDir = tempfile.gettempdir() self.webDir = self.webDir.expand().abspath() if not self.configDir.exists(): self.configDir.mkdir() self.recentProjects = [] if self.configParser.has_section('recent_projects'): recentProjectsSection = self.configParser.recent_projects for key, path in recentProjectsSection.items(): self.recentProjects.append(path) self.hiddeniDevices = [] if self.configParser.has_section('idevices'): idevicesSection = self.configParser.idevices for key,value in idevicesSection.items(): value = value.strip().lower() if value == "0" or value == "no" or value == "false" or \ value == "off": self.hiddeniDevices.append(key.lower()) if self.configParser.has_section('deprecated'): deprecatedSection = self.configParser.deprecated for key,value in deprecatedSection.items(): value = value.strip().lower() if value == "1" or value == "yes" or value == "true" or \ value == "on": if key.lower() in self.deprecatediDevices: self.deprecatediDevices.remove(key.lower()) if self.configParser.has_section('user'): if self.configParser.user.has_option('locale'): self.locale = self.configParser.user.locale return self.locale = chooseDefaultLocale(self.localeDir) def onWrite(self, configParser): """ Called just before the config file is written. We use it to fill out any settings that are stored here and not in the config parser itself """ self.configParser.delete('recent_projects') recentProjectsSection = self.configParser.addSection('recent_projects') for num, path in enumerate(self.recentProjects): recentProjectsSection[str(num)] = path def setupLogging(self): """ setup logging file """ try: hdlr = RotatingFileHandler(self.configDir/'exe.log', 'a', 500000, 10) hdlr.doRollover() except OSError: hdlr = logging.FileHandler(self.configDir/'exe.log') format = "%(asctime)s %(name)s %(levelname)s %(message)s" log = logging.getLogger() hdlr.setFormatter(logging.Formatter(format)) log.addHandler(hdlr) loggingLevels = {"DEBUG" : logging.DEBUG, "INFO" : logging.INFO, "WARNING" : logging.WARNING, "ERROR" : logging.ERROR, "CRITICAL" : logging.CRITICAL } if self.configParser.has_section('logging'): for logger, level in self.configParser._sections["logging"].items(): if logger == "root": logging.getLogger().setLevel(loggingLevels[level]) else: logging.getLogger(logger).setLevel(loggingLevels[level]) log.info("************** eXe logging started **************") log.info("configPath = %s" % self.configPath) log.info("exePath = %s" % self.exePath) log.info("browserPath = %s" % self.browserPath) log.info("webDir = %s" % self.webDir) log.info("xulDir = %s" % self.xulDir) log.info("localeDir = %s" % self.localeDir) log.info("port = %d" % self.port) log.info("dataDir = %s" % self.dataDir) log.info("configDir = %s" % self.configDir) log.info("locale = %s" % self.locale) def loadStyles(self): """ Scans the eXe style directory and builds a list of styles """ log = logging.getLogger() self.styles = [] styleDir = self.webDir/"style" log.debug("loadStyles from %s" % styleDir) for subDir in styleDir.dirs(): styleSheet = subDir/'content.css' log.debug(" checking %s" % styleSheet) if styleSheet.exists(): style = subDir.basename() log.debug(" loading style %s" % style) self.styles.append(style) def loadLocales(self): """ Scans the eXe locale directory and builds a list of locales """ log = logging.getLogger() log.debug("loadLocales") gettext.install('exe', self.localeDir, True) self.locales = {} for subDir in self.localeDir.dirs(): if (subDir/'LC_MESSAGES'/'exe.mo').exists(): self.locales[subDir.basename()] = \ gettext.translation('exe', self.localeDir, languages=[str(subDir.basename())]) if subDir.basename() == self.locale: locale = subDir.basename() log.debug(" loading locale %s" % locale) self.locales[locale].install(unicode=True)
class Config: """ The Config class contains the configuration information for eXe. """ # Class attributes optionNames = { 'system': ('webDir', 'xulDir', 'port', 'dataDir', 'configDir', 'localeDir', 'browserPath', ), 'user': ('locale', 'latexpath'), } def __init__(self): """ Initialise """ self.configPath = None self.configParser = ConfigParser(self.onWrite) # Set default values # exePath is the whole path and filename of the exe executable self.exePath = Path(sys.argv[0]).abspath() # webDir is the parent directory for styles,scripts and templates self.webDir = self.exePath.dirname() # xulDir is the parent directory for styles,scripts and templates self.xulDir = self.exePath.dirname() # localeDir is the base directory where all the locales are stored self.localeDir = self.exePath.dirname()/"locale" # port is the port the exe webserver will listen on # (previous default, which earlier users might still use, was 8081) self.port = 51235 # dataDir is the default directory that is shown to the user # to save packages and exports in self.dataDir = Path(".") # configDir is the dir for storing user profiles # and user made idevices and the config file self.configDir = Path(".") # browserPath is the entire pathname to firefox self.browserPath = Path("firefox") # locale is the language of the user self.locale = chooseDefaultLocale(self.localeDir) # internalAnchors indicate which exe_tmp_anchor tags to generate for each tinyMCE field # available values = "enable_all", "disable_autotop", or "disable_all" self.internalAnchors = "enable_all" # styles is the list of style names available for loading self.styles = [] # The documents that we've recently looked at self.recentProjects = [] # canonical (English) names of iDevices not to show in the iDevice pane self.hiddeniDevices = [] # likewise, a canonical (English) names of iDevices not to show in the # iDevice pane but, contrary to the hiddens, these are ones that the # configuration can specify to turn ON: self.deprecatediDevices = [ "flash with text", "flash movie", "mp3", \ "attachment"] # by default, only allow embedding of media types for which a # browser plugin is found: self.assumeMediaPlugins = False; # Let our children override our defaults depending # on the OS that we're running on self._overrideDefaultVals() # Try to make the defaults a little intelligent # Under devel trees, webui is the default webdir self.webDir = Path(self.webDir) if not (self.webDir/'scripts').isdir() \ and (self.webDir/'webui').isdir(): self.webDir /= 'webui' # Under devel trees, xului is the default xuldir self.xulDir = Path(self.xulDir) if not (self.xulDir/'scripts').isdir() \ and (self.xulDir/'xului').isdir(): self.xulDir /= 'xului' # Latex distribution path if environment wasn't set properly self.latexpath = "" # Find where the config file will be saved self.__setConfigPath() # Fill in any undefined config options with our defaults self._writeDefaultConfigFile() # Now we are ready to serve the application self.loadSettings() self.setupLogging() self.loadStyles() self.loadLocales() def _overrideDefaultVals(self): """ Override this to override the default config values """ def _getConfigPathOptions(self): """ Override this to give a list of possible config filenames in order of preference """ return ['exe.conf'] def _writeDefaultConfigFile(self): """ [Over]writes 'self.configPath' with a default config file (auto write is on so we don't need to write the file at the end) """ for sectionName, optionNames in self.optionNames.items(): for optionName in optionNames: defaultVal = getattr(self, optionName) self.configParser.setdefault(sectionName, optionName, defaultVal) # Logging can't really be changed from inside the program at the moment... self.configParser.setdefault('logging', 'root', 'INFO') def _getWinFolder(self, code): """ Gets one of the windows famous directorys depending on 'code' Possible values can be found at: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/enums/csidl.asp#CSIDL_WINDOWS """ from ctypes import WinDLL, create_unicode_buffer dll = WinDLL('shell32') # The '5' and the '0' from the below call come from # google: "ShellSpecialConstants site:msdn.microsoft.com" result = create_unicode_buffer(260) resource = dll.SHGetFolderPathW(None, code, None, 0, result) if resource != 0: return Path('') else: return Path(result.value) def __setConfigPath(self): """ sets self.configPath to the filename of the config file that we'll use. In descendant classes set self.configFileOptions to a list of directories where the configDir should be in order of preference. If no config files can be found in these dirs, it will force creation of the config file in the top dir """ # If there's an EXECONF environment variable, use it self.configPath = None configFileOptions = map(Path, self._getConfigPathOptions()) if "EXECONF" in os.environ: envconf = Path(os.environ["EXECONF"]) if envconf.isfile(): self.configPath = os.environ["EXECONF"] # Otherwise find the most appropriate existing file if self.configPath is None: for confPath in configFileOptions: if confPath.isfile(): self.configPath = confPath break else: # If no config files exist, create and use the # first one on the list self.configPath = configFileOptions[0] folder = self.configPath.abspath().dirname() if not folder.exists(): folder.makedirs() self.configPath.touch() # Now make our configParser self.configParser.read(self.configPath) self.configParser.autoWrite = True def upgradeFile(self): """ Called before loading the config file, removes or upgrades any old settings. """ if self.configParser.has_section('system'): system = self.configParser.system if system.has_option('appDataDir'): # Older config files had configDir stored as appDataDir self.configDir = Path(system.appDataDir) # We'll just upgrade their config file for them for now... system.configDir = self.configDir del system.appDataDir if system.has_option('greDir'): # No longer used, system should automatically support del system.greDir def loadSettings(self): """ Loads the settings from the exe.conf file. Overrides the defaults set in __init__ """ # Set up the parser so that if a certain value is not in the config # file, it will use the value from our default values def defVal(dummy, option): """If something is not in the config file, just use the default in 'self'""" return getattr(self, option) self.configParser.defaultValue = defVal self.upgradeFile() # System Section if self.configParser.has_section('system'): system = self.configParser.system self.webDir = Path(system.webDir) self.xulDir = Path(system.xulDir) self.localeDir = Path(system.localeDir) self.port = int(system.port) self.browserPath = Path(system.browserPath) self.dataDir = Path(system.dataDir) self.configDir = Path(system.configDir) self.assumeMediaPlugins = False; if self.configParser.has_option('system', \ 'assumeMediaPlugins'): value = system.assumeMediaPlugins.strip().lower() if value == "1" or value == "yes" or value == "true" or \ value == "on": self.assumeMediaPlugins = True; # If the dataDir points to some other dir, fix it if not self.dataDir.isdir(): self.dataDir = tempfile.gettempdir() # make the webDir absolute, to hide path joins of relative paths self.webDir = self.webDir.expand().abspath() # If the configDir doesn't exist (as it may be a default setting with a # new installation) create it if not self.configDir.exists(): self.configDir.mkdir() # Get the list of recently opened projects self.recentProjects = [] if self.configParser.has_section('recent_projects'): recentProjectsSection = self.configParser.recent_projects for key, path in recentProjectsSection.items(): self.recentProjects.append(path) # Load the list of "hidden" iDevices self.hiddeniDevices = [] if self.configParser.has_section('idevices'): idevicesSection = self.configParser.idevices for key,value in idevicesSection.items(): # emulate standard library's getboolean() value = value.strip().lower() if value == "0" or value == "no" or value == "false" or \ value == "off": self.hiddeniDevices.append(key.lower()) #self.deprecatediDevices = [ "flash with text", "flash movie", ...] # and UN-Load from the list of "deprecated" iDevices if self.configParser.has_section('deprecated'): deprecatedSection = self.configParser.deprecated for key,value in deprecatedSection.items(): # emulate standard library's getboolean() value = value.strip().lower() if value == "1" or value == "yes" or value == "true" or \ value == "on": if key.lower() in self.deprecatediDevices: self.deprecatediDevices.remove(key.lower()) # Load the "user" section if self.configParser.has_section('user'): if self.configParser.user.has_option('internalAnchors'): self.internalAnchors = self.configParser.user.internalAnchors if self.configParser.user.has_option('locale'): self.locale = self.configParser.user.locale return self.locale = chooseDefaultLocale(self.localeDir) def onWrite(self, configParser): """ Called just before the config file is written. We use it to fill out any settings that are stored here and not in the config parser itself """ # Recent projects self.configParser.delete('recent_projects') recentProjectsSection = self.configParser.addSection('recent_projects') for num, path in enumerate(self.recentProjects): recentProjectsSection[str(num)] = path def setupLogging(self): """ setup logging file """ try: hdlr = RotatingFileHandler(self.configDir/'exe.log', 'a', 500000, 10) hdlr.doRollover() except OSError: # ignore the error we get if the log file is logged hdlr = logging.FileHandler(self.configDir/'exe.log') format = "%(asctime)s %(name)s %(levelname)s %(message)s" log = logging.getLogger() hdlr.setFormatter(logging.Formatter(format)) log.addHandler(hdlr) loggingLevels = {"DEBUG" : logging.DEBUG, "INFO" : logging.INFO, "WARNING" : logging.WARNING, "ERROR" : logging.ERROR, "CRITICAL" : logging.CRITICAL } if self.configParser.has_section('logging'): for logger, level in self.configParser._sections["logging"].items(): if logger == "root": logging.getLogger().setLevel(loggingLevels[level]) else: logging.getLogger(logger).setLevel(loggingLevels[level]) log.info("************** eXe logging started **************") log.info("configPath = %s" % self.configPath) log.info("exePath = %s" % self.exePath) log.info("browserPath = %s" % self.browserPath) log.info("webDir = %s" % self.webDir) log.info("xulDir = %s" % self.xulDir) log.info("localeDir = %s" % self.localeDir) log.info("port = %d" % self.port) log.info("dataDir = %s" % self.dataDir) log.info("configDir = %s" % self.configDir) log.info("locale = %s" % self.locale) log.info("internalAnchors = %s" % self.internalAnchors) def loadStyles(self): """ Scans the eXe style directory and builds a list of styles """ log = logging.getLogger() self.styles = [] styleDir = self.webDir/"style" localeStyleDir = self.configDir / "style" if not os.path.exists(localeStyleDir): os.makedirs(localeStyleDir) log.debug("loadStyles from %s" % styleDir) for subDir in styleDir.dirs(): if self.__checkStyle(subDir): styleName = subDir.basename() log.debug(" adding style to style/%s" % styleName) self.styles.append(styleName) # adding style from config to style/locale for subDir in localeStyleDir.dirs(): if self.__checkStyle(subDir): styleName = "locale/" + subDir.basename() log.debug(" adding locale style to style/%s" % styleName) self.styles.append(styleName) def __checkStyle(self, style): '''Checks if it's valid style''' styleSheet = style / 'content.css' return styleSheet.exists() def loadLocales(self): """ Scans the eXe locale directory and builds a list of locales """ log = logging.getLogger() log.debug("loadLocales") gettext.install('exe', self.localeDir, True) self.locales = {} for subDir in self.localeDir.dirs(): if (subDir/'LC_MESSAGES'/'exe.mo').exists(): self.locales[subDir.basename()] = \ gettext.translation('exe', self.localeDir, languages=[str(subDir.basename())]) if subDir.basename() == self.locale: locale = subDir.basename() log.debug(" loading locale %s" % locale) self.locales[locale].install(unicode=True)
try: # Try to get templates' strings execfile(application.config.templatesDir / 'strings.py') print(u'Re-adding HTML to template translations') # Load all locale catalogs locale_catalogs = {} for name, locale in application.config.locales.iteritems(): current_locale = {} current_locale['locale'] = locale locale_catalogs[name] = current_locale # Load the catalogs from the temp directory for sub_dir in locale_path.dirs(): if (sub_dir / 'LC_MESSAGES' / 'exe.po').exists() and os.path.basename(sub_dir) in locale_catalogs: catalog_stream = open(sub_dir / 'LC_MESSAGES' / 'exe.po', 'r') catalog_string = catalog_stream.read() catalog_stream.close() locale_catalogs[os.path.basename(sub_dir)]['catalog'] = read_po(StringIO(catalog_string)) locale_catalogs[os.path.basename(sub_dir)]['path'] = sub_dir / 'LC_MESSAGES' / 'exe.po' # Go through all the templates, nodes, idevices and fields for path, template in templates.iteritems(): for node in template['nodes']: for idevice in node['idevices']: for field in idevice['fields']: # For each locale for name, locale in locale_catalogs.iteritems():
try: # Try to get templates' strings execfile(application.config.templatesDir / 'strings.py') print(u'Re-adding HTML to template translations') # Load all locale catalogs locale_catalogs = {} for name, locale in application.config.locales.iteritems(): current_locale = {} current_locale['locale'] = locale locale_catalogs[name] = current_locale # Load the catalogs from the temp directory for sub_dir in locale_path.dirs(): if (sub_dir / 'LC_MESSAGES' / 'exe.po' ).exists() and os.path.basename(sub_dir) in locale_catalogs: catalog_stream = open(sub_dir / 'LC_MESSAGES' / 'exe.po', 'r') catalog_string = catalog_stream.read() catalog_stream.close() locale_catalogs[os.path.basename( sub_dir)]['catalog'] = read_po(StringIO(catalog_string)) locale_catalogs[os.path.basename( sub_dir)]['path'] = sub_dir / 'LC_MESSAGES' / 'exe.po' # Go through all the templates, nodes, idevices and fields for path, template in templates.iteritems(): for node in template['nodes']: for idevice in node['idevices']: