Beispiel #1
0
def handle_workflow_change(object, event):
    settings = Settings(object)
    site = getPortal(object)
    gsettings = GlobalSettings(site)
    if not gsettings.storage_obfuscate or \
            settings.storage_type != 'File':
        return
    for perm in object.rolesOfPermission("View"):
        if perm['name'] == 'Anonymous' and perm["selected"] != "":
            # anon can now view, move it to normal
            storage_dir = storage_dir = storage.getResourceDirectory(
                gsettings=gsettings, settings=settings)
            secret_dir = os.path.join(storage_dir, settings.obfuscate_secret)
            if not os.path.exists(secret_dir):
                # already public, oops
                return
            for folder in os.listdir(secret_dir):
                path = os.path.join(secret_dir, folder)
                newpath = os.path.join(storage_dir, folder)
                shutil.move(path, newpath)
            shutil.rmtree(secret_dir)
            settings.obfuscated_filepath = False
            return
    # if we made it here, the item might have been switched back
    # to being unpublished. Let's just get the converter object
    # and re-move it
    converter = Converter(object)
    converter.handleFileObfuscation()
def handle_workflow_change(obj, event):
    settings = Settings(obj)
    site = getPortal(obj)
    gsettings = GlobalSettings(site)
    if not gsettings.storage_obfuscate or \
            settings.storage_type != 'File':
        return

    for perm in obj.rolesOfPermission("View"):
        if perm['name'] == 'Anonymous' and perm["selected"] != "":
            # anon can now view, move it to normal
            storage_dir = storage_dir = storage.getResourceDirectory(
                gsettings=gsettings, settings=settings)
            secret_dir = os.path.join(storage_dir,
                                      settings.obfuscate_secret)
            if not os.path.exists(secret_dir):
                # already public, oops
                return

            for folder in os.listdir(secret_dir):
                path = os.path.join(secret_dir, folder)
                newpath = os.path.join(storage_dir, folder)
                shutil.move(path, newpath)

            shutil.rmtree(secret_dir)
            settings.obfuscated_filepath = False
            return

    # if we made it here, the item might have been switched back
    # to being unpublished. Let's just get the converter object
    # and re-move it
    converter = Converter(object)
    converter.handleFileObfuscation()
def queueJob(obj):
    """
    queue a job async if available.
    otherwise, just run normal
    """
    async = asyncInstalled()
    converter = Converter(obj)
    #there is a bug if not shared blobs. I'm assuming that setup for worker is ok
    if not async:
        if not converter.can_convert:
            return
    if async:
        try:
            runner = JobRunner(obj)
            runner.set_quota()
            if runner.already_in_queue:
                logger.info('object %s already in queue for conversion' %
                            (repr(obj)))
            else:
                runner.queue_it()
            return
        except:
            logger.exception(
                "Error using plone.app.async with "
                "collective.documentviewer. Converting pdf without "
                "plone.app.async...")
            converter()
    else:
        converter()
def queueJob(object):
    """
    queue a job async if available.
    otherwise, just run normal
    """
    converter = Converter(object)
    if not converter.can_convert:
        return
    if asyncInstalled():
        try:
            runner = JobRunner(object)
            runner.set_quota()
            if runner.already_in_queue:
                logger.info('object %s already in queue for conversion' % (
                    repr(object)))
            else:
                runner.queue_it()
            return
        except:
            logger.exception("Error using plone.app.async with "
                "collective.documentviewer. Converting pdf without "
                "plone.app.async...")
            converter()
    else:
        converter()
Beispiel #5
0
 def test_sets_can_not_convert_after_conversion(self):
     fi = self.createFile('test.odp')
     gsettings = GlobalSettings(self.portal)
     gsettings.auto_select_layout = True
     gsettings.auto_layout_file_types = ['ppt']
     notify(ObjectInitializedEvent(fi))
     converter = Converter(fi)
     self.assertTrue(not converter.can_convert)
Beispiel #6
0
def queueJob(obj):
    converter = Converter(obj)
    if not converter.can_convert:
        return
    try:
        if celeryInstalled():
            celeryQueueJob(obj)
        else:
            converter(async=False)
    except QueueException:
        logger.exception(
            "Error using async with "
            "collective.documentviewer. Converting pdf without async...")
        converter()
Beispiel #7
0
def converter_call(self, *args, **kwargs):
    notify(ConversionStartedEvent(self.context))
    return Converter._old___call__(self, *args, **kwargs)
Beispiel #8
0
 def convertFileToPdf(self, repositoryitem, fileobj):
     """
     Convert a single file to document viewer using collective.documentviewer
     """
     
     # Check that docviewer is installed before processing
     if docViewerInstalled():
                 
         from collective.documentviewer.convert import Converter
         from collective.documentviewer.settings import GlobalSettings
         from zope.app.component.hooks import getSite
         from bungenicms.repository.browser.interfaces import IEnhancedDocumentViewerSchema
         
         context = repositoryitem
         filename = fileobj["filename"] 
         portal_url = getToolByName(context, "portal_url")() 
         isFileConverted = False
         
         # Where to put in the newly created objects
         # Get the settings from collective.documentviewer
         gsettings = GlobalSettings(getSite())
         gsettings.use_interface = IEnhancedDocumentViewerSchema
         storage_folder = gsettings.folder_location or CONVERTED_FILES_FOLDER # if empty
         plone_root = context.portal_url.getPortalObject()  
         
         container = None           
         if plone_root.hasObject(storage_folder):
             container = plone_root[storage_folder]
             print "files-folder exists. No need to create a new one."
         else:
             plone_root.invokeFactory("Folder", id=storage_folder, title="Files Folder")
             container = plone_root[storage_folder]
             print CONVERTED_FILES_FOLDER + " does NOT exist. Created a new one."
         
         # Make sure the folder is public/published
         try:
             folder_review_state = container.portal_workflow.getInfoFor(container, "review_state")
             if not folder_review_state == "published":
                 container.portal_workflow.doActionFor(container, "publish", comment="published")
         except:
             print "Could not publish: " + str(container.getId) + " already published?"            
         
         
         # Confirm whether the file has been converted using object UID
         uid = None
         for id, item in container.objectItems():
             if context.UID() == "FILE".join( item.UID().split( "FILE" )[0:1] ):
                 if filename.translate(None, " ?.!/\;:-{}[]()|~^`") == item.UID().split("FNIX",1)[1]:
                     print "A file with the same name already exists. No need to re-convert."
                     isFileConverted = True
                     uid = item.UID()
                     break
                     
         if not isFileConverted:
             # Grant user temp managerial permssions to allow doc conversion.                
             sm = getSecurityManager()
             if "Manager" not in sm.getUser().getRoles():
                 tmp_user = BaseUnrestrictedUser(
                     sm.getUser().getId(),"", ["Manager"],"")
                 newSecurityManager(None, tmp_user)                                  
             
                             
             # Set the file object attributes using the format below:
             
             # [parent_UID]FILE[object_uid]FNIX[file_name]
             
             # NOTE: The file-name generation mechanism used here is 
             # used in other parts of the application. Make sure to 
             # change those parts as well when you make change the following two lines.
             new_fname = filename.translate(None, " ?.!/\;:-{}[]()|~^`")
             uid = context.UID() + "FILE" + str(DateTime().millis()) + "FNIX" + new_fname
             
             # Try to create the file object
             container.invokeFactory("File", uid, icon=fileobj["icon"])
             obj_newObject = container[uid]
             obj_newObject._setUID( uid )
             obj_newObject.setTitle( fileobj["filename"])
             obj_newObject.setDescription("Description of file " + fileobj["filename"])
             obj_newObject.setFile( fileobj["file"])
             obj_newObject.setContentType( fileobj["content_type"])
             obj_newObject.reindexObject()
             
             # Convert the file
             converter = Converter( obj_newObject )
             converter()
             
             print "Done converting RepositoryItem File object."
         
         resultsurl = ("%s/%s/%s/view#document/p1") %(context.portal_url(), storage_folder, uid) 
         return resultsurl
     
     else:
         print "ERROR: collective.documentviewer is not installed. Unable to view file."
         
     return None