def launchBrowser(config, packageName): """ Launch the configured webbrowser for this platform """ url = u'%s/%s' % (G.application.exeAppUri, quote(packageName)) log.info(u"url " + url) dfbrw=mywebbrowser.get() withdefaultbrowser=True if config.browser!=None: try: config.browser = mywebbrowser.get(config.browser) if not config.browser.open(url): log.error("Unable to open defined browser: " + config.browser.name) withdefaultbrowser = True else: withdefaultbrowser = False except: browser_path = Path(config.browser) if browser_path.exists(): log.info(u"path browser " + browser_path.abspath()) mywebbrowser.register("custom-browser" , None, mywebbrowser.BackgroundBrowser(browser_path.abspath()), -1) config.browser = mywebbrowser.get("custom-browser") if not config.browser.open(url): log.error("Unable to open custom defined browser: " + browser_path.abspath()) withdefaultbrowser=True else: withdefaultbrowser=False if withdefaultbrowser: config.browser = dfbrw config.browser.open(url, new=0, autoraise=True) if hasattr(config.browser, "name"): log.info(u"Defined Browser: " + config.browser.name)
def render_POST(self, request): """ function replaced by nevow_clientToServerEvent to avoid POST message """ log.debug("render_POST " + repr(request.args)) data = {} try: locale = request.args["locale"][0] self.config.locale = locale self.config.locales[locale].install(unicode=True) self.config.configParser.set("user", "locale", locale) internalAnchors = request.args["internalAnchors"][0] self.config.internalAnchors = internalAnchors self.config.configParser.set("user", "internalAnchors", internalAnchors) editormodesel = request.args["editorMode"][0] self.config.editorMode = editormodesel self.config.configParser.set("user", "editorMode", editormodesel) theme = request.args["theme"][0] self.config.theme = theme self.config.configParser.set("user", "theme", theme) doctypesel = request.args["docType"][0] self.config.docType = doctypesel self.config.configParser.set("user", "docType", doctypesel) googleApiClientID = request.args["googleApiClientID"][0] self.config.googleApiClientID = googleApiClientID self.config.configParser.set("user", "googleApiClientID", googleApiClientID) defaultLicense = request.args["defaultLicense"][0] self.config.defaultLicense = defaultLicense self.config.configParser.set("user", "defaultLicense", defaultLicense) browser = request.args["browser"][0] if browser == "None": browser = None try: self.config.browser = mywebbrowser.get(browser) except Exception as e: browser_path = Path(browser) if browser_path.exists(): mywebbrowser.register( "custom-browser", None, mywebbrowser.BackgroundBrowser(browser_path.abspath()), -1 ) self.config.browser = mywebbrowser.get("custom-browser") else: raise e self.config.configParser.set("system", "browser", browser) showPreferencesOnStart = request.args["showPreferencesOnStart"][0] self.config.showPreferencesOnStart = showPreferencesOnStart self.config.configParser.set("user", "showPreferencesOnStart", showPreferencesOnStart) except Exception as e: log.exception(e) return json.dumps({"success": False, "errorMessage": _("Failed to save preferences")}) return json.dumps({"success": True, "data": data})
def render_POST(self, request): """ function replaced by nevow_clientToServerEvent to avoid POST message """ log.debug("render_POST " + repr(request.args)) data = {} try: locale = request.args['locale'][0] self.config.locale = locale self.config.locales[locale].install(unicode=True) self.config.configParser.set('user', 'locale', locale) internalAnchors = request.args['internalAnchors'][0] self.config.internalAnchors = internalAnchors self.config.configParser.set('user', 'internalAnchors', internalAnchors) editormodesel = request.args['editorMode'][0] self.config.editorMode = editormodesel self.config.configParser.set('user', 'editorMode', editormodesel) doctypesel = request.args['docType'][0] self.config.docType = doctypesel self.config.configParser.set('user', 'docType', doctypesel) defaultLicense = request.args['defaultLicense'][0] self.config.defaultLicense = defaultLicense self.config.configParser.set('user', 'defaultLicense', defaultLicense) browser = request.args['browser'][0] if browser == "None": browser = None try: self.config.browser = mywebbrowser.get(browser) except Exception as e: browser_path = Path(browser) if browser_path.exists(): mywebbrowser.register( 'custom-browser', None, mywebbrowser.BackgroundBrowser(browser_path.abspath()), -1) self.config.browser = mywebbrowser.get('custom-browser') else: raise e self.config.configParser.set('system', 'browser', browser) showPreferencesOnStart = request.args['showPreferencesOnStart'][0] self.config.showPreferencesOnStart = showPreferencesOnStart self.config.configParser.set('user', 'showPreferencesOnStart', showPreferencesOnStart) except Exception as e: log.exception(e) return json.dumps({ 'success': False, 'errorMessage': _("Failed to save preferences") }) return json.dumps({'success': True, 'data': data})
def render_POST(self, request): """ function replaced by nevow_clientToServerEvent to avoid POST message """ log.debug("render_POST " + repr(request.args)) data = {} try: locale = request.args['locale'][0] self.config.locale = locale self.config.locales[locale].install(unicode=True) self.config.configParser.set('user', 'locale', locale) internalAnchors = request.args['internalAnchors'][0] self.config.internalAnchors = internalAnchors self.config.configParser.set('user', 'internalAnchors', internalAnchors) editormodesel = request.args['editorMode'][0] self.config.editorMode = editormodesel self.config.configParser.set('user', 'editorMode', editormodesel) editorveresel = request.args['editorVersion'][0] self.config.editorVersion = editorveresel self.config.configParser.set('user', 'editorVersion', editorveresel) doctypesel = request.args['docType'][0] self.config.docType = doctypesel self.config.configParser.set('user', 'docType', doctypesel) defaultLicense = request.args['defaultLicense'][0] self.config.defaultLicense = defaultLicense self.config.configParser.set('user', 'defaultLicense', defaultLicense) browser = request.args['browser'][0] if browser == "None": browser = None try: self.config.browser = mywebbrowser.get(browser) except Exception as e: browser_path = Path(browser) if browser_path.exists(): mywebbrowser.register('custom-browser', None, mywebbrowser.BackgroundBrowser(browser_path.abspath()), -1) self.config.browser = mywebbrowser.get('custom-browser') else: raise e self.config.configParser.set('system', 'browser', browser) showPreferencesOnStart = request.args['showPreferencesOnStart'][0] self.config.showPreferencesOnStart = showPreferencesOnStart self.config.configParser.set('user', 'showPreferencesOnStart', showPreferencesOnStart) except Exception as e: log.exception(e) return json.dumps({'success': False, 'errorMessage': _("Failed to save preferences")}) return json.dumps({'success': True, 'data': data})
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 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 export(self, package): """ Export epub 3 package """ # First do the export to a temporary directory outputDir = TempDirPath() ''' fileDir = outputDir/"META-INF" fileDir.mkdir() fileDir = outputDir/"Content" fileDir.mkdir() ''' metainfPages = Path(outputDir.abspath() + '/META-INF') # metainfPages = outputDir/'META-INF' metainfPages.mkdir() contentPages = Path(outputDir.abspath() + '/EPUB') quizContentPages = Path(outputDir.abspath() + '/EPUB/tools/quiz') quizImagesPages = Path(quizContentPages.abspath() + '/images') quizScriptsPages = Path(quizContentPages.abspath() + '/scripts') quizVideoPages = Path(quizContentPages.abspath() + '/video') quizCssPages = Path(quizContentPages.abspath() + '/css') quizFilesPages = Path(quizContentPages.abspath() + '/css') # contentPages = outputDir/'Content' contentPages.mkdir() quizContentPages.makedirs() quizImagesPages.mkdir() quizScriptsPages.mkdir() quizVideoPages.mkdir() quizCssPages.mkdir() quizFilesPages.mkdir() # print contentPages.abspath() # print outputDir.abspath() # Export the package content self.pages = [Epub3Cover("cover", 1, package.root)] self.generatePages(package.root, 2) uniquifyNames(self.pages) cover = None for page in self.pages: page.save(contentPages) if hasattr(page, 'cover'): cover = page.cover # Create mimetype file mimetypeFile = open(outputDir.abspath() + '/mimetype', "w") mimetypeFile.write('application/epub+zip') mimetypeFile.close() # Copy the style sheet files to the output dir # But not nav.css cssStyleFiles = [self.styleDir / '..' / 'base.css'] cssStyleFiles += [f for f in self.styleDir.files("*.css") if f.basename() != "nav.css"] imgStyleFiles = [self.styleDir / '..' / 'popup_bg.gif'] imgStyleFiles += self.styleDir.files("*.jpg") imgStyleFiles += self.styleDir.files("*.gif") imgStyleFiles += self.styleDir.files("*.png") scriptStyleFiles = self.styleDir.files("*.js") filesStyleFiles = self.styleDir.files("*.html") filesStyleFiles += self.styleDir.files("*.ttf") filesStyleFiles += self.styleDir.files("*.eot") filesStyleFiles += self.styleDir.files("*.otf") filesStyleFiles += self.styleDir.files("*.woff") # FIXME for now, only copy files referenced in Common Cartridge # this really should apply to all exports, but without a manifest # of the files needed by an included stylesheet it is too restrictive package.resourceDir.copyfiles(contentPages) self.styleDir.copylist(cssStyleFiles, quizCssPages) self.styleDir.copylist(imgStyleFiles, quizImagesPages) self.styleDir.copylist(scriptStyleFiles, quizScriptsPages) self.styleDir.copylist(filesStyleFiles, quizFilesPages) self.scriptsDir.copylist(('common.js',), quizScriptsPages) # copy players for media idevices. hasFlowplayer = False hasMagnifier = False hasXspfplayer = False hasGallery = False hasFX = False hasSH = False hasGames = False hasWikipedia = False isBreak = False hasInstructions = False hasTooltips = False for page in self.pages: if isBreak: break for idevice in page.node.idevices: if (hasFlowplayer and hasMagnifier and hasXspfplayer and hasGallery and hasFX and hasSH and hasGames and hasWikipedia): isBreak = True break if not hasFlowplayer: if 'flowPlayer.swf' in idevice.systemResources: hasFlowplayer = True if not hasMagnifier: if 'mojomagnify.js' in idevice.systemResources: hasMagnifier = True if not hasXspfplayer: if 'xspf_player.swf' in idevice.systemResources: hasXspfplayer = True if not hasGallery: hasGallery = common.ideviceHasGallery(idevice) if not hasFX: hasFX = common.ideviceHasFX(idevice) if not hasSH: hasSH = common.ideviceHasSH(idevice) if not hasGames: hasGames = common.ideviceHasGames(idevice) if not hasWikipedia: if 'WikipediaIdevice' == idevice.klass: hasWikipedia = True if not hasInstructions: if 'TrueFalseIdevice' == idevice.klass or 'MultichoiceIdevice' == idevice.klass or 'VerdaderofalsofpdIdevice' == idevice.klass or 'EleccionmultiplefpdIdevice' == idevice.klass: hasInstructions = True if not hasTooltips: hasTooltips = common.ideviceHasTooltips(idevice) if hasFlowplayer: videofile = (self.templatesDir / 'flowPlayer.swf') videofile.copyfile(contentPages / 'flowPlayer.swf') controlsfile = (self.templatesDir / 'flowplayer.controls.swf') controlsfile.copyfile(contentPages / 'flowplayer.controls.swf') if hasMagnifier: videofile = (self.templatesDir / 'mojomagnify.js') videofile.copyfile(contentPages / 'mojomagnify.js') if hasXspfplayer: videofile = (self.templatesDir / 'xspf_player.swf') videofile.copyfile(contentPages / 'xspf_player.swf') if hasGallery: exeLightbox = (self.scriptsDir / 'exe_lightbox') exeLightbox.copyfiles(contentPages) if hasFX: exeEffects = (self.scriptsDir / 'exe_effects') exeEffects.copyfiles(contentPages) if hasSH: exeSH = (self.scriptsDir / 'exe_highlighter') exeSH.copyfiles(contentPages) if hasGames: exeGames = (self.scriptsDir / 'exe_games') exeGames.copyfiles(contentPages) if hasWikipedia: wikipediaCSS = (self.cssDir / 'exe_wikipedia.css') wikipediaCSS.copyfile(contentPages / 'exe_wikipedia.css') if hasInstructions: common.copyFileIfNotInStyle('panel-amusements.png', self, contentPages) common.copyFileIfNotInStyle('stock-stop.png', self, contentPages) if hasTooltips: exe_tooltips = (self.scriptsDir / 'exe_tooltips') exe_tooltips.copyfiles(contentPages) my_style = G.application.config.styleStore.getStyle(package.style) if my_style.hasValidConfig: if my_style.get_jquery() == True: jsFile = (self.scriptsDir / 'exe_jquery.js') jsFile.copyfile(contentPages / 'exe_jquery.js') else: jsFile = (self.scriptsDir / 'exe_jquery.js') jsFile.copyfile(contentPages / 'exe_jquery.js') # if hasattr(package, 'exportSource') and package.exportSource: # (G.application.config.webDir / 'templates' / 'content.xsd').copyfile(outputDir / 'content.xsd') # (outputDir / 'content.data').write_bytes(encodeObject(package)) # (outputDir / 'contentv3.xml').write_bytes(encodeObjectToXML(package)) if package.license == "license GFDL": # include a copy of the GNU Free Documentation Licence (self.templatesDir / 'fdl.html').copyfile(contentPages / 'fdl.html') # Create the nav.xhtml file container = NavEpub3(self.pages, contentPages) container.save() # Create the publication file publication = PublicationEpub3(self.config, contentPages, package, self.pages, cover) publication.save("package.opf") # Create the container file container = ContainerEpub3(metainfPages) container.save("container.xml") # Zip it up! self.filename.safeSave(self.doZip, _(u'EXPORT FAILED!\nLast succesful export is %s.'), outputDir) # Clean up the temporary dir outputDir.rmtree()
def export(self, package): """ Export epub 3 package """ # First do the export to a temporary directory outputDir = TempDirPath() ''' fileDir = outputDir/"META-INF" fileDir.mkdir() fileDir = outputDir/"Content" fileDir.mkdir() ''' metainfPages = Path(outputDir.abspath() + '/META-INF') # metainfPages = outputDir/'META-INF' metainfPages.mkdir() contentPages = Path(outputDir.abspath() + '/EPUB') quizContentPages = Path(outputDir.abspath() + '/EPUB/tools/quiz') quizImagesPages = Path(quizContentPages.abspath() + '/images') quizScriptsPages = Path(quizContentPages.abspath() + '/scripts') quizVideoPages = Path(quizContentPages.abspath() + '/video') quizCssPages = Path(quizContentPages.abspath() + '/css') quizFilesPages = Path(quizContentPages.abspath() + '/css') # contentPages = outputDir/'Content' contentPages.mkdir() quizContentPages.makedirs() quizImagesPages.mkdir() quizScriptsPages.mkdir() quizVideoPages.mkdir() quizCssPages.mkdir() quizFilesPages.mkdir() # print contentPages.abspath() # print outputDir.abspath() # Export the package content self.pages = [Epub3Cover("cover", 1, package.root)] self.generatePages(package.root, 2) uniquifyNames(self.pages) cover = None for page in self.pages: page.save(contentPages) if hasattr(page, 'cover'): cover = page.cover # Create mimetype file mimetypeFile = open(outputDir.abspath() + '/mimetype', "w") mimetypeFile.write('application/epub+zip') mimetypeFile.close() # Create lang file langFile = open(contentPages + '/common_i18n.js', "w") langFile.write(common.getJavaScriptStrings(False)) langFile.close() # Copy the style files to the output dir # But not nav.css filesStyleFiles = [self.styleDir / '..' / 'base.css'] filesStyleFiles += [f for f in self.styleDir.files("*.*") if f.basename() != "nav.css"] filesStyleFiles += [self.styleDir / '..' / 'popup_bg.gif'] # FIXME for now, only copy files referenced in Common Cartridge # this really should apply to all exports, but without a manifest # of the files needed by an included stylesheet it is too restrictive package.resourceDir.copyfiles(contentPages) self.styleDir.copylist(filesStyleFiles, quizFilesPages) self.scriptsDir.copylist(('common.js',), quizScriptsPages) # copy players for media idevices. hasFlowplayer = False hasMagnifier = False hasXspfplayer = False hasGallery = False hasFX = False hasSH = False hasGames = False hasWikipedia = False isBreak = False hasInstructions = False hasTooltips = False hasABCMusic = False for page in self.pages: if isBreak: break for idevice in page.node.idevices: if (hasFlowplayer and hasMagnifier and hasXspfplayer and hasGallery and hasFX and hasSH and hasGames and hasWikipedia and hasInstructions and hasTooltips and hasABCMusic): isBreak = True break if not hasFlowplayer: if 'flowPlayer.swf' in idevice.systemResources: hasFlowplayer = True if not hasMagnifier: if 'mojomagnify.js' in idevice.systemResources: hasMagnifier = True if not hasXspfplayer: if 'xspf_player.swf' in idevice.systemResources: hasXspfplayer = True if not hasGallery: hasGallery = common.ideviceHasGallery(idevice) if not hasFX: hasFX = common.ideviceHasFX(idevice) if not hasSH: hasSH = common.ideviceHasSH(idevice) if not hasGames: hasGames = common.ideviceHasGames(idevice) if not hasWikipedia: if 'WikipediaIdevice' == idevice.klass: hasWikipedia = True if not hasInstructions: if 'TrueFalseIdevice' == idevice.klass or 'MultichoiceIdevice' == idevice.klass or 'VerdaderofalsofpdIdevice' == idevice.klass or 'EleccionmultiplefpdIdevice' == idevice.klass: hasInstructions = True if not hasTooltips: hasTooltips = common.ideviceHasTooltips(idevice) if not hasABCMusic: hasABCMusic = common.ideviceHasABCMusic(idevice) if hasFlowplayer: videofile = (self.templatesDir / 'flowPlayer.swf') videofile.copyfile(contentPages / 'flowPlayer.swf') controlsfile = (self.templatesDir / 'flowplayer.controls.swf') controlsfile.copyfile(contentPages / 'flowplayer.controls.swf') if hasMagnifier: videofile = (self.templatesDir / 'mojomagnify.js') videofile.copyfile(contentPages / 'mojomagnify.js') if hasXspfplayer: videofile = (self.templatesDir / 'xspf_player.swf') videofile.copyfile(contentPages / 'xspf_player.swf') if hasGallery: exeLightbox = (self.scriptsDir / 'exe_lightbox') exeLightbox.copyfiles(contentPages) if hasFX: exeEffects = (self.scriptsDir / 'exe_effects') exeEffects.copyfiles(contentPages) if hasSH: exeSH = (self.scriptsDir / 'exe_highlighter') exeSH.copyfiles(contentPages) if hasGames: exeGames = (self.scriptsDir / 'exe_games') exeGames.copyfiles(contentPages) # Add game js string to common_i18n langGameFile = open(contentPages + '/common_i18n.js', "a") langGameFile.write(common.getGamesJavaScriptStrings(False)) langGameFile.close() if hasWikipedia: wikipediaCSS = (self.cssDir / 'exe_wikipedia.css') wikipediaCSS.copyfile(contentPages / 'exe_wikipedia.css') if hasInstructions: common.copyFileIfNotInStyle('panel-amusements.png', self, contentPages) common.copyFileIfNotInStyle('stock-stop.png', self, contentPages) if hasTooltips: exe_tooltips = (self.scriptsDir / 'exe_tooltips') exe_tooltips.copyfiles(contentPages) if hasABCMusic: pluginScripts = (self.scriptsDir/'tinymce_4/js/tinymce/plugins/abcmusic/export') pluginScripts.copyfiles(contentPages) my_style = G.application.config.styleStore.getStyle(package.style) if my_style.hasValidConfig: if my_style.get_jquery() == True: jsFile = (self.scriptsDir / 'exe_jquery.js') jsFile.copyfile(contentPages / 'exe_jquery.js') else: jsFile = (self.scriptsDir / 'exe_jquery.js') jsFile.copyfile(contentPages / 'exe_jquery.js') # if hasattr(package, 'exportSource') and package.exportSource: # (G.application.config.webDir / 'templates' / 'content.xsd').copyfile(outputDir / 'content.xsd') # (outputDir / 'content.data').write_bytes(encodeObject(package)) # (outputDir / 'contentv3.xml').write_bytes(encodeObjectToXML(package)) if package.license == "license GFDL": # include a copy of the GNU Free Documentation Licence (self.templatesDir / 'fdl.html').copyfile(contentPages / 'fdl.html') # Create the nav.xhtml file container = NavEpub3(self.pages, contentPages) container.save() # Create the publication file publication = PublicationEpub3(self.config, contentPages, package, self.pages, cover) publication.save("package.opf") # Create the container file container = ContainerEpub3(metainfPages) container.save("container.xml") # Zip it up! self.filename.safeSave(self.doZip, _(u'EXPORT FAILED!\nLast succesful export is %s.'), outputDir) # Clean up the temporary dir outputDir.rmtree()
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
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_POST(self, request): """ function replaced by nevow_clientToServerEvent to avoid POST message """ log.debug("render_POST " + repr(request.args)) data = {} try: locale = request.args['locale'][0] self.config.locale = locale # Change package lang too session = request.getSession() packagename = request.getPackageName() for name,package in session.packageStore.loaded.items(): if name == packagename: package.set_lang(locale) # self.config.locales[locale].install(unicode=True) self.config.configParser.set('user', 'locale', locale) internalAnchors = request.args['internalAnchors'][0] self.config.internalAnchors = internalAnchors self.config.configParser.set('user', 'internalAnchors', internalAnchors) editormodesel = request.args['editorMode'][0] self.config.editorMode = editormodesel self.config.configParser.set('user', 'editorMode', editormodesel) editorveresel = request.args['editorVersion'][0] self.config.editorVersion = editorveresel self.config.configParser.set('user', 'editorVersion', editorveresel) doctypesel = request.args['docType'][0] self.config.docType = doctypesel self.config.configParser.set('user', 'docType', doctypesel) defaultLicense = request.args['defaultLicense'][0] self.config.defaultLicense = defaultLicense self.config.configParser.set('user', 'defaultLicense', defaultLicense) forceEditableExport = request.args['forceEditableExport'][0] self.config.forceEditableExport = forceEditableExport self.config.configParser.set('user', 'forceEditableExport', forceEditableExport) cutFileName = request.args['cutFileName'][0] self.config.cutFileName = cutFileName self.config.configParser.set('user', 'cutFileName', cutFileName) autosaveTime = request.args['autosaveTime'][0] try: float(autosaveTime) except Exception: autosaveTime = '0' self.config.autosaveTime = autosaveTime self.config.configParser.set('user', 'autosaveTime', autosaveTime) browser = request.args['browser'][0] if browser == "None": browser = None try: self.config.browser = mywebbrowser.get(browser) except Exception as e: browser_path = Path(browser) if browser_path.exists(): mywebbrowser.register('custom-browser', None, mywebbrowser.BackgroundBrowser(browser_path.abspath()), -1) self.config.browser = mywebbrowser.get('custom-browser') else: raise e self.config.configParser.set('system', 'browser', browser) showPreferencesOnStart = request.args['showPreferencesOnStart'][0] self.config.showPreferencesOnStart = showPreferencesOnStart self.config.configParser.set('user', 'showPreferencesOnStart', showPreferencesOnStart) except Exception as e: log.exception(e) return json.dumps({'success': False, 'errorMessage': _("Failed to save preferences")}) return json.dumps({'success': True, 'data': data})
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 ""