Exemple #1
0
 def set_footerImg(self, value):
     """Set the footer image for this package"""
     if self._footerImg:
         self._footerImg.delete()
     if value:
         if value.startswith("file://"):
             value = value[7:]
         imgFile = Path(value)
         self._footerImg = Resource(self, Path(imgFile))
     else:
         self._footerImg = u''
Exemple #2
0
def exportWebSite2(request, client, filename, stylesDir):
    """Overwrite allowed, proceed"""
    try:
        filename = Path(filename)
        if filename.exists():
            if filename.isdir():
                shutil.rmtree(filename)
            else:
                os.remove(filename)
        filename.makedirs()
        websiteExport = WebsiteExport(self.config, stylesDir, filename)
        websiteExport.export(package)
        self._startFile(client, filename)
    except Exception, e:
        log.error("EXPORT FAILED! %s" % filename)
        raise
Exemple #3
0
def exportText(self, client, filename):
    try:
        filename = Path(filename)
        log.debug(u"exportWebsite, filename=%s" % filename)
        # Append an extension if required
        if not filename.lower().endswith(".txt"):
            filename += ".txt"
            if Path(filename).exists():
                msg = _(u'"%s" already exists.\nPlease try again with a different filename') % filename
                client.alert(_(u"EXPORT FAILED!\n%s" % msg))
                return
        # Do the export
        textExport = TextExport(filename)
        textExport.export(package)
    except Exception, e:
        client.alert(_("EXPORT FAILED!\n%s" % str(e)))
        raise
def exportPresentation(request, client, filename, stylesDir):
    """
    export client to a DOM presentation
    """

    try:
        # filename is a directory where we will export the website to
        # We assume that the user knows what they are doing
        # and don't check if the directory is already full or not
        # and we just overwrite what's already there
        filename = Path(filename)
        # Append the package name to the folder path if necessary
        if filename.basename() != package.name:
            filename /= package.name
        if not filename.exists():
            filename.makedirs()
        elif not filename.isdir():
            client.alert(
                _(u'Filename %s is a file, cannot replace it') % filename)
            log.error("Couldn't export web page: " +
                      "Filename %s is a file, cannot replace it" % filename)
            return
        else:
            client.alert(
                _(u'Folder name %s already exists. '
                  'Please choose another one or delete existing one then try again.'
                  ) % filename)
            return
        # Now do the export
        presentationExport = PresentationExport(self.config, stylesDir,
                                                filename)
        presentationExport.export(package)
    except Exception, e:
        client.alert(_('EXPORT FAILED!\n%s') % str(e))
        raise
def exportText(self, client, filename):
    try:
        filename = Path(filename)
        log.debug(u"exportWebsite, filename=%s" % filename)
        # Append an extension if required
        if not filename.lower().endswith('.txt'):
            filename += '.txt'
            if Path(filename).exists():
                msg = _(
                    u'"%s" already exists.\nPlease try again with a different filename'
                ) % filename
                client.alert(_(u'EXPORT FAILED!\n%s' % msg))
                return
        # Do the export
        textExport = TextExport(filename)
        textExport.export(package)
    except Exception, e:
        client.alert(_('EXPORT FAILED!\n%s' % str(e)))
        raise
Exemple #6
0
def exportWebSite(request, client, filename, stylesDir, quick=False):
    """
    Export 'client' to a web site,
    'webDir' is just read from config.webDir
    'stylesDir' is where to copy the style sheet information from
    """
    # filename is a directory where we will export the website to
    filename = Path(filename)
    # Append the package name to the folder path if necessary
    if filename.basename() != package.name:
        filename /= package.name

    if filename.exists() and not quick:
        client.sendScript(
            'askOverwrite("%s", "%s");' % (str(filename).replace("\\", "\\\\"), stylesDir.replace("\\", "\\\\"))
        )
    else:
        # Now do the export
        self.exportWebSite2(client, filename, stylesDir)
def exportWebSite(request, client, filename, stylesDir, quick=False):
    """
    Export 'client' to a web site,
    'webDir' is just read from config.webDir
    'stylesDir' is where to copy the style sheet information from
    """
    # filename is a directory where we will export the website to
    filename = Path(filename)
    # Append the package name to the folder path if necessary
    if filename.basename() != package.name:
        filename /= package.name

    if filename.exists() and not quick:
        client.sendScript('askOverwrite("%s", "%s");' \
                          % (str(filename).replace("\\", "\\\\"),
                             stylesDir.replace("\\", "\\\\")))
    else:
        # Now do the export
        self.exportWebSite2(client, filename, stylesDir)
def exportWebZip(request, client, filename, stylesDir):
    try:
        log.debug(u"exportWebsite, filename=%s" % filename)
        filename = Path(filename)
        # Do the export
        filename = self.b4save(client, filename, '.zip', _(u'EXPORT FAILED!'))
        websiteExport = WebsiteExport(self.config, stylesDir, filename)
        websiteExport.export(package)
    except Exception, e:
        client.alert(_('EXPORT FAILED!\n%s' % str(e)))
        raise
Exemple #9
0
def exportScorm(request, client, filename, stylesDir, scormType):
    """
    Exports this package to a scorm package file
    """
    try:
        filename = Path(filename)
        log.debug(u"exportScorm, filename=%s" % filename)
        # Append an extension if required
        if not filename.lower().endswith(".zip"):
            filename += ".zip"
            if Path(filename).exists():
                msg = _(u'"%s" already exists.\nPlease try again with a different filename') % filename
                client.alert(_(u"EXPORT FAILED!\n%s" % msg))
                return
        # Do the export
        scormExport = ScormExport(self.config, stylesDir, filename, scormType)
        scormExport.export(package)
    except Exception, e:
        client.alert(_("EXPORT FAILED!\n%s" % str(e)))
        raise
def extractPackage(request, package, filename, existOk):
    """
    Create a new package consisting of the current node and export
    'existOk' means the user has been informed of existance and ok'd it
    """
    filename = Path(filename)
    saveDir = filename.dirname()
    if saveDir and not saveDir.exists():
        client.alert(
            _(u'Cannot access directory named ') + unicode(saveDir) +
            _(u'. Please use ASCII names.'))
        return

    # Add the extension if its not already there
    if not filename.lower().endswith('.elp'):
        filename += '.elp'

    if Path(filename).exists() and existOk != 'true':
        msg = _(
            u'"%s" already exists.\nPlease try again with a different filename'
        ) % filename
        client.alert(_(u'EXTRACT FAILED!\n%s' % msg))
        return

    try:
        # Create a new package for the extracted nodes
        newPackage = package.extractNode()

        # trigger a rename of all of the internal nodes and links,
        # and to remove any old anchors from the dest package,
        # and remove any zombie links via isExtract:
        newNode = newPackage.root
        if newNode:
            newNode.RenamedNodePath(isExtract=True)

        # Save the new package
        newPackage.save(filename)
    except Exception, e:
        client.alert(_('EXTRACT FAILED!\n%s' % str(e)))
        raise
Exemple #11
0
def exportPresentation(request, client, filename, stylesDir):
    """
    export client to a DOM presentation
    """

    try:
        # filename is a directory where we will export the website to
        # We assume that the user knows what they are doing
        # and don't check if the directory is already full or not
        # and we just overwrite what's already there
        filename = Path(filename)
        # Append the package name to the folder path if necessary
        if filename.basename() != package.name:
            filename /= package.name
        if not filename.exists():
            filename.makedirs()
        elif not filename.isdir():
            client.alert(_(u"Filename %s is a file, cannot replace it") % filename)
            log.error("Couldn't export web page: " + "Filename %s is a file, cannot replace it" % filename)
            return
        else:
            client.alert(
                _(u"Folder name %s already exists. " "Please choose another one or delete existing one then try again.")
                % filename
            )
            return
        # Now do the export
        presentationExport = PresentationExport(self.config, stylesDir, filename)
        presentationExport.export(package)
    except Exception, e:
        client.alert(_("EXPORT FAILED!\n%s") % str(e))
        raise
def exportScorm(request, client, filename, stylesDir, scormType):
    """
    Exports this package to a scorm package file
    """
    try:
        filename = Path(filename)
        log.debug(u"exportScorm, filename=%s" % filename)
        # Append an extension if required
        if not filename.lower().endswith('.zip'):
            filename += '.zip'
            if Path(filename).exists():
                msg = _(
                    u'"%s" already exists.\nPlease try again with a different filename'
                ) % filename
                client.alert(_(u'EXPORT FAILED!\n%s' % msg))
                return
        # Do the export
        scormExport = ScormExport(self.config, stylesDir, filename, scormType)
        scormExport.export(package)
    except Exception, e:
        client.alert(_('EXPORT FAILED!\n%s' % str(e)))
        raise
Exemple #13
0
def extractPackage(request, package, filename, existOk):

    """
    Create a new package consisting of the current node and export
    'existOk' means the user has been informed of existance and ok'd it
    """
    filename = Path(filename)
    saveDir = filename.dirname()
    if saveDir and not saveDir.exists():
        client.alert(_(u"Cannot access directory named ") + unicode(saveDir) + _(u". Please use ASCII names."))
        return

    # Add the extension if its not already there
    if not filename.lower().endswith(".elp"):
        filename += ".elp"

    if Path(filename).exists() and existOk != "true":
        msg = _(u'"%s" already exists.\nPlease try again with a different filename') % filename
        client.alert(_(u"EXTRACT FAILED!\n%s" % msg))
        return

    try:
        # Create a new package for the extracted nodes
        newPackage = package.extractNode()

        # trigger a rename of all of the internal nodes and links,
        # and to remove any old anchors from the dest package,
        # and remove any zombie links via isExtract:
        newNode = newPackage.root
        if newNode:
            newNode.RenamedNodePath(isExtract=True)

        # Save the new package
        newPackage.save(filename)
    except Exception, e:
        client.alert(_("EXTRACT FAILED!\n%s" % str(e)))
        raise
Exemple #14
0
def loadCC(zippedFile, filename):
    """
    Load an IMS Common Cartridge or Content Package from filename
    """
    package = Package(Path(filename).namebase)
    xmldoc = minidom.parseString(zippedFile.read('imsmanifest.xml'))

    organizations_list = xmldoc.getElementsByTagName('organizations')
    level = 0
    # now a two-pass system to first unzip all applicable resources:
    for pass_num in range(2):
        for organizations in organizations_list:
            organization_list = organizations.getElementsByTagName(
                'organization')
            for organization in organization_list:
                for item in organization.childNodes:
                    if item.nodeName == 'item':
                        loadNode(pass_num, package.resourceDir, zippedFile,
                                 package.root, xmldoc, item, level)
    return package
Exemple #15
0
 def updateRecentDocuments(self, filename):
     """
     Updates the list of recent documents
     """
     # TODO Fix the function
     return 0
     # Don't update the list for the generic.data "package"
     genericData = G.application.config.configDir / 'idevices' / 'generic.data'
     if genericData.isfile() or genericData.islink():
         if Path(filename).samefile(genericData):
             return
     # Save in recentDocuments list
     recentProjects = G.application.config.recentProjects
     if filename in recentProjects:
         # If we're already number one, carry on
         if recentProjects[0] == filename:
             return
         recentProjects.remove(filename)
     recentProjects.insert(0, filename)
     del recentProjects[5:]  # Delete any older names from the list
     G.application.config.configParser.write()  # Save the settings
def exportWebSite2(request, client, filename, stylesDir):
    '''Overwrite allowed, proceed'''
    try:
        filename = Path(filename)
        if filename.exists():
            if filename.isdir():
                shutil.rmtree(filename)
            else:
                os.remove(filename)
        filename.makedirs()
        websiteExport = WebsiteExport(self.config, stylesDir, filename)
        websiteExport.export(package)
        self._startFile(client, filename)
    except Exception, e:
        log.error("EXPORT FAILED! %s" % filename)
        raise
def exportSinglePage(request, client, filename, webDir, stylesDir, \
                     printFlag):
    """
    Export 'client' to a single web page,
    'webDir' is just read from config.webDir
    'stylesDir' is where to copy the style sheet information from
    'printFlag' indicates whether or not this is for print 
                (and whatever else that might mean)
    """
    try:
        imagesDir = webDir.joinpath('images')
        scriptsDir = webDir.joinpath('scripts')
        templatesDir = webDir.joinpath('templates')
        # filename is a directory where we will export the website to
        # We assume that the user knows what they are doing
        # and don't check if the directory is already full or not
        # and we just overwrite what's already there
        filename = Path(filename)
        # Append the package name to the folder path if necessary
        if filename.basename() != package.name:
            filename /= package.name
        if not filename.exists():
            filename.makedirs()
        elif not filename.isdir():
            client.alert(
                _(u'Filename %s is a file, cannot replace it') % filename)
            log.error("Couldn't export web page: " +
                      "Filename %s is a file, cannot replace it" % filename)
            return
        else:
            client.alert(
                _(u'Folder name %s already exists. '
                  'Please choose another one or delete existing one then try again.'
                  ) % filename)
            return
        # Now do the export
        singlePageExport = SinglePageExport(stylesDir, filename, \
                                     imagesDir, scriptsDir, templatesDir)
        singlePageExport.export(package, printFlag)
    except Exception, e:
        client.alert(_('SAVE FAILED!\n%s' % str(e)))
        raise
Exemple #18
0
def exportSinglePage(request, client, filename, webDir, stylesDir, printFlag):
    """
    Export 'client' to a single web page,
    'webDir' is just read from config.webDir
    'stylesDir' is where to copy the style sheet information from
    'printFlag' indicates whether or not this is for print 
                (and whatever else that might mean)
    """
    try:
        imagesDir = webDir.joinpath("images")
        scriptsDir = webDir.joinpath("scripts")
        templatesDir = webDir.joinpath("templates")
        # filename is a directory where we will export the website to
        # We assume that the user knows what they are doing
        # and don't check if the directory is already full or not
        # and we just overwrite what's already there
        filename = Path(filename)
        # Append the package name to the folder path if necessary
        if filename.basename() != package.name:
            filename /= package.name
        if not filename.exists():
            filename.makedirs()
        elif not filename.isdir():
            client.alert(_(u"Filename %s is a file, cannot replace it") % filename)
            log.error("Couldn't export web page: " + "Filename %s is a file, cannot replace it" % filename)
            return
        else:
            client.alert(
                _(u"Folder name %s already exists. " "Please choose another one or delete existing one then try again.")
                % filename
            )
            return
        # Now do the export
        singlePageExport = SinglePageExport(stylesDir, filename, imagesDir, scriptsDir, templatesDir)
        singlePageExport.export(package, printFlag)
    except Exception, e:
        client.alert(_("SAVE FAILED!\n%s" % str(e)))
        raise
Exemple #19
0
    def load(filename, newLoad=True, destinationPackage=None):
        """
        Load package from disk, returns a package.
        """
        #if not zipfile.is_zipfile(filename):
        #    return None
        try:
            zippedFile = zipfile.ZipFile(filename, "r")
        except zipfile.BadZipFile:
            log.error("File %s is not a zip file" % file)
            return None

        try:
            # Get the jellied package data
            toDecode = zippedFile.read(u"content.data")
        except KeyError:
            log.info(
                "no content.data, trying Common Cartridge/Content Package")
            newPackage = loadCC(zippedFile, filename)
            newPackage.tempFile = False
            newPackage.isChanged = False
            newPackage.filename = Path(filename)

            return newPackage

        # Need to add a TempDirPath because it is a non-persistent member
        resourceDir = TempDirPath()

        # Extract resource files from package to temporary directory
        for fn in zippedFile.namelist():
            if unicode(fn, 'utf8') != u"content.data":
                outFile = open(resourceDir / fn, "wb")
                outFile.write(zippedFile.read(fn))
                outFile.flush()
                outFile.close()

        try:
            newPackage = decodeObjectRaw(toDecode)
            #            G.application.afterUpgradeHandlers = []
            newPackage.resourceDir = resourceDir
            #            G.application.afterUpgradeZombies2Delete = []

            if newLoad:
                # provide newPackage to doUpgrade's versionUpgrade() to
                # correct old corrupt extracted packages by setting the
                # any corrupt package references to the new package:

                log.debug("load() about to doUpgrade newPackage \"" +
                          newPackage._name + "\" " + repr(newPackage))
                if hasattr(newPackage, 'resourceDir'):
                    log.debug("newPackage resourceDir = " +
                              newPackage.resourceDir)
                else:
                    # even though it was just set above? should not get here:
                    log.error("newPackage resourceDir has NO resourceDir!")

#                doUpgrade(newPackage)

# after doUpgrade, compare the largest found field ID:
#                if G.application.maxFieldId >= Field.nextId:
#                    Field.nextId = G.application.maxFieldId + 1

            else:
                # and when merging, automatically set package references to
                # the destinationPackage, into which this is being merged:

                log.debug("load() about to merge doUpgrade newPackage \"" +
                          newPackage._name + "\" " + repr(newPackage) +
                          " INTO destinationPackage \"" +
                          destinationPackage._name + "\" " +
                          repr(destinationPackage))

                log.debug("using their resourceDirs:")
                if hasattr(newPackage, 'resourceDir'):
                    log.debug("   newPackage resourceDir = " +
                              newPackage.resourceDir)
                else:
                    log.error("newPackage has NO resourceDir!")
                if hasattr(destinationPackage, 'resourceDir'):
                    log.debug("   destinationPackage resourceDir = " +
                              destinationPackage.resourceDir)
                else:
                    log.error("destinationPackage has NO resourceDir!")

                doUpgrade(destinationPackage,
                          isMerge=True,
                          preMergePackage=newPackage)

                # after doUpgrade, compare the largest found field ID:
#                if G.application.maxFieldId >= Field.nextId:
#                    Field.nextId = G.application.maxFieldId + 1

        except:
            import traceback
            traceback.print_exc()
            raise

        if newPackage.tempFile:
            # newPackage.filename was stored as it's original filename
            newPackage.tempFile = False
        else:
            # newPackage.filename is the name that the package was last loaded from
            # or saved to
            newPackage.filename = Path(filename)

        # Let idevices and nodes handle any resource upgrading they may need to
        # Note: Package afterUpgradeHandlers *must* be done after Resources'
        # and the package should be updated before everything else,
        # so, prioritize with a 3-pass, 3-level calling setup
        # in order of: 1) resources, 2) package, 3) anything other objects

        newPackage.updateRecentDocuments(newPackage.filename)
        newPackage.isChanged = False
        return newPackage
def generateTinyMCEmath(request, package, tinyMCEwin, tinyMCEwin_name, \
                         tinyMCEfield, latex_source, math_fontsize, \
                         preview_image_filename, preview_math_srcfile):
    """
    Based off of handleTinyMCEimageChoice(), 
    handleTinyMCEmath() is similar in that it places a .gif math image 
    (and a corresponding .tex LaTeX source file) into the previews dir.
    Rather than copying the image from a user-selected directory, though,
    this routine actually generates the math image using mimetex.
    """
    server_filename = ""
    callback_errors = ""
    errors = 0

    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:
    #    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

    # the mimetex usage code was swiped from the Math iDevice:
    if latex_source <> "":

        # first write the latex_source out into the preview_math_srcfile,
        # such that it can then be passed into the compile command:
        math_filename = previewDir.joinpath(preview_math_srcfile)
        math_filename_str = math_filename.abspath().encode('utf-8')
        log.info("handleTinyMCEmath: using LaTeX source: " + latex_source)
        log.debug("writing LaTeX source into \'" \
                + math_filename_str + "\'.")
        math_file = open(math_filename, 'wb')
        # do we need to append a \n here?:
        math_file.write(latex_source)
        math_file.flush()
        math_file.close()

        try:
            use_latex_sourcefile = math_filename_str
            tempFileName = compile(use_latex_sourcefile, math_fontsize, \
                    latex_is_file=True)
        except Exception, e:
            client.alert(_('MimeTeX compile failed!\n%s' % str(e)))
            log.error("handleTinyMCEmath unable to compile LaTeX using "\
                +"mimetex, error = " + str(e))
            raise

        # copy the file into previews
        server_filename = previewDir.joinpath(preview_image_filename)
        log.debug("handleTinyMCEmath copying math image from \'"\
                + tempFileName + "\' to \'" \
                + server_filename.abspath().encode('utf-8') + "\'.")
        shutil.copyfile(tempFileName, \
                server_filename.abspath().encode('utf-8'))

        # Delete the temp file made by compile
        Path(tempFileName).remove()
Exemple #21
0
def generateTinyMCEmath(
    request,
    package,
    tinyMCEwin,
    tinyMCEwin_name,
    tinyMCEfield,
    latex_source,
    math_fontsize,
    preview_image_filename,
    preview_math_srcfile,
):

    """
    Based off of handleTinyMCEimageChoice(), 
    handleTinyMCEmath() is similar in that it places a .gif math image 
    (and a corresponding .tex LaTeX source file) into the previews dir.
    Rather than copying the image from a user-selected directory, though,
    this routine actually generates the math image using mimetex.
    """
    server_filename = ""
    callback_errors = ""
    errors = 0

    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:
    #    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

    # the mimetex usage code was swiped from the Math iDevice:
    if latex_source <> "":

        # first write the latex_source out into the preview_math_srcfile,
        # such that it can then be passed into the compile command:
        math_filename = previewDir.joinpath(preview_math_srcfile)
        math_filename_str = math_filename.abspath().encode("utf-8")
        log.info("handleTinyMCEmath: using LaTeX source: " + latex_source)
        log.debug("writing LaTeX source into '" + math_filename_str + "'.")
        math_file = open(math_filename, "wb")
        # do we need to append a \n here?:
        math_file.write(latex_source)
        math_file.flush()
        math_file.close()

        try:
            use_latex_sourcefile = math_filename_str
            tempFileName = compile(use_latex_sourcefile, math_fontsize, latex_is_file=True)
        except Exception, e:
            client.alert(_("MimeTeX compile failed!\n%s" % str(e)))
            log.error("handleTinyMCEmath unable to compile LaTeX using " + "mimetex, error = " + str(e))
            raise

        # copy the file into previews
        server_filename = previewDir.joinpath(preview_image_filename)
        log.debug(
            "handleTinyMCEmath copying math image from '"
            + tempFileName
            + "' to '"
            + server_filename.abspath().encode("utf-8")
            + "'."
        )
        shutil.copyfile(tempFileName, server_filename.abspath().encode("utf-8"))

        # Delete the temp file made by compile
        Path(tempFileName).remove()
Exemple #22
0
def exportPackage(request, package, exportType, filename, print_callback="", quick=False):

    """
    Called by js. 
    Exports the current package to one of the above formats
    'exportType' can be one of 'singlePage' 'webSite' 'zipFile' 'ipod'
                 'textFile' 'scorm' or 'presentation'
    'filename' is a file for scorm pages, and a directory for websites
    """
    G.application.lastExportType = exportType
    G.application.lastExportPath = filename
    client.sendScript('document.getElementById("quick-export")' + '.setAttribute("disabled", "false");')
    client.sendScript('document.getElementById("serving-elem")' + '.setAttribute("disabled", "false");')
    client.sendScript('document.getElementById("serving-elem")' + '.setAttribute("label", "Start Serving");')
    client.sendScript('document.getElementById("serving-elem")' + '.setAttribute("oncommand", "serveDocument\(\)");')
    client.sendScript('document.getElementById("quick-export").' + 'setAttribute("disabled", "false");')
    log.info("Filename to export" + filename)
    webDir = Path(self.config.webDir)
    if package.style.find("locale/") != -1:
        # local style loaded
        stylesDir = self.config.configDir / "style"
        # delete "locale/" from style name
        stylesDir /= package.style[package.style.find("locale/") + len("locale/") :]
    else:
        # global style
        stylesDir = webDir / "style"
        stylesDir /= package.style

    exportDir = Path(filename).dirname()
    if exportDir and not exportDir.exists():
        client.alert(_(u"Cannot access directory named ") + unicode(exportDir) + _(u". Please use ASCII names."))
        return

    """ 
    adding the print feature in using the same export functionality:
    """
    if exportType == "singlePage" or exportType == "printSinglePage":
        printit = 0
        if exportType == "printSinglePage":
            printit = 1
        exported_dir = self.exportSinglePage(client, filename, webDir, stylesDir, printit)
        # the above will return None if the desired exported directory
        # already exists (printing always goes to a new temp dir, though):
        if printit == 1 and not exported_dir is None:
            web_printdir = self.get_printdir_relative2web(exported_dir)
            # now that this has ben exported, go ahead and trigger
            # the requested printing callback:
            client.call(print_callback, filename, exported_dir, web_printdir)

    elif exportType == "webSite":
        self.exportWebSite(client, filename, stylesDir, quick=quick)

    elif exportType == "presentation":
        self.exportPresentation(client, filename, stylesDir)
    elif exportType == "printHandout":
        exported_dir = self.printHandout(client, filename, stylesDir)
        print exported_dir
        web_printdir = self.get_printdir_relative2web(exported_dir)
        client.call(print_callback, filename, exported_dir, web_printdir)

    elif exportType == "zipFile":
        filename = self.b4save(client, filename, ".zip", _(u"EXPORT FAILED!"))
        self.exportWebZip(client, filename, stylesDir)
    elif exportType == "textFile":
        self.exportText(client, filename)
    elif exportType == "ipod":
        self.exportIpod(client, filename)
    elif exportType == "scorm":
        filename = self.b4save(client, filename, ".zip", _(u"EXPORT FAILED!"))
        self.exportScorm(client, filename, stylesDir, "scorm1.2")
    elif exportType == "scorm2004":
        filename = self.b4save(client, filename, ".zip", _(u"EXPORT FAILED!"))
        self.exportScorm(client, filename, stylesDir, "scorm2004")
    elif exportType == "commoncartridge":
        filename = self.b4save(client, filename, ".zip", _(u"EXPORT FAILED!"))
        self.exportScorm(client, filename, stylesDir, "commoncartridge")
    else:
        filename = self.b4save(client, filename, ".zip", _(u"EXPORT FAILED!"))
        self.exportIMS(client, filename, stylesDir)
Exemple #23
0
def previewTinyMCEimage(request, package, 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 '&amp;',
        # 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 previewTinyMCEimage(request, package, 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 '&amp;',
        # 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 exportPackage(request,
                  package,
                  exportType,
                  filename,
                  print_callback='',
                  quick=False):
    """
    Called by js. 
    Exports the current package to one of the above formats
    'exportType' can be one of 'singlePage' 'webSite' 'zipFile' 'ipod'
                 'textFile' 'scorm' or 'presentation'
    'filename' is a file for scorm pages, and a directory for websites
    """
    G.application.lastExportType = exportType
    G.application.lastExportPath = filename
    client.sendScript('document.getElementById("quick-export")' + \
                      '.setAttribute("disabled", "false");')
    client.sendScript('document.getElementById("serving-elem")' + \
                      '.setAttribute("disabled", "false");')
    client.sendScript('document.getElementById("serving-elem")' + \
                      '.setAttribute("label", "Start Serving");')
    client.sendScript('document.getElementById("serving-elem")' + \
                    '.setAttribute("oncommand", "serveDocument\(\)");')
    client.sendScript('document.getElementById("quick-export").' +\
                      'setAttribute("disabled", "false");')
    log.info("Filename to export" + filename)
    webDir = Path(self.config.webDir)
    if package.style.find("locale/") != -1:
        # local style loaded
        stylesDir = self.config.configDir / "style"
        # delete "locale/" from style name
        stylesDir /= package.style[package.style.find\
                                        ("locale/") + len("locale/"):]
    else:
        # global style
        stylesDir = webDir / "style"
        stylesDir /= package.style

    exportDir = Path(filename).dirname()
    if exportDir and not exportDir.exists():
        client.alert(
            _(u'Cannot access directory named ') + unicode(exportDir) +
            _(u'. Please use ASCII names.'))
        return
    """ 
    adding the print feature in using the same export functionality:
    """
    if exportType == 'singlePage' or exportType == 'printSinglePage':
        printit = 0
        if exportType == 'printSinglePage':
            printit = 1
        exported_dir = self.exportSinglePage(client, filename, webDir, \
                                             stylesDir, printit)
        # the above will return None if the desired exported directory
        # already exists (printing always goes to a new temp dir, though):
        if printit == 1 and not exported_dir is None:
            web_printdir = self.get_printdir_relative2web(exported_dir)
            # now that this has ben exported, go ahead and trigger
            # the requested printing callback:
            client.call(print_callback, filename, exported_dir, \
                        web_printdir)

    elif exportType == 'webSite':
        self.exportWebSite(client, filename, stylesDir, quick=quick)

    elif exportType == 'presentation':
        self.exportPresentation(client, filename, stylesDir)
    elif exportType == 'printHandout':
        exported_dir = self.printHandout(client, filename, stylesDir)
        print exported_dir
        web_printdir = self.get_printdir_relative2web(exported_dir)
        client.call(print_callback, filename, exported_dir, web_printdir)

    elif exportType == 'zipFile':
        filename = self.b4save(client, filename, '.zip', _(u'EXPORT FAILED!'))
        self.exportWebZip(client, filename, stylesDir)
    elif exportType == 'textFile':
        self.exportText(client, filename)
    elif exportType == 'ipod':
        self.exportIpod(client, filename)
    elif exportType == "scorm":
        filename = self.b4save(client, filename, '.zip', _(u'EXPORT FAILED!'))
        self.exportScorm(client, filename, stylesDir, "scorm1.2")
    elif exportType == "scorm2004":
        filename = self.b4save(client, filename, '.zip', _(u'EXPORT FAILED!'))
        self.exportScorm(client, filename, stylesDir, "scorm2004")
    elif exportType == "commoncartridge":
        filename = self.b4save(client, filename, '.zip', _(u'EXPORT FAILED!'))
        self.exportScorm(client, filename, stylesDir, "commoncartridge")
    else:
        filename = self.b4save(client, filename, '.zip', _(u'EXPORT FAILED!'))
        self.exportIMS(client, filename, stylesDir)