コード例 #1
0
    def __call__(self, no_response=False, msg=None, *args, **kwargs):
        """
        This is a copy from the orginal publisher.publish view for
        PloneFormGen.
        it also publishs all its contents
        """
        self.logger = getLogger()

        # get username
        user = self.context.portal_membership.getAuthenticatedMember()
        username = user.getUserName()
        # create Job
        queue = Queue(self.context)
        queue.createJob("push", self.context, username)
        self.logger.info(
            'Created "%s" Job for "%s" at %s' % ("push", self.context.Title(), "/".join(self.context.getPhysicalPath()))
        )

        # Get all items recursively and add theme to the queue
        def add_item_to_queue(items):
            for item in items:
                queue.createJob("push", item, username)
                subitems = item.objectValues()
                if subitems:
                    add_item_to_queue(subitems)

        add_item_to_queue(self.context.objectValues())

        # status message
        if msg is None:
            msg = _(u"This object has been added to the queue.")
        IStatusMessage(self.request).addStatusMessage(msg, type="info")
        if not no_response:
            return self.request.RESPONSE.redirect("./view")
コード例 #2
0
    def __call__(self):
        logger = getLogger()

        action = self.request.form['action']
        filepath = self.request.form['filepath']
        path = self.request.form['path']
        additional_data = encode_after_json(
            json.loads(self.request.form['additional_data']))
        obj = api.portal.get().unrestrictedTraverse(path, None)
        require_token = self.request.form['token']
        attempt = self.request.form['attempt']

        if obj is None:
            if attempt < MAX_ATTEMPTS:
                sleep(TIMEOUT_BETWEEN_ATTEMPTS)
                return enqueue_deferred_extraction(None,
                                                   action,
                                                   filepath,
                                                   additional_data,
                                                   attempt=attempt + 1,
                                                   token=require_token,
                                                   path=path)
            else:
                os.remove(filepath)
                logger.warning(
                    'Removed "{0}", since the destination {1} no longer '
                    'exists.'.format(filepath, path))
                return 'JSON File "{0}" removed'.format(filepath)

        current_token = IAnnotations(obj).get(TOKEN_ANNOTATION_KEY, None)

        if current_token != require_token:
            # The current version of the object is not the version we have
            # planned to extract.
            if attempt < MAX_ATTEMPTS:
                # Lets retry for solving the problem that the worker is too
                # early and the transaction which triggered the action was not
                # yet commited to the database.
                sleep(TIMEOUT_BETWEEN_ATTEMPTS)
                return enqueue_deferred_extraction(obj,
                                                   action,
                                                   filepath,
                                                   additional_data,
                                                   attempt=attempt + 1,
                                                   token=require_token)

            else:
                raise Exception(
                    'Unexpected object version' +
                    ' after {!r} attempts.'.format(attempt) +
                    ' Required token: {!r},'.format(require_token) +
                    ' got token: {!r}'.format(current_token))

        extractor = Extractor()
        data = extractor(obj, action, additional_data)

        with open(filepath, 'w') as target:
            target.write(data)

        return 'OK'
コード例 #3
0
    def __call__(self, event, no_response=False, msg=None):
        if IPreventPublishing.providedBy(self.context):
            return 'prevented'

        if publisher_jobs_are_disabled():
            return 'disabled'

        self.logger = getLogger()
        # is the object blacklisted?
        if IPathBlacklist(self.context).is_blacklisted():
            self.logger.warning(
                'Could not create move job for blacklisted object (%s at %s)' %
                (self.context.Title(), '/'.join(
                    self.context.getPhysicalPath())))
            if not no_response:
                return self.request.RESPONSE.redirect('./view')
            return False

        # This View should not be executed at the PloneSiteRoot
        if IPloneSiteRoot.providedBy(self.context):
            raise Exception('Not allowed on PloneSiteRoot')

        # get username
        user = self.context.portal_membership.getAuthenticatedMember()
        username = user.getUserName()

        # create Job
        portal = self.context.portal_url.getPortalObject()
        queue = IQueue(portal)

        additional_data = {
            'move_data': {
                'newName': event.newName,
                'newParent': get_site_relative_path(event.newParent),
                'newTitle': event.object.Title().decode('utf-8'),
                'oldName': event.oldName,
                'oldParent': get_site_relative_path(event.oldParent),
            }
        }

        queue.createJob('move',
                        self.context,
                        username,
                        additional_data=additional_data)
        self.logger.debug('Created "%s" Job for "%s" at %s' % (
            'move',
            self.context.Title(),
            '/'.join(self.context.getPhysicalPath()),
        ))

        # status message
        if msg is None:
            msg = _(u'Object move/rename action has been added to the queue.')

        IStatusMessage(self.request).addStatusMessage(msg, type='info')
        if not no_response:
            return self.request.RESPONSE.redirect('./view')
コード例 #4
0
    def __call__(self):
        """
        Handles logging purposes and calls execute() method.
        """

        # get config and queue
        self.config = IConfig(self.context)
        portal = self.context.portal_url.getPortalObject()
        self.queue = IQueue(portal)
        event.notify(BeforeQueueExecutionEvent(portal, self.queue))
        # prepare logger
        self.logger = getLogger()
        self.error_logger = getErrorLogger()
        # is it allowed to publish?
        if not self.config.publishing_enabled():
            self.logger.warning('PUBLISHING IS DISABLED')
            return 'PUBLISHING IS DISABLED'

        if self.config.locking_enabled():
            self.logger.info('LOCKING IS ENABLED')
        else:
            self.logger.info('LOCKING IS DISABLED')

        # lock - check for locking flag
        if self.config.locking_enabled(
        ) and not self.get_lock_object().acquire(0):
            self.logger.warning('Already publishing')
            return 'Already publishing'

        # register our own logging handler for returning logs afterwards
        logStream = StringIO()
        logHandler = logging.StreamHandler(logStream)
        self.logger.addHandler(logHandler)
        # be sure to remove the handler!
        try:
            # execute queue
            self.execute()
        except Exception:
            self.logger.removeHandler(logHandler)
            if self.config.locking_enabled():
                self.get_lock_object().release()
            # re-raise exception
            raise
        # get logs
        self.logger.removeHandler(logHandler)
        logStream.seek(0)
        log = logStream.read()
        del logStream
        del logHandler

        # unlock
        if self.config.locking_enabled():
            self.get_lock_object().release()

        event.notify(QueueExecutedEvent(portal, log))
        return log
コード例 #5
0
    def __call__(self):
        logger = getLogger()

        action = self.request.form['action']
        filepath = self.request.form['filepath']
        path = self.request.form['path']
        additional_data = encode_after_json(json.loads(self.request.form['additional_data']))
        obj = api.portal.get().unrestrictedTraverse(path, None)
        require_token = self.request.form['token']
        attempt = self.request.form['attempt']

        if obj is None:
            if attempt < MAX_ATTEMPTS:
                sleep(TIMEOUT_BETWEEN_ATTEMPTS)
                return enqueue_deferred_extraction(
                    None, action, filepath, additional_data,
                    attempt=attempt + 1,
                    token=require_token,
                    path=path)
            else:
                os.remove(filepath)
                logger.warning(
                    'Removed "{0}", since the destination {1} no longer '
                    'exists.'.format(filepath, path))
                return 'JSON File "{0}" removed'.format(filepath)

        current_token = IAnnotations(obj).get(TOKEN_ANNOTATION_KEY, None)

        if current_token != require_token:
            # The current version of the object is not the version we have
            # planned to extract.
            if attempt < MAX_ATTEMPTS:
                # Lets retry for solving the problem that the worker is too
                # early and the transaction which triggered the action was not
                # yet commited to the database.
                sleep(TIMEOUT_BETWEEN_ATTEMPTS)
                return enqueue_deferred_extraction(
                    obj, action, filepath, additional_data,
                    attempt=attempt + 1,
                    token=require_token)

            else:
                raise Exception(
                    'Unexpected object version' +
                    ' after {!r} attempts.'.format(attempt) +
                    ' Required token: {!r},'.format(require_token) +
                    ' got token: {!r}'.format(current_token))

        extractor = Extractor()
        data = extractor(obj, action, additional_data)

        with open(filepath, 'w') as target:
            target.write(data)

        return 'OK'
コード例 #6
0
    def __call__(self, no_response=False, msg=None, *args, **kwargs):
        """
        The __call__ method is used to execute the BrowserView. It creates and
        adds a "PUSH"-Job on the current context to the queue.
        @param args:    list of unnamed arguments
        @type args:     list
        @param kwargs:  dict of named keyword-arguments
        @type kwargs:   dict
        @return:        Redirect to object`s default view
        """

        if IPreventPublishing.providedBy(self.context):
            return 'prevented'

        if publisher_jobs_are_disabled():
            return 'disabled'

        self.logger = getLogger()
        # is the object blacklisted?
        if IPathBlacklist(self.context).is_blacklisted():
            self.logger.warning('Could not create push job for blacklisted '+\
                                    'object (%s at %s)' % (
                    self.context.Title(),
                    '/'.join(self.context.getPhysicalPath())))
            if not no_response:
                return self.request.RESPONSE.redirect('./view')
            return False

        # mle: now its possible to execite this view on plonesiteroot
        # This View should not be executed at the PloneSiteRoot
        #if IPloneSiteRoot.providedBy(self.context):
        #    raise Exception('Not allowed on PloneSiteRoot')
        # get username
        user = self.context.portal_membership.getAuthenticatedMember()
        username = user.getUserName()
        # create Job
        portal = self.context.portal_url.getPortalObject()
        queue = IQueue(portal)
        queue.createJob('push', self.context, username)
        self.logger.debug('Created "%s" Job for "%s" at %s' % (
                'push',
                self.context.Title(),
                '/'.join(self.context.getPhysicalPath()),
                ))

        # status message
        if msg is None:
            msg = _(u'This object has been added to the queue.')
        IStatusMessage(self.request).addStatusMessage(
            msg,
            type='info'
            )
        if not no_response:
            return self.request.RESPONSE.redirect('./view')
コード例 #7
0
    def __init__(self, context):
        """
        Constructor: load the annotations, which are stored on the
        plone site.

        @param context:     any context
        @type context:      Plone object
        """
        self.context = aq_inner(context.portal_url.getPortalObject())
        self.annotations = IAnnotations(self.context)
        self.logger = getLogger()
コード例 #8
0
    def __init__(self, context):
        """
        Constructor: load the annotations, which are stored on the
        plone site.

        @param context:     any context
        @type context:      Plone object
        """
        self.context = aq_inner(context.portal_url.getPortalObject())
        self.annotations = IAnnotations(self.context)
        self.logger = getLogger()
コード例 #9
0
    def __call__(self):
        """
        Handles logging purposes and calls execute() method.
        """

        # get config and queue
        self.config = IConfig(self.context)
        portal = self.context.portal_url.getPortalObject()
        self.queue = IQueue(portal)
        event.notify(BeforeQueueExecutionEvent(portal, self.queue))
        # prepare logger
        self.logger = getLogger()
        self.error_logger = getErrorLogger()
        # is it allowed to publish?
        if not self.config.publishing_enabled():
            self.logger.warning('PUBLISHING IS DISABLED')
            return 'PUBLISHING IS DISABLED'

        if self.config.locking_enabled():
            self.logger.info('LOCKING IS ENABLED')
        else:
            self.logger.info('LOCKING IS DISABLED')

        # lock - check for locking flag
        if self.config.locking_enabled() and not self.get_lock_object().acquire(0):
            self.logger.warning('Already publishing')
            return 'Already publishing'

        # register our own logging handler for returning logs afterwards
        logStream = StringIO()
        logHandler = logging.StreamHandler(logStream)
        self.logger.addHandler(logHandler)
        # be sure to remove the handler!
        try:
            # execute queue
            self.execute()
        except:
            self.logger.removeHandler(logHandler)
            if self.config.locking_enabled(): self.get_lock_object().release()
            # re-raise exception
            raise
        # get logs
        self.logger.removeHandler(logHandler)
        logStream.seek(0)
        log = logStream.read()
        del logStream
        del logHandler

        # unlock
        if self.config.locking_enabled(): self.get_lock_object().release()

        event.notify(QueueExecutedEvent(portal, log))
        return log
コード例 #10
0
    def __call__(self, no_response=False, msg=None, *args, **kwargs):
        """
        Add the current context as delete-job to the queue, creates a status
        message to inform the user and returns to the default view.
        @param args:    list of unnamed arguments
        @type args:     list
        @param kwargs:  dict of named keyword-arguments
        @type kwargs:   dict
        @return:        Redirect to object`s default view
        """

        if IPreventPublishing.providedBy(self.context):
            return 'prevented'

        if publisher_jobs_are_disabled():
            return 'disabled'

        self.logger = getLogger()
        # is the object blacklisted?
        if IPathBlacklist(self.context).is_blacklisted():
            self.logger.warning('Could not create delete job for blacklisted '
                                'object (%s at %s)' % (
                    self.context.Title(),
                    '/'.join(self.context.getPhysicalPath())))
            if not no_response:
                return self.request.RESPONSE.redirect('./view')
            return False

        # This view should not be executed at the PloneSiteRoot
        if IPloneSiteRoot.providedBy(self.context):
            raise Exception('Not allowed on PloneSiteRoot')
        # get username
        user = self.context.portal_membership.getAuthenticatedMember()
        username = user.getUserName()
        # create Job
        portal = self.context.portal_url.getPortalObject()
        queue = IQueue(portal)
        queue.createJob('delete', self.context, username)
        self.logger.debug('Created "%s" Job for "%s" at %s' % (
                'delete',
                self.context.Title(),
                '/'.join(self.context.getPhysicalPath()),
                ))

        # status message
        if msg is None:
            msg = _(u'This object will be deleted at the remote sites.')
        add_transaction_aware_status_message(self.request, msg, type='info')

        if not no_response:
            return self.request.RESPONSE.redirect('./view')
コード例 #11
0
    def __call__(self, no_response=False, msg=None, recursive=True):
        if IPreventPublishing.providedBy(self.context):
            return 'prevented'

        if publisher_jobs_are_disabled():
            return 'disabled'

        self.logger = getLogger()
        # is the object blacklisted?
        if IPathBlacklist(self.context).is_blacklisted():
            self.logger.warning(
                'Could not create push job for blacklisted object (%s at %s)' %
                (self.context.Title(), '/'.join(
                    self.context.getPhysicalPath())))
            if not no_response:
                return self.request.RESPONSE.redirect('./view')
            return False

        event.notify(BeforePublishEvent(self.context))

        # mle: now its possible to execite this view on plonesiteroot
        # This View should not be executed at the PloneSiteRoot
        # if IPloneSiteRoot.providedBy(self.context):
        #    raise Exception('Not allowed on PloneSiteRoot')
        # get username
        user = self.context.portal_membership.getAuthenticatedMember()
        username = user.getUserName()

        # create Job
        portal = self.context.portal_url.getPortalObject()
        queue = IQueue(portal)
        queue.createJob('push', self.context, username)
        self.logger.debug('Created "%s" Job for "%s" at %s' % (
            'push',
            self.context.Title(),
            '/'.join(self.context.getPhysicalPath()),
        ))

        if recursive and base_hasattr(self.context, 'contentValues'):
            # Use contentValues for implicit ftw.trash compatibility.
            for obj in filter(belongs_to_parent, self.context.contentValues()):
                obj.restrictedTraverse('@@publisher.publish')(no_response=True,
                                                              msg=msg)

        # status message
        if msg is None:
            msg = _(u'This object has been added to the queue.')
        IStatusMessage(self.request).addStatusMessage(msg, type='info')
        if not no_response:
            return self.request.RESPONSE.redirect('./view')
コード例 #12
0
 def execute_single_job(self, job):
     """ Executes a single job without calling the view
     """
     self.logger = getLogger()
     self.error_logger = getErrorLogger()
     portal = self.context.portal_url.getPortalObject()
     self.config = IConfig(portal)
     self.queue = IQueue(portal)
     # remove job from queue
     if job in self.queue.getJobs():
         self.queue.removeJob(job)
     elif job in self.queue.get_executed_jobs():
         self.queue.remove_executed_job(job)
     # execute it
     self.executeJob(job)
     # move json file
     job.move_jsonfile_to(self.config.get_executed_folder())
     # add to executed list
     return self.queue.append_executed_job(job)
コード例 #13
0
 def execute_single_job(self, job):
     """ Executes a single job without calling the view
     """
     self.logger = getLogger()
     self.error_logger = getErrorLogger()
     portal = self.context.portal_url.getPortalObject()
     self.config = IConfig(portal)
     self.queue = IQueue(portal)
     # remove job from queue
     if job in self.queue.getJobs():
         self.queue.removeJob(job)
     elif job in self.queue.get_executed_jobs():
         self.queue.remove_executed_job(job)
     # execute it
     self.executeJob(job)
     # move json file
     job.move_jsonfile_to(self.config.get_executed_folder())
     # add to executed list
     return self.queue.append_executed_job(job)
コード例 #14
0
    def __call__(self, no_response=False, msg=None):
        if IPreventPublishing.providedBy(self.context):
            return 'prevented'

        if publisher_jobs_are_disabled():
            return 'disabled'

        self.logger = getLogger()
        # is the object blacklisted?
        if IPathBlacklist(self.context).is_blacklisted():
            self.logger.warning('Could not create delete job for blacklisted '
                                'object (%s at %s)' %
                                (self.context.Title(), '/'.join(
                                    self.context.getPhysicalPath())))
            if not no_response:
                return self.request.RESPONSE.redirect('./view')
            return False

        # This view should not be executed at the PloneSiteRoot
        if IPloneSiteRoot.providedBy(self.context):
            raise Exception('Not allowed on PloneSiteRoot')

        # get username
        user = self.context.portal_membership.getAuthenticatedMember()
        username = user.getUserName()

        # create Job
        portal = self.context.portal_url.getPortalObject()
        queue = IQueue(portal)
        queue.createJob('delete', self.context, username)
        self.logger.debug('Created "%s" Job for "%s" at %s' % (
            'delete',
            self.context.Title(),
            '/'.join(self.context.getPhysicalPath()),
        ))

        # status message
        if msg is None:
            msg = _(u'This object will be deleted at the remote sites.')
        add_transaction_aware_status_message(self.request, msg, type='info')

        if not no_response:
            return self.request.RESPONSE.redirect('./view')
コード例 #15
0
    def __call__(self):
        logger = getLogger()

        action = self.request.form['action']
        filepath = self.request.form['filepath']
        path = self.request.form['path']

        obj = api.portal.get().unrestrictedTraverse(path, None)

        if obj is None:
            os.remove(filepath)
            logger.warning(
                'Removed "{0}", since the destination {1} no longer '
                'exists'.format(filepath, path))
            return 'JSON File "{0}" removed'.format(filepath)

        extractor = Extractor()
        data = extractor(obj, action)

        with open(filepath, 'w') as target:
            target.write(data)

        return 'OK'
コード例 #16
0
    def __call__(self, event, no_response=False, msg=None, *args, **kwargs):
        """
        Creates a "rename" job for the current item(s)
        @param args:    list of unnamed arguments
        @type args:     list
        @param kwargs:  dict of named keyword-arguments
        @type kwargs:   dict
        @return:        Redirect to object`s default view
        """

        if IPreventPublishing.providedBy(self.context):
            return 'prevented'

        if publisher_jobs_are_disabled():
            return 'disabled'

        self.logger = getLogger()
        # is the object blacklisted?
        if IPathBlacklist(self.context).is_blacklisted():
            self.logger.warning('Could not create move job for blacklisted '+\
                                    'object (%s at %s)' % (
                    self.context.Title(),
                    '/'.join(self.context.getPhysicalPath())))
            if not no_response:
                return self.request.RESPONSE.redirect('./view')
            return False

        # This View should not be executed at the PloneSiteRoot
        if IPloneSiteRoot.providedBy(self.context):
            raise Exception('Not allowed on PloneSiteRoot')
        # get username
        user = self.context.portal_membership.getAuthenticatedMember()
        username = user.getUserName()
        # create Job
        portal = self.context.portal_url.getPortalObject()
        queue = IQueue(portal)

        additional_data = {'move_data': {
            'newName': event.newName,
            'newParent': get_site_relative_path(event.newParent),
            'newTitle': event.object.Title().decode('utf-8'),
            'oldName': event.oldName,
            'oldParent': get_site_relative_path(event.oldParent),
        }}

        queue.createJob('move', self.context, username,
                        additional_data=additional_data)
        self.logger.debug('Created "%s" Job for "%s" at %s' % (
            'move',
            self.context.Title(),
            '/'.join(self.context.getPhysicalPath()),
        ))
        # status message
        if msg is None:
            msg = _(u'Object move/rename action has been added to the queue.')

        IStatusMessage(self.request).addStatusMessage(
            msg,
            type='info'
        )
        if not no_response:
            return self.request.RESPONSE.redirect('./view')