def get_remote_objects(self):
     """ Returns a list of remote objects (as dicts) with some basic
     information.
     """
     jdata = sendRequestToRealm({}, self.get_current_realm(),
                                '@@publisher-controlling-json-remote-object')
     bl = IPathBlacklist(self.context)
     def _filterer(item):
         path = self.remote_to_local_path(item.get('path'))
         if bl.is_blacklisted(path):
             return False
         elif bl.is_blacklisted(item.get('original_path')):
             return False
         return True
     data = filter(_filterer, simplejson.loads(jdata))
     return data
Пример #2
0
def download(self, REQUEST=None, RESPONSE=None):
    """Download the saved data
    """
    url_tool = getToolByName(self, 'portal_url')
    config = IConfig(url_tool.getPortalObject())
    pub_state = getMultiAdapter((self, REQUEST), IPublisherContextState)
    realms = config.getRealms()
    download_format = getattr(self, 'DownloadFormat', 'csv')

    if len(realms) == 0 or not pub_state.is_parent_published():
        if download_format == 'tsv':
            return self.download_tsv(REQUEST, RESPONSE)
        else:
            assert download_format == 'csv', 'Unknown download format'
            return self.download_csv(REQUEST, RESPONSE)

    elif len(realms) == 1:
        data = {'uid': self.UID(), 'download_format': download_format}
        return_data_realm = sendRequestToRealm(data,
                                               realms[0],
                                               'formgen_get_saved_data')
        return_data_this = self.getSavedFormInputForEdit()
        return_data = '{}{}'.format(return_data_realm, return_data_this)

        filename = self.id
        if filename.find('.') < 0:
            filename = '%s.%s' % (filename, download_format)
        header_value = contentDispositionHeader('attachment',
                                                self.getCharset(),
                                                filename=filename)
        RESPONSE.setHeader("Content-Disposition", header_value)
        sep_type = download_format == 'csv' and 'comma' or 'tab'
        RESPONSE.setHeader("Content-Type",
                           'text/%s-separated-values;'
                           'charset=%s' % (sep_type, self.getCharset()))

        return return_data

    else:
        messages = IStatusMessage(self.request)
        messages.add(_(u"couldn't determine correct realm to fetch from."),
                     type=u"error")
        return RESPONSE.redirect(self.context.absolute_url())
Пример #3
0
 def __call__(self, *args, **kwargs):
     id = self.request.get('id', '')
     realm = self.getRealmById(id)
     if not realm:
         self.statusMessage(_(u'error_realm_not_found',
                              default=u'Could not find realm'), 'error')
     else:
         responseText = sendRequestToRealm({}, realm,
                                           'publisher.testConnection')
         if responseText=='ok':
             self.statusMessage(_(u'info_realm_connection_okay',
                                  default=u'Connection okay'))
         else:
             self.statusMessage(
                 _(u'error_realm_connection_failed',
                   default=u'Connection to realm failed: ${msg}',
                   mapping=dict(msg=responseText.decode('utf-8'))),
                 type='error')
     return self.request.RESPONSE.redirect('./@@publisher-config')
Пример #4
0
 def __call__(self, *args, **kwargs):
     id = self.request.get('id', '')
     realm = self.getRealmById(id)
     if not realm:
         self.statusMessage(_(u'error_realm_not_found',
                              default=u'Could not find realm'), 'error')
     else:
         responseText = sendRequestToRealm({}, realm,
                                           'publisher.testConnection')
         if responseText=='ok':
             self.statusMessage(_(u'info_realm_connection_okay',
                                  default=u'Connection okay'))
         else:
             self.statusMessage(
                 _(u'error_realm_connection_failed',
                   default=u'Connection to realm failed: ${msg}',
                   mapping=dict(msg=responseText.decode('utf-8'))),
                 type='error')
     return self.request.RESPONSE.redirect('./@@publisher-config')
def download(self, REQUEST=None, RESPONSE=None):
    """Download the saved data
    """
    url_tool = getToolByName(self, 'portal_url')
    config = IConfig(url_tool.getPortalObject())
    pub_state = getMultiAdapter((self, REQUEST), IPublisherContextState)
    realms = config.getRealms()
    download_format = getattr(self, 'DownloadFormat', 'csv')

    if len(realms) == 0 or not pub_state.is_parent_published():
        if download_format == 'tsv':
            return self.download_tsv(REQUEST, RESPONSE)
        else:
            assert download_format == 'csv', 'Unknown download format'
            return self.download_csv(REQUEST, RESPONSE)

    elif len(realms) == 1:
        data = {'uid': self.UID(), 'download_format': download_format}
        return_data = sendRequestToRealm(data,
                                         realms[0],
                                         'formgen_get_saved_data')
        filename = self.id
        if filename.find('.') < 0:
            filename = '%s.%s' % (filename, download_format)
        header_value = contentDispositionHeader('attachment',
                                                self.getCharset(),
                                                filename=filename)
        RESPONSE.setHeader("Content-Disposition", header_value)
        sep_type = download_format == 'csv' and 'comma' or 'tab'
        RESPONSE.setHeader("Content-Type",
                           'text/%s-separated-values;'
                           'charset=%s' % (sep_type, self.getCharset()))
        return return_data

    else:
        messages = IStatusMessage(self.request)
        messages.add(_(u"couldn't determine correct realm to fetch from."),
                     type=u"error")
        return RESPONSE.redirect(self.context.absolute_url())
Пример #6
0
def download(self, response, delimiter=""):
    """This patch combines the data from the sender installation and the receiver
    installation to one csv / tsv.
    We assume that the form config is the same on both sides.

    The concept is to first execute the standard implementation, which sets the
    response headers and streams the local data.

    If the context is considered public, the second step is to get the data from
    the remote realms and append it to the response body (with response.write).

    This will combine the data of the all sites in a streamed http response.

    This implementation also works in local development with two plone sites,
    assuming that the receiver side does not have any realms configured.
    """

    site = getSite()
    realms = IConfig(site).getRealms()
    if not realms:
        return

    if site.REQUEST.get('is_publisher', None):
        # Prevent endless loop if sender and receiver are running on the same machine
        self._old_download(response, delimiter)
        return

    pub_state = getMultiAdapter((get_context(self), response),
                                IPublisherContextState)
    if not pub_state.is_parent_published():
        return

    site_path = '/'.join(site.getPhysicalPath())
    context_path = '/'.join(get_context(self).getPhysicalPath())
    relative_path = os.path.relpath(context_path, site_path)
    view_path = '/'.join((relative_path, '@@actions', self.__name__, '@@data'))

    is_xlsx = getattr(self, 'DownloadFormat', 'tsv') == 'xlsx'
    is_csv = getattr(self, 'DownloadFormat', 'tsv') == 'csv'

    if is_csv and len(delimiter) == 0:
        delimiter = ','

    if not is_xlsx:
        self._old_download(response, delimiter)

    for realm in realms:
        try:
            remote_response = sendRequestToRealm(getSite().REQUEST.form.copy(),
                                                 realm,
                                                 view_path.lstrip('/') +
                                                 '?is_publisher=1',
                                                 return_response=True)

        except HTTPError:
            remote_response = False  # Nothing to combine

        if remote_response and remote_response.code != 200:
            raise ValueError(
                'Bad response from remote realm ({} {}): {!r}..'.format(
                    remote_response.code,
                    remote_response.msg,
                    remote_response.read(100),
                ))

        try:
            if is_xlsx:
                use_title_row = getattr(self, "UseColumnNames", False)
                local_excel = self.get_saved_form_input_as_xlsx(use_title_row)
                combine_excel(response, local_excel, remote_response,
                              use_title_row)
            else:
                response.write(remote_response.read())
        except ImportError:
            raise Exception(
                'Was not able to combine excel, since openpyxl is missing')
        finally:
            if remote_response:
                remote_response.close()