Beispiel #1
0
 def testUpgradeTo0_20(self):
     """
     Creates a package similar to what 0.19 would
     and tests if it upgrades ok
     """
     fn = Path('0.19 resources upgrade test.elp')
     assert fn.isfile() or fn.islink()
     package = self.package.__class__.load(fn)
     assert hasattr(package, 'resources')
     assert len(package.resources) == 8, len(package.resources)
     for checksum, resources in package.resources.items():
         storageNames = []
         userNames = []
         for res in resources:
             storageNames.append(res.storageName)
             userNames.append(res.userName)
         assert len(
             set(storageNames)
         ) == 1, 'Two identical resources have different storage names:\n%s' % storageNames
     allResourceNames = []
     for reses in package.resources.values():
         allResourceNames.append(reses[0].storageName)
     filenames = [path.basename() for path in package.resourceDir.files()]
     withoutDups = set(filenames) - set(allResourceNames)
     assert withoutDups == set(
         []), "Duplicate files weren't deleted %s" % withoutDups
     assert len(filenames) == len(allResourceNames)
     assert len(filenames) > 0, 'All resources have been deleted!'
Beispiel #2
0
    def uploadFile(self):
        '''Store pdf in package, gets sides from pdf, if self.sides
        isn't empty
        '''
        filePath = self.path
        log.debug(u"uploadFile " + unicode(filePath))
        if not self.parentNode or not self.parentNode.package:
            log.error('something is wrong with the file')
        ## replace all non-digits and non-usefull stuff with ''
        self.pages = sub('[^\d,-]', '', self.pages)
        if self.pages != "":
            input = PdfFileReader(file(filePath, "rb"))
            lastPage = input.getNumPages() - 1 # last page
            toimport = PdfIdevice.__parseImportPages(self.pages, lastPage)
            log.debug("Parsed pages: " + str(toimport))
            output = PdfFileWriter()

            for page in toimport:
                output.addPage(input.getPage(page))
            log.debug("Found pages to import %s" % toimport)
            tmp = os.tmpnam() + ".pdf"
            log.debug('Tempfile is %s' % tmp)
            outputStream = file(tmp, "wb")
            output.write(outputStream)
            outputStream.close()
            resourceFile = Path(tmp)
            self.file = Resource(self, resourceFile)
            log.debug("Uploaded %s, pages: %s" % (tmp, toimport)) 
            os.remove(tmp)
            filePath = tmp
        resourceFile = Path(filePath)
        if resourceFile.isfile():
            self.file = Resource(self, resourceFile)
            log.debug(u"uploaded " + self.path)
 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
Beispiel #4
0
class StandaloneConfig(Config):
    """
    The StandaloneConfig overrides the Config class with ready-to-run specific
    configuration
    """
    
    def _overrideDefaultVals(self):
        """
        Setup with our default settings
        """
        self.exePath = Path(sys.argv[0])
        if self.exePath.isfile():
            self.exePath = self.exePath.dirname()
        exePath = self.exePath
        # Override the default settings
        self.webDir        = exePath
        self.configDir     = exePath/'config'
        self.localeDir     = exePath/'locale'
        self.stylesDir     = Path(exePath/'style').abspath()
        self.styles        = []
        self.lastDir       = exePath

    def _getConfigPathOptions(self):
        """
        Returns the best places for a linux config file
        """
        return [self.configDir/'exe.conf']
Beispiel #5
0
class StandaloneConfig(Config):
    """
    The StandaloneConfig overrides the Config class with ready-to-run specific
    configuration
    """
    def _overrideDefaultVals(self):
        """
        Setup with our default settings
        """
        self.exePath = Path(sys.argv[0])
        if self.exePath.isfile():
            self.exePath = self.exePath.dirname()
        exePath = self.exePath
        # Override the default settings
        self.webDir = exePath
        self.dataDir = exePath / 'packages'
        if not self.dataDir.exists():
            self.dataDir.makedirs()
        self.configDir = Path(self._getWinFolder(APPDATA)) / 'exe'
        self.localeDir = exePath / 'locale'
        self.xulrunnerPath = exePath / 'xulrunner/xulrunner'
        self.styles = []
        self.browserPath = exePath / 'firefox' / 'firefox.exe'

    def _getConfigPathOptions(self):
        """
        Returns the best places for a linux config file
        """
        return [self.configDir / 'exe.conf']
Beispiel #6
0
 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
Beispiel #7
0
 def setFlash(self, flashPath):
     """
     Store the image in the package
     Needs to be in a package to work.
     """
     log.debug(u"setFlash "+unicode(flashPath))
     resourceFile = Path(flashPath)
     assert(self.idevice.parentNode,
            'Flash '+self.idevice.id+' has no parentNode')
     assert(self.idevice.parentNode.package,
            'iDevice '+self.idevice.parentNode.id+' has no package')
     if resourceFile.isfile():
         if self.flashResource:
             self.flashResource.delete()
             self.idevice.userResources.remove(self.flashResource)
         try:
             flvDic = FLVReader(resourceFile)
             self.height = flvDic["height"] +30        
             self.width  = flvDic["width"]
             self.flashResource = Resource(self.idevice.parentNode.package,
                                           resourceFile)
             self.idevice.userResources.append(self.flashResource)
         except AssertionError: 
             log.error('File %s is not a flash movie' % resourceFile)
     else:
         log.error('File %s is not a file' % resourceFile)
Beispiel #8
0
class StandaloneConfig(Config):
    """
    The StandaloneConfig overrides the Config class with ready-to-run specific
    configuration
    """
    def _overrideDefaultVals(self):
        """
        Setup with our default settings
        """
        self.exePath = Path(sys.argv[0])
        if self.exePath.isfile():
            self.exePath = self.exePath.dirname()
        exePath = self.exePath
        self.webDir        = exePath
        self.dataDir       = exePath/'packages'
        if not self.dataDir.exists():
            self.dataDir.makedirs()
        self.configDir     = exePath/'config'
        self.localeDir     = exePath/'locale'
        self.xulrunnerPath = exePath/'xulrunner/xulrunner'
        self.styles        = []
        self.browserPath = exePath/'firefox'/'firefox.exe'
    def _getConfigPathOptions(self):
        """
        Returns the best places for a linux config file
        """
        return [self.configDir/'exe.conf']
Beispiel #9
0
 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
Beispiel #10
0
class StandaloneConfig(Config):
    """
    The StandaloneConfig overrides the Config class with ready-to-run specific
    configuration
    """
    def _overrideDefaultVals(self):
        """
        Setup with our default settings
        """
        self.exePath = Path(sys.argv[0])
        if self.exePath.isfile():
            self.exePath = self.exePath.dirname()
        exePath = self.exePath
        # Override the default settings
        self.webDir = exePath
        self.configDir = exePath / 'config'
        self.localeDir = exePath / 'locale'
        self.stylesDir = Path(exePath / 'style').abspath()
        self.templatesDir = Path(exePath / 'content_template').abspath()
        self.styles = []
        self.lastDir = exePath

    def _getConfigPathOptions(self):
        """
        Returns the best places for a linux config file
        """
        return [self.configDir / 'exe.conf']
Beispiel #11
0
 def testUpgradeTo0_20(self):
     """
     Creates a package similar to what 0.19 would
     and tests if it upgrades ok
     """
     fn = Path('0.19 resources upgrade test.elp')
     assert fn.isfile() or fn.islink()
     package = self.package.__class__.load(fn)
     assert hasattr(package, 'resources')
     assert len(package.resources) == 8, len(package.resources)
     for checksum, resources in package.resources.items():
         storageNames = []
         userNames = []
         for res in resources:
             storageNames.append(res.storageName)
             userNames.append(res.userName)
         assert len(set(storageNames)) == 1, 'Two identical resources have different storage names:\n%s' % storageNames
     allResourceNames = []
     for reses in package.resources.values():
         allResourceNames.append(reses[0].storageName)
     filenames = [path.basename() for path in package.resourceDir.files()]
     withoutDups = set(filenames) - set(allResourceNames)
     assert withoutDups == set([]), "Duplicate files weren't deleted %s" % withoutDups
     assert len(filenames) == len(allResourceNames)
     assert len(filenames) > 0, 'All resources have been deleted!'
Beispiel #12
0
    def uploadFile(self):
        """Store pdf in package, gets sides from pdf, if self.sides
        isn't empty
        """
        filePath = self.path
        log.debug(u"uploadFile " + unicode(filePath))
        if not self.parentNode or not self.parentNode.package:
            log.error("something is wrong with the file")
        ## replace all non-digits and non-usefull stuff with ''
        self.pages = sub("[^\d,-]", "", self.pages)
        if self.pages != "":
            input = PdfFileReader(file(filePath, "rb"))
            lastPage = input.getNumPages() - 1  # last page
            toimport = PdfIdevice.__parseImportPages(self.pages, lastPage)
            log.debug("Parsed pages: " + str(toimport))
            output = PdfFileWriter()

            for page in toimport:
                output.addPage(input.getPage(page))
            log.debug("Found pages to import %s" % toimport)
            tmp = os.tmpnam() + ".pdf"
            log.debug("Tempfile is %s" % tmp)
            outputStream = file(tmp, "wb")
            output.write(outputStream)
            outputStream.close()
            resourceFile = Path(tmp)
            self.file = Resource(self, resourceFile)
            log.debug("Uploaded %s, pages: %s" % (tmp, toimport))
            os.remove(tmp)
            filePath = tmp
        resourceFile = Path(filePath)
        if resourceFile.isfile():
            self.file = Resource(self, resourceFile)
            log.debug(u"uploaded " + self.path)
Beispiel #13
0
    def render_POST(self, request=None):
        log.debug("render_POST")

        lang_only = False

        data = {}
        try:
            clear = False
            if 'clear' in request.args:
                clear = True
                request.args.pop('clear')
            if 'lang_only' in request.args:
                lang_only = True
                request.args.pop('lang_only')
            if 'lom_general_title_string1' in request.args:
                if clear:
                    self.package.setLomDefaults()
                else:
                    self.setLom(request.args)
            elif 'lomes_general_title_string1' in request.args:
                if clear:
                    self.package.setLomEsDefaults()
                else:
                    self.setLomes(request.args)
            else:
                items = request.args.items()
                if 'pp_lang' in request.args:
                    value = request.args['pp_lang']
                    item = ('pp_lang', value)
                    items.remove(item)
                    items.insert(0, item)
                for key, value in items:
                    obj, name = self.fieldId2obj(key)
                    if key in self.booleanFieldNames:
                        setattr(obj, name, value[0] == 'true')
                    else:
                        if key in self.imgFieldNames:
                            path = Path(toUnicode(value[0]))
                            if path.isfile():
                                setattr(obj, name, path)
                                data[key] = getattr(obj, name).basename()
                            else:
                                if getattr(obj, name):
                                    if getattr(obj, name).basename() != path:
                                        setattr(obj, name, None)
                        else:
                            #if name=='docType': common.setExportDocType(toUnicode(value[0]))

                            setattr(obj, name, toUnicode(value[0]))

        except Exception as e:
            log.exception(e)
            return json.dumps({'success': False, 'errorMessage': _("Failed to save properties")})

        if not self.package.isTemplate or not lang_only:
            self.package.isChanged = True

        return json.dumps({'success': True, 'data': data})
Beispiel #14
0
 def uploadNeededScripts(self):
     from exe import globals
     import os, sys
     scriptFileNames = ['jquery-ui-1.10.3.custom.min.js', 'memmatch-0.2.js']
     for scriptName in scriptFileNames:
         from exe import globals
         scriptSrcFilename = globals.application.config.webDir / "templates" / scriptName
         gameScriptFile = Path(scriptSrcFilename)
         if gameScriptFile.isfile():
             Resource(self, gameScriptFile)
Beispiel #15
0
 def uploadNeededScripts(self):
     from exe import globals
     import os,sys
     scriptFileNames = ['jquery-ui-1.10.3.custom.min.js', 'memmatch-0.2.js']
     for scriptName in scriptFileNames:
         from exe import globals 
         scriptSrcFilename = globals.application.config.webDir/"templates"/scriptName
         gameScriptFile = Path(scriptSrcFilename)
         if gameScriptFile.isfile():
             Resource(self, gameScriptFile)
Beispiel #16
0
 def uploadFile(self, filePath):
     """
     Store the upload files in the package
     Needs to be in a package to work.
     """
     if self.type == "descartes" and not filePath.endswith(".jar"):
         if filePath.find(",") == -1:
             global SCENE_NUM
             SCENE_NUM = 1
         else:
             SCENE_NUM = int(filePath[:filePath.find(",")])
     if self.type == "descartes" and (filePath.endswith(".htm")
                                      or filePath.endswith(".html")):
         global url
         url = filePath
         self.appletCode = self.getAppletcodeDescartes(filePath)
         # none scene was found:
         if self.appletCode == '':
             return None
     else:
         log.debug(u"uploadFile " + unicode(filePath))
         resourceFile = Path(filePath)
         assert self.parentNode, _('file %s has no parentNode') % self.id
         assert self.parentNode.package, \
                 _('iDevice %s has no package') % self.parentNode.id
         if resourceFile.isfile():
             self.message = ""
             Resource(self, resourceFile)
             if self.type == "geogebra":
                 self.appletCode = self.getAppletcodeGeogebra(
                     resourceFile.basename().replace(' ', '_').replace(
                         ')', '').replace('(', ''))
             if self.type == "jclic":
                 self.appletCode = self.getAppletcodeJClic(
                     resourceFile.basename().replace(' ', '_').replace(
                         ')', '').replace('(', ''))
             if self.type == "scratch":
                 self.appletCode = self.getAppletcodeScratch(
                     resourceFile.basename().replace(' ', '_').replace(
                         ')', '').replace('(', ''))
             if self.type == "descartes":
                 self.appletCode = self.getAppletcodeDescartes(
                     resourceFile.basename())
             ## next code should be used to load in the editor the HTML code of the html file:
             # if self.type == "other":
             #     if filePath.endswith(".html") or filePath.endswith(".htm"):
             #         content = open(filePath, 'r')
             #         str = content.read()
             #         self.appletCode = str
             #         content.close()
             #    else:
             #        log.error('File %s is not a HTML file' % resourceFile)
         else:
             log.error('File %s is not a file' % resourceFile)
Beispiel #17
0
 def handleTinyMCEimageChoice(self, client, tinyMCEwin, tinyMCEwin_name, \
                          tinyMCEfield, local_filename, preview_filename):
     """
     Once an image is selected in the file browser that is spawned by the 
     TinyMCE image dialog, copy this file (which is local to the user's 
     machine) into the server space, under a preview directory 
     (after checking if this exists, and creating it if necessary).
     Note that this IS a "cheat", in violation of the client-server 
     separation, but can be done since we know that the eXe server is 
     actually sitting on the client host.
     """
     server_filename = ""
     callback_errors = ""
     errors = 0
     webDir     = Path(self.config.webDir)
     previewDir  = webDir.joinpath('previews')
     if not previewDir.exists():
         log.debug("image previews directory does not yet exist; " \
                 + "creating as %s " % previewDir)
         previewDir.makedirs()
     elif not previewDir.isdir():
         client.alert( \
             _(u'Preview directory %s is a file, cannot replace it') \
             % previewDir)
         log.error("Couldn't preview tinyMCE-chosen image: "+
                   "Preview dir %s is a file, cannot replace it" \
                   % previewDir)
         callback_errors =  "Preview dir is a file, cannot replace"
         errors += 1
     if errors == 0:
         localImagePath = Path(local_filename)
         if not localImagePath.exists() or not localImagePath.isfile():
             client.alert( \
                  _(u'Image file %s is not found, cannot preview it') \
                  % localImagePath)
             log.error("Couldn't find tinyMCE-chosen image: %s" \
                     % localImagePath)
             callback_errors = "Image file %s not found, cannot preview" \
                     % localImagePath
             errors += 1
     try:
         server_filename = previewDir.joinpath(preview_filename);
         log.debug("handleTinyMCEimageChoice copying image from \'"\
                 + local_filename + "\' to \'" \
                 + server_filename.abspath().encode('utf-8') + "\'.");
         shutil.copyfile(local_filename, \
                 server_filename.abspath().encode('utf-8'));
     except Exception, e:
         client.alert(_('SAVE FAILED!\n%s' % str(e)))
         log.error("handleTinyMCEimageChoice unable to copy local image "\
                 +"file to server prevew, error = " + str(e))
         raise
Beispiel #18
0
    def addGameScript(self):
        from exe import globals
        import os,sys
            
        scriptSrcFilename = globals.application.config.webDir/"templates"/"hangman.js"
        log.debug("Script filename = " + scriptSrcFilename)
        
        #assert(self.parentNode,
        #       'Image '+self.id+' has no parentNode')
        #assert(self.parentNode.package,
        #       'iDevice '+self.parentNode.id+' has no package')

        gameScriptFile = Path(scriptSrcFilename)
        if gameScriptFile.isfile():
            Resource(self, gameScriptFile)
Beispiel #19
0
 def setFlash(self, flashPath):
     """
     Store the image in the package
     Needs to be in a package to work.
     """
     log.debug(u"setFlash " + unicode(flashPath))
     resourceFile = Path(flashPath)
     assert (self.idevice.parentNode, "Flash " + self.idevice.id + " has no parentNode")
     assert (self.idevice.parentNode.package, "iDevice " + self.idevice.parentNode.id + " has no package")
     if resourceFile.isfile():
         if self.flashResource:
             self.flashResource.delete()
         self.flashResource = Resource(self.idevice, resourceFile)
     else:
         log.error("File %s is not a file" % resourceFile)
Beispiel #20
0
    def addGameScript(self):
        from exe import globals
        import os, sys

        scriptSrcFilename = globals.application.config.webDir / "templates" / "hangman.js"
        log.debug("Script filename = " + scriptSrcFilename)

        # assert(self.parentNode,
        #       'Image '+self.id+' has no parentNode')
        # assert(self.parentNode.package,
        #       'iDevice '+self.parentNode.id+' has no package')

        gameScriptFile = Path(scriptSrcFilename)
        if gameScriptFile.isfile():
            Resource(self, gameScriptFile)
Beispiel #21
0
 def uploadFile(self, filePath):
     """
     Store the upload files in the package
     Needs to be in a package to work.
     """ 
     log.debug(u"uploadFile "+unicode(filePath))
     resourceFile = Path(filePath)
     assert(self.parentNode, _('file %s has no parentNode') % self.id)
     assert(self.parentNode.package, _('iDevice %s has no package') % self.parentNode.id)
     if resourceFile.isfile():
         self.message = ""
         Resource(self, resourceFile)
         if self.type == "geogebra":
             self.appletCode = self.getAppletcode(resourceFile.basename())
     else:
         log.error('File %s is not a file' % resourceFile)
Beispiel #22
0
 def uploadFile(self, filePath):
     """
     Store the upload files in the package
     Needs to be in a package to work.
     """ 
     log.debug(u"uploadFile "+unicode(filePath))
     resourceFile = Path(filePath)
     assert(self.parentNode,
            _('file %s has no parentNode') % self.id)
     assert(self.parentNode.package,
            _('iDevice %s has no package') % self.parentNode.id)
     if resourceFile.isfile():
         self.userResources += [ Resource(self.parentNode.package,
                                         resourceFile) ]
     else:
         log.error('File %s is not a file' % resourceFile)
Beispiel #23
0
 def setImage(self, imagePath):
     """
     Store the image in the package
     Needs to be in a package to work.
     """
     log.debug(u"setImage "+unicode(imagePath))
     resourceFile = Path(imagePath)
     assert(self.idevice.parentNode,
            'Image '+self.idevice.id+' has no parentNode')
     assert(self.idevice.parentNode.package,
            'iDevice '+self.idevice.parentNode.id+' has no package')
     if resourceFile.isfile():
         if self.imageResource:
             self.imageResource.delete()
         self.imageResource = Resource(self.idevice, resourceFile)
     else:
         log.error('File %s is not a file' % resourceFile)
Beispiel #24
0
 def uploadFile(self, filePath):
     """
     Store the upload files in the package
     Needs to be in a package to work.
     """ 
     if self.type == "descartes" and not filePath.endswith(".jar"):
         if filePath.find(",") == -1:
             global SCENE_NUM
             SCENE_NUM = 1
         else:
             SCENE_NUM = int(filePath[:filePath.find(",")])
     if self.type == "descartes" and (filePath.endswith(".htm") or filePath.endswith(".html")):
         global url
         url = filePath
         self.appletCode = self.getAppletcodeDescartes(filePath)
         # none scene was found:
         if self.appletCode == '':
             return None
     else:
         log.debug(u"uploadFile "+unicode(filePath))
         resourceFile = Path(filePath)
         assert self.parentNode, _('file %s has no parentNode') % self.id
         assert self.parentNode.package, \
                 _('iDevice %s has no package') % self.parentNode.id
         if resourceFile.isfile():
             self.message = ""
             Resource(self, resourceFile)
             if self.type == "geogebra":
                 self.appletCode = self.getAppletcodeGeogebra(resourceFile.basename().replace(' ','_').replace(')','').replace('(',''))
             if self.type == "jclic":
                 self.appletCode = self.getAppletcodeJClic(resourceFile.basename().replace(' ','_').replace(')','').replace('(',''))
             if self.type == "scratch":
                 self.appletCode = self.getAppletcodeScratch(resourceFile.basename().replace(' ','_').replace(')','').replace('(',''))
             if self.type == "descartes":
                 self.appletCode = self.getAppletcodeDescartes(resourceFile.basename())
             ## next code should be used to load in the editor the HTML code of the html file:
             # if self.type == "other":
             #     if filePath.endswith(".html") or filePath.endswith(".htm"):
             #         content = open(filePath, 'r')
             #         str = content.read()
             #         self.appletCode = str
             #         content.close()
             #    else:
             #        log.error('File %s is not a HTML file' % resourceFile)
         else:
             log.error('File %s is not a file' % resourceFile)
 def uploadFile(self, filePath):
     """
     Store the upload files in the package
     Needs to be in a package to work.
     """ 
     log.debug(u"uploadFile "+unicode(filePath))
     resourceFile = Path(filePath)
     assert(self.parentNode, _('file %s has no parentNode') % self.id)
     assert(self.parentNode.package, _('iDevice %s has no package') % self.parentNode.id)
     
     if resourceFile.isfile():
         self.message = ""
         Resource(self, resourceFile)
         if self.type == "geogebra":
             self.appletCode = self.getAppletcode(resourceFile.basename())
     else:
         log.error('File %s is not a file' % resourceFile)
Beispiel #26
0
 def setAttachment(self, attachmentPath):
     """
     Store the attachment in the package
     Needs to be in a package to work.
     """ 
     log.debug(u"setAttachment "+unicode(attachmentPath))
     resourceFile = Path(attachmentPath)
     assert(self.parentNode,
            _('Attachment %s has no parentNode') % self.id)
     assert(self.parentNode.package,
            _('iDevice %s has no package') % self.parentNode.id)
     if resourceFile.isfile():
         if self.userResources:
             while self.userResources:
                 self.userResources[0].delete()
         Resource(self, resourceFile)
     else:
         log.error('File %s is not a file' % resourceFile)
Beispiel #27
0
    def uploadFile(self, filePath):
        if self.fileResource is not None:
            self.fileResource.delete()

        finalName = str(filePath)
        if self.alwaysNameTo is not None:
            from os.path import dirname
            from shutil import copyfile
            dirName = dirname(filePath)
            finalName = dirName + "/" + self.alwaysNameTo
            copyfile(filePath, finalName)

        if self.fileDescription.content == "":
            self.fileDescription.content = os.path.basename(filePath)

        resourceFile = Path(finalName)
        if resourceFile.isfile():
            self.idevice.message = ""
            self.fileResource = Resource(self.idevice, resourceFile)
Beispiel #28
0
 def uploadFile(self, filePath):
     if self.fileResource is not None:
         self.fileResource.delete()
         
     finalName = str(filePath)
     if self.alwaysNameTo is not None:
         from os.path import dirname
         from shutil import copyfile
         dirName = dirname(filePath)
         finalName = dirName + "/" + self.alwaysNameTo
         copyfile(filePath, finalName)
     
     if self.fileDescription.content == "":
         self.fileDescription.content = os.path.basename(filePath)
         
     resourceFile = Path(finalName)
     if resourceFile.isfile():
         self.idevice.message = ""
         self.fileResource = Resource(self.idevice, resourceFile)
Beispiel #29
0
 def setFlash(self, flashPath):
     """
     Store the image in the package
     Needs to be in a package to work.
     """
     log.debug(u"setFlash "+unicode(flashPath))
     resourceFile = Path(flashPath)
     assert(self.idevice.parentNode,
            'Flash '+self.idevice.id+' has no parentNode')
     assert(self.idevice.parentNode.package,
            'iDevice '+self.idevice.parentNode.id+' has no package')
     if resourceFile.isfile():
         if self.flashResource:
             self.flashResource.delete()
             self.idevice.userResources.remove(self.flashResource)
         self.flashResource = Resource(self.idevice.parentNode.package,
                                       resourceFile)
         self.idevice.userResources.append(self.flashResource)
     else:
         log.error('File %s is not a file' % resourceFile)
Beispiel #30
0
    def setAttachment(self, attachmentPath):
        """
        Store the attachment in the package
        Needs to be in a package to work.
        """
        log.debug(u"setAttachment " + unicode(attachmentPath))
        resourceFile = Path(attachmentPath)

        assert self.parentNode, _("Attachment %s has no parentNode") % self.id
        assert self.parentNode.package, _("iDevice %s has no package") % self.parentNode.id

        if resourceFile.isfile():
            if self.userResources:
                # Clear out old attachment/s
                while self.userResources:
                    self.userResources[0].delete()
            # Create the new resource
            Resource(self, resourceFile)
        else:
            log.error("File %s is not a file" % resourceFile)
Beispiel #31
0
 def render_POST(self, request=None):
     log.debug("render_POST")
     
     data = {}
     try:
         for key, value in request.args.items():
             obj, name = self.fieldId2obj(key)
             if key in self.booleanFieldNames:
                 setattr(obj, name, value[0] == 'true')
             else:
                 if key in self.imgFieldNames:
                     path = Path(value[0])
                     if path.isfile():
                         setattr(obj, name, toUnicode(value[0]))
                         data[key] = getattr(obj, name).basename()
                 else:
                     setattr(obj, name, toUnicode(value[0]))
     except Exception as e:
         log.exception(e)
         return json.dumps({'success': False, 'errorMessage': _("Failed to save properties")})
     return json.dumps({'success': True, 'data': data})
Beispiel #32
0
 def setMedia(self, mediaPath):
     """
     Store the media file in the package
     Needs to be in a package to work.
     """
     log.debug(u"setMedia " + unicode(mediaPath))
     resourceFile = Path(mediaPath)
     assert (self.idevice.parentNode, "Media " + self.idevice.id + " has no parentNode")
     assert (self.idevice.parentNode.package, "iDevice " + self.idevice.parentNode.id + " has no package")
     if resourceFile.isfile():
         if self.mediaResource:
             self.mediaResource.delete()
         self.mediaResource = Resource(self.idevice, resourceFile)
         if "+" in self.mediaResource.storageName:
             path = self.mediaResource.path
             newPath = path.replace("+", "")
             Path(path).rename(newPath)
             self.mediaResource._storageName = self.mediaResource.storageName.replace("+", "")
             self.mediaResource._path = newPath
     else:
         log.error("File %s is not a file" % resourceFile)
Beispiel #33
0
 def setFlash(self, flashPath):
     """
     Store the image in the package
     Needs to be in a package to work.
     """
     log.debug(u"setFlash " + unicode(flashPath))
     resourceFile = Path(flashPath)
     assert (self.idevice.parentNode, "Flash " + self.idevice.id + " has no parentNode")
     assert (self.idevice.parentNode.package, "iDevice " + self.idevice.parentNode.id + " has no package")
     if resourceFile.isfile():
         if self.flashResource:
             self.flashResource.delete()
         try:
             flvDic = FLVReader(resourceFile)
             self.height = flvDic["height"] + 30
             self.width = flvDic["width"]
             self.flashResource = Resource(self.idevice, resourceFile)
         except AssertionError:
             log.error("File %s is not a flash movie" % resourceFile)
     else:
         log.error("File %s is not a file" % resourceFile)
Beispiel #34
0
    def setAttachment(self, attachmentPath):
        """
        Store the attachment in the package
        Needs to be in a package to work.
        """
        log.debug(u"setAttachment " + unicode(attachmentPath))
        resourceFile = Path(attachmentPath)

        assert self.parentNode, \
               _('Attachment %s has no parentNode') % self.id
        assert self.parentNode.package, \
               _('iDevice %s has no package') % self.parentNode.id

        if resourceFile.isfile():
            if self.userResources:
                # Clear out old attachment/s
                while self.userResources:
                    self.userResources[0].delete()
            # Create the new resource
            Resource(self, resourceFile)
        else:
            log.error('File %s is not a file' % resourceFile)
Beispiel #35
0
 def uploadFile(self, filePath):
     """
     Store the upload files in the package
     Needs to be in a package to work.
     """ 
     if self.type == "descartes" and not filePath.endswith(".jar"):
         if filePath.find(",") == -1:
             global SCENE_NUM
             SCENE_NUM = 1
         else:
             SCENE_NUM = int(filePath[:filePath.find(",")])
     if (filePath.endswith(".htm") or filePath.endswith(".html")):
         global url
         url = filePath
         self.appletCode = self.getAppletcodeDescartes(filePath)
         # none scene was found:
         if self.appletCode == '':
             return None
     else:
         log.debug(u"uploadFile "+unicode(filePath))
         resourceFile = Path(filePath)
         assert self.parentNode, _('file %s has no parentNode') % self.id
         assert self.parentNode.package, \
                 _('iDevice %s has no package') % self.parentNode.id
         if resourceFile.isfile():
             self.message = ""
             Resource(self, resourceFile)
             if self.type == "geogebra":
                 self.appletCode = self.getAppletcodeGeogebra(resourceFile.basename())
             if self.type == "jclic":
                 self.appletCode = self.getAppletcodeJClic(resourceFile.basename())
             if self.type == "scratch":
                 self.appletCode = self.getAppletcodeScratch(resourceFile.basename())
             if self.type == "descartes":
                 self.appletCode = self.getAppletcodeDescartes(resourceFile.basename())
         else:
             log.error('File %s is not a file' % resourceFile)
 def uploadFile(self, filePath):
     """
     Store the upload files in the package
     Needs to be in a package to work.
     """ 
     if self.type == "descartes" and not filePath.endswith(".jar"):
         if filePath.find(",") == -1:
             global SCENE_NUM
             SCENE_NUM = 1
         else:
             SCENE_NUM = int(filePath[:filePath.find(",")])
     if (filePath.endswith(".htm") or filePath.endswith(".html")):
         global url
         url = filePath
         self.appletCode = self.getAppletcodeDescartes(filePath)
         # none scene was found:
         if self.appletCode == '':
             return None
     else:
         log.debug(u"uploadFile "+unicode(filePath))
         resourceFile = Path(filePath)
         assert self.parentNode, _('file %s has no parentNode') % self.id
         assert self.parentNode.package, \
                 _('iDevice %s has no package') % self.parentNode.id
         if resourceFile.isfile():
             self.message = ""
             Resource(self, resourceFile)
             if self.type == "geogebra":
                 self.appletCode = self.getAppletcodeGeogebra(resourceFile.basename())
             if self.type == "jclic":
                 self.appletCode = self.getAppletcodeJClic(resourceFile.basename())
             if self.type == "scratch":
                 self.appletCode = self.getAppletcodeScratch(resourceFile.basename())
             if self.type == "descartes":
                 self.appletCode = self.getAppletcodeDescartes(resourceFile.basename())
         else:
             log.error('File %s is not a file' % resourceFile)
Beispiel #37
0
 def setMedia(self, mediaPath):
     """
     Store the media file in the package
     Needs to be in a package to work.
     """
     log.debug(u"setMedia "+unicode(mediaPath))
     resourceFile = Path(mediaPath)
     assert(self.idevice.parentNode,
            'Media '+self.idevice.id+' has no parentNode')
     assert(self.idevice.parentNode.package,
            'iDevice '+self.idevice.parentNode.id+' has no package')
     if resourceFile.isfile():
         if self.mediaResource:
             self.mediaResource.delete()
         self.mediaResource = Resource(self.idevice, resourceFile)
         if '+' in self.mediaResource.storageName:
             path = self.mediaResource.path
             newPath = path.replace('+','')
             Path(path).rename(newPath)
             self.mediaResource._storageName = \
                 self.mediaResource.storageName.replace('+','')
             self.mediaResource._path = newPath
     else:
         log.error('File %s is not a file' % resourceFile)
    def handleTinyMCEimageChoice(self, client, tinyMCEwin, tinyMCEwin_name, \
                             tinyMCEfield, local_filename, preview_filename):
        """
        Once an image is selected in the file browser that is spawned by the 
        TinyMCE image dialog, copy this file (which is local to the user's 
        machine) into the server space, under a preview directory 
        (after checking if this exists, and creating it if necessary).
        Note that this IS a "cheat", in violation of the client-server 
        separation, but can be done since we know that the eXe server is 
        actually sitting on the client host.
        """
        server_filename = ""
        callback_errors = ""
        errors = 0

        log.debug('handleTinyMCEimageChoice: image local = ' + local_filename +
                  ', base=' + os.path.basename(local_filename))

        webDir = Path(G.application.tempWebDir)
        previewDir = webDir.joinpath('previews')

        if not previewDir.exists():
            log.debug("image previews directory does not yet exist; " \
                    + "creating as %s " % previewDir)
            previewDir.makedirs()
        elif not previewDir.isdir():
            client.alert( \
                _(u'Preview directory %s is a file, cannot replace it') \
                % previewDir)
            log.error("Couldn't preview tinyMCE-chosen image: "+
                      "Preview dir %s is a file, cannot replace it" \
                      % previewDir)
            callback_errors = "Preview dir is a file, cannot replace"
            errors += 1

        if errors == 0:
            log.debug('handleTinyMCEimageChoice: originally, local_filename=' +
                      local_filename)
            local_filename = unicode(local_filename, 'utf-8')
            log.debug('handleTinyMCEimageChoice: in unicode, local_filename=' +
                      local_filename)

            localImagePath = Path(local_filename)
            log.debug(
                'handleTinyMCEimageChoice: after Path, localImagePath= ' +
                localImagePath)
            if not localImagePath.exists() or not localImagePath.isfile():
                client.alert( \
                     _(u'Local file %s is not found, cannot preview it') \
                     % localImagePath)
                log.error("Couldn't find tinyMCE-chosen image: %s" \
                        % localImagePath)
                callback_errors = "Image file %s not found, cannot preview" \
                        % localImagePath
                errors += 1

        try:
            # joinpath needs its join arguments to already be in Unicode:
            #preview_filename = toUnicode(preview_filename);
            # but that's okay, cuz preview_filename is now URI safe, right?
            log.debug('URIencoded preview filename=' + preview_filename)

            server_filename = previewDir.joinpath(preview_filename)
            log.debug("handleTinyMCEimageChoice copying image from \'"\
                    + local_filename + "\' to \'" \
                    + server_filename.abspath() + "\'.")
            shutil.copyfile(local_filename, \
                    server_filename.abspath())

            # new optional description file to provide the
            # actual base filename, such that once it is later processed
            # copied into the resources directory, it can be done with
            # only the basename.   Otherwise the resource filenames
            # are too long for some users, preventing them from making
            # backup CDs of the content, for example.
            #
            # Remember that the full path of the
            # file is only used here as an easy way to keep the names
            # unique WITHOUT requiring a roundtrip call from the Javascript
            # to this server, and back again, a process which does not
            # seem to work with tinyMCE in the mix.  BUT, once tinyMCE's
            # part is done, and this image processed, it can be returned
            # to just its basename, since the resource parts have their
            # own unique-ification mechanisms already in place.

            descrip_file_path = Path(server_filename + ".exe_info")
            log.debug("handleTinyMCEimageChoice creating preview " \
                    + "description file \'" \
                    + descrip_file_path.abspath() + "\'.")
            descrip_file = open(descrip_file_path, 'wb')

            # safety measures against TinyMCE, otherwise it will
            # later take ampersands and entity-escape them into '&',
            # and filenames with hash signs will not be found, etc.:
            unspaced_filename = local_filename.replace(' ', '_')
            unhashed_filename = unspaced_filename.replace('#', '_num_')
            unamped_local_filename = unhashed_filename.replace('&', '_and_')
            log.debug("and setting new file basename as: " +
                      unamped_local_filename)
            my_basename = os.path.basename(unamped_local_filename)
            descrip_file.write((u"basename=" + my_basename).encode('utf-8'))

            descrip_file.flush()
            descrip_file.close()

        except Exception, e:
            client.alert(_('SAVE FAILED!\n%s' % str(e)))
            log.error("handleTinyMCEimageChoice unable to copy local image "\
                    +"file to server prevew, error = " + str(e))
            raise
    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 ""
Beispiel #40
0
    def handleTinyMCEimageChoice(self, client, tinyMCEwin, tinyMCEwin_name, \
                             tinyMCEfield, local_filename, preview_filename):
        """
        Once an image is selected in the file browser that is spawned by the 
        TinyMCE image dialog, copy this file (which is local to the user's 
        machine) into the server space, under a preview directory 
        (after checking if this exists, and creating it if necessary).
        Note that this IS a "cheat", in violation of the client-server 
        separation, but can be done since we know that the eXe server is 
        actually sitting on the client host.
        """
        server_filename = ""
        callback_errors = ""
        errors = 0

        log.debug('handleTinyMCEimageChoice: image local = ' + local_filename 
                + ', base=' + os.path.basename(local_filename))

        webDir     = Path(G.application.tempWebDir)
        previewDir  = webDir.joinpath('previews')

        if not previewDir.exists():
            log.debug("image previews directory does not yet exist; " \
                    + "creating as %s " % previewDir)
            previewDir.makedirs()
        elif not previewDir.isdir():
            client.alert( \
                _(u'Preview directory %s is a file, cannot replace it') \
                % previewDir)
            log.error("Couldn't preview tinyMCE-chosen image: "+
                      "Preview dir %s is a file, cannot replace it" \
                      % previewDir)
            callback_errors =  "Preview dir is a file, cannot replace"
            errors += 1

        if errors == 0:
            log.debug('handleTinyMCEimageChoice: originally, local_filename='
                    + local_filename)
            local_filename = unicode(local_filename, 'utf-8')
            log.debug('handleTinyMCEimageChoice: in unicode, local_filename='
                    + local_filename)

            localImagePath = Path(local_filename)
            log.debug('handleTinyMCEimageChoice: after Path, localImagePath= '
                    + localImagePath);
            if not localImagePath.exists() or not localImagePath.isfile():
                client.alert( \
                     _(u'Local file %s is not found, cannot preview it') \
                     % localImagePath)
                log.error("Couldn't find tinyMCE-chosen image: %s" \
                        % localImagePath)
                callback_errors = "Image file %s not found, cannot preview" \
                        % localImagePath
                errors += 1

        try:
            # joinpath needs its join arguments to already be in Unicode:
            #preview_filename = toUnicode(preview_filename);
            # but that's okay, cuz preview_filename is now URI safe, right?
            log.debug('URIencoded preview filename=' + preview_filename);

            server_filename = previewDir.joinpath(preview_filename);
            log.debug("handleTinyMCEimageChoice copying image from \'"\
                    + local_filename + "\' to \'" \
                    + server_filename.abspath() + "\'.");
            shutil.copyfile(local_filename, \
                    server_filename.abspath());

            # new optional description file to provide the 
            # actual base filename, such that once it is later processed
            # copied into the resources directory, it can be done with
            # only the basename.   Otherwise the resource filenames
            # are too long for some users, preventing them from making
            # backup CDs of the content, for example.
            # 
            # Remember that the full path of the
            # file is only used here as an easy way to keep the names
            # unique WITHOUT requiring a roundtrip call from the Javascript
            # to this server, and back again, a process which does not
            # seem to work with tinyMCE in the mix.  BUT, once tinyMCE's
            # part is done, and this image processed, it can be returned
            # to just its basename, since the resource parts have their
            # own unique-ification mechanisms already in place.

            descrip_file_path = Path(server_filename+".exe_info")
            log.debug("handleTinyMCEimageChoice creating preview " \
                    + "description file \'" \
                    + descrip_file_path.abspath() + "\'.");
            descrip_file = open(descrip_file_path, 'wb')

            # safety measures against TinyMCE, otherwise it will 
            # later take ampersands and entity-escape them into '&',
            # and filenames with hash signs will not be found, etc.:
            unspaced_filename  = local_filename.replace(' ','_')
            unhashed_filename  = unspaced_filename.replace('#', '_num_')
            unamped_local_filename  = unhashed_filename.replace('&', '_and_')
            log.debug("and setting new file basename as: " 
                    + unamped_local_filename);
            my_basename = os.path.basename(unamped_local_filename)
            descrip_file.write((u"basename="+my_basename).encode('utf-8'))

            descrip_file.flush()
            descrip_file.close()

        except Exception, e:
            client.alert(_('SAVE FAILED!\n%s' % str(e)))
            log.error("handleTinyMCEimageChoice unable to copy local image "\
                    +"file to server prevew, error = " + str(e))
            raise
Beispiel #41
0
    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 testExport(self):
        # Delete the output dir
        outdir = TempDirPath()
        
        G.application = Application()
        
        G.application.loadConfiguration()
        G.application.preLaunch()
        
        # Load a package
        package = Package.load('testing/testPackage2.elp')
        # Do the export
        style_dir = G.application.config.stylesDir / package.style
        
        exporter = WebsiteExport(G.application.config,
                                 style_dir, 
                                 outdir)
        
        exporter.export(package)
        # Check that it all exists now
        assert outdir.isdir()
        assert (outdir / 'index.html').isfile()
        # Check that the style sheets have been copied
        for filename in style_dir.files():
            
            #Skip the styles config.xml - that should not be included
            if filename.basename() == "config.xml":
                continue
            
            assert ((outdir / filename.basename()).exists(),
                    'Style file "%s" not copied' % (outdir / filename.basename()))
            #check the modification time is correct
            f_dst = Path(outdir/filename.basename())
            f_src = Path(filename)
            
            self.assertTrue(
                TestUtils.mod_time_diff(f_dst, f_src) < 0.1,
                "Modification time in style dir preserved")

        for res_file in package.resourceDir.files():
            dst_file = Path(outdir/ res_file.basename())
            self.assertTrue(dst_file.isfile())
            
            self.assertTrue(
                TestUtils.mod_time_diff(res_file, dst_file) < 0.1,
                "Resource file %s has same mod time as origin" \
                % res_file.basename())

        #test that everything that was copied hahs the right mod time
        copy_list = package.make_system_copy_list(style_dir, 
                                  G.application.config.webDir/"scripts" , 
                                  G.application.config.webDir/"templates", 
                                  G.application.config.webDir/"images", 
                                  G.application.config.webDir/"css", 
                                  outdir)
        TestUtils.check_copy_list_mod_time(copy_list, self)

        # Check that each node in the package has had a page made
        pagenodes  = Set([p.node for p in exporter.pages])
        othernodes = Set(self._getNodes([], package.root))
        assert pagenodes == othernodes

        for page in exporter.pages:
            self._testPage(page, outdir)
Beispiel #43
0
    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 ""
Beispiel #44
0
 def handleTinyMCEimageChoice(
     self, client, tinyMCEwin, tinyMCEwin_name, tinyMCEfield, local_filename, preview_filename
 ):
     """
     Once an image is selected in the file browser that is spawned by the 
     TinyMCE image dialog, copy this file (which is local to the user's 
     machine) into the server space, under a preview directory 
     (after checking if this exists, and creating it if necessary).
     Note that this IS a "cheat", in violation of the client-server 
     separation, but can be done since we know that the eXe server is 
     actually sitting on the client host.
     """
     server_filename = ""
     callback_errors = ""
     errors = 0
     log.debug(
         "handleTinyMCEimageChoice: image local = " + local_filename + ", base=" + os.path.basename(local_filename)
     )
     webDir = Path(G.application.tempWebDir)
     previewDir = webDir.joinpath("previews")
     if not previewDir.exists():
         log.debug("image previews directory does not yet exist; " + "creating as %s " % previewDir)
         previewDir.makedirs()
     elif not previewDir.isdir():
         client.alert(_(u"Preview directory %s is a file, cannot replace it") % previewDir)
         log.error(
             "Couldn't preview tinyMCE-chosen image: " + "Preview dir %s is a file, cannot replace it" % previewDir
         )
         callback_errors = "Preview dir is a file, cannot replace"
         errors += 1
     if errors == 0:
         log.debug("handleTinyMCEimageChoice: originally, local_filename=" + local_filename)
         local_filename = unicode(local_filename, "utf-8")
         log.debug("handleTinyMCEimageChoice: in unicode, local_filename=" + local_filename)
         localImagePath = Path(local_filename)
         log.debug("handleTinyMCEimageChoice: after Path, localImagePath= " + localImagePath)
         if not localImagePath.exists() or not localImagePath.isfile():
             client.alert(_(u"Local file %s is not found, cannot preview it") % localImagePath)
             log.error("Couldn't find tinyMCE-chosen image: %s" % localImagePath)
             callback_errors = "Image file %s not found, cannot preview" % localImagePath
             errors += 1
     try:
         log.debug("URIencoded preview filename=" + preview_filename)
         server_filename = previewDir.joinpath(preview_filename)
         log.debug(
             "handleTinyMCEimageChoice copying image from '"
             + local_filename
             + "' to '"
             + server_filename.abspath()
             + "'."
         )
         shutil.copyfile(local_filename, server_filename.abspath())
         descrip_file_path = Path(server_filename + ".exe_info")
         log.debug(
             "handleTinyMCEimageChoice creating preview " + "description file '" + descrip_file_path.abspath() + "'."
         )
         descrip_file = open(descrip_file_path, "wb")
         unspaced_filename = local_filename.replace(" ", "_")
         unhashed_filename = unspaced_filename.replace("#", "_num_")
         unamped_local_filename = unhashed_filename.replace("&", "_and_")
         log.debug("and setting new file basename as: " + unamped_local_filename)
         my_basename = os.path.basename(unamped_local_filename)
         descrip_file.write((u"basename=" + my_basename).encode("utf-8"))
         descrip_file.flush()
         descrip_file.close()
     except Exception, e:
         client.alert(_("SAVE FAILED!\n%s" % str(e)))
         log.error(
             "handleTinyMCEimageChoice unable to copy local image " + "file to server prevew, error = " + str(e)
         )
         raise