Ejemplo n.º 1
0
 def post(self, target, source, target_comment=None, source_comment=None):
     if not is_iterable_but_not_string(source):
         source = [source]
     payload = dict(ids=source,
                    target_comment=target_comment,
                    source_comment=source_comment)
     url = self.api._build_url(self.api.endpoint.merge(id=target))
     return self.api._post(url, payload=payload)
Ejemplo n.º 2
0
    def __call__(self, *args, **kwargs):

        renamed_kwargs = dict()
        modifiers = list()
        sort_order = list()
        for key, value in kwargs.items():
            if isinstance(value, date):
                kwargs[key] = value.strftime(self.ZENDESK_DATE_FORMAT)
            elif isinstance(key, datetime):
                kwargs[key] = value.strftime(self.ISO_8601_FORMAT)
            elif is_iterable_but_not_string(value) and key == 'ids':
                kwargs[key] = self._format_many(value)

            if key.endswith('_between'):
                modifiers.append(self.format_between(key, value))
            elif key in ('sort_by', 'sort_order'):
                sort_order.append("%s=%s" % (key, value))
            elif key.endswith('_after'):
                renamed_kwargs[key.replace('_after', '>')] = kwargs[key]
            elif key.endswith('_before'):
                renamed_kwargs[key.replace('_before', '<')] = kwargs[key]
            elif key.endswith('_greater_than'):
                renamed_kwargs[key.replace('_greater_than', '>')] = kwargs[key]
            elif key.endswith('_less_than'):
                renamed_kwargs[key.replace('_less_than', '<')] = kwargs[key]
            elif key == 'minus':
                if is_iterable_but_not_string(value):
                    [modifiers.append("-%s" % v) for v in value]
                else:
                    modifiers.append("-%s" % value)
            elif is_iterable_but_not_string(value):
                modifiers.append(self.format_or(key, value))
            else:
                renamed_kwargs.update({key + ':': '"%s"' % value})

        query = self.endpoint + 'query='
        if args:
            query += ' '.join(args) + '+'

        sort_section = ""
        if sort_order:
            sort_section += '&' + "&".join(sort_order)

        search_parameters = self._format(*modifiers, **renamed_kwargs)

        return "%(query)s%(search_parameters)s%(sort_section)s" % locals()
Ejemplo n.º 3
0
    def __call__(self, query=None, **kwargs):

        renamed_kwargs = dict()
        modifiers = list()
        params = dict()
        for key, value in kwargs.items():
            if isinstance(value, date):
                kwargs[key] = value.strftime(self.ZENDESK_DATE_FORMAT)
            elif isinstance(key, datetime):
                kwargs[key] = value.strftime(self.ISO_8601_FORMAT)
            elif is_iterable_but_not_string(value) and key == 'ids':
                kwargs[key] = ", ".join(map(str, value))
            if key.endswith('_between'):
                modifiers.append(self.format_between(key, value))
            elif key in ('sort_by', 'sort_order'):
                params[key] = value
            elif key.endswith('_after'):
                renamed_kwargs[key.replace('_after', '>')] = kwargs[key]
            elif key.endswith('_before'):
                renamed_kwargs[key.replace('_before', '<')] = kwargs[key]
            elif key.endswith('_greater_than'):
                renamed_kwargs[key.replace('_greater_than', '>')] = kwargs[key]
            elif key.endswith('_less_than'):
                renamed_kwargs[key.replace('_less_than', '<')] = kwargs[key]
            elif key == 'minus':
                if is_iterable_but_not_string(value):
                    [modifiers.append("-%s" % v) for v in value]
                else:
                    modifiers.append("-%s" % value)
            elif is_iterable_but_not_string(value):
                modifiers.append(self.format_or(key, value))
            else:
                if isinstance(value, str) and value.count(' ') > 0:
                    value = '"{}"'.format(value)
                renamed_kwargs.update({key + ':': '%s' % value})

        search_query = [
            '%s%s' % (key, value) for (key, value) in renamed_kwargs.items()
        ]
        search_query.extend(modifiers)
        if query is not None:
            search_query.insert(0, quote(query))
        params['query'] = ' '.join(search_query)

        return Url(self.endpoint, params)
Ejemplo n.º 4
0
    def __call__(self, *args, **kwargs):

        renamed_kwargs = dict()
        modifiers = list()
        sort_order = list()
        for key, value in kwargs.items():
            if isinstance(value, datetime):
                kwargs[key] = value.strftime(self.ZENDESK_DATE_FORMAT)
            elif is_iterable_but_not_string(value) and key == 'ids':
                kwargs[key] = self._format_many(value)

            if key.endswith('_between'):
                modifiers.append(self.format_between(key, value))
            elif key in ('sort_by', 'sort_order'):
                sort_order.append("%s=%s" % (key, value))
            elif key.endswith('_after'):
                renamed_kwargs[key.replace('_after', '>')] = kwargs[key]
            elif key.endswith('_before'):
                renamed_kwargs[key.replace('_before', '<')] = kwargs[key]
            elif key.endswith('_greater_than'):
                renamed_kwargs[key.replace('_greater_than', '>')] = kwargs[key]
            elif key.endswith('_less_than'):
                renamed_kwargs[key.replace('_less_than', '<')] = kwargs[key]
            elif key == 'minus':
                if is_iterable_but_not_string(value):
                    [modifiers.append("-%s" % v) for v in value]
                else:
                    modifiers.append("-%s" % value)
            elif is_iterable_but_not_string(value):
                modifiers.append(self.format_or(key, value))
            else:
                renamed_kwargs.update({key + ':': '"%s"' % value})

        query = self.endpoint + 'query='
        if args:
            query += ' '.join(args) + '+'

        sort_section = ""
        if sort_order:
            sort_section += '&' + "&".join(sort_order)

        search_parameters = self._format(*modifiers, **renamed_kwargs)

        return "%(query)s%(search_parameters)s%(sort_section)s" % locals()
Ejemplo n.º 5
0
 def format_between(self, key, values):
     if not is_iterable_but_not_string(values):
         raise ZenpyException("*_between requires an iterable (list, set, tuple etc)")
     elif not len(values) == 2:
         raise ZenpyException("*_between requires exactly 2 items!")
     elif not all([isinstance(d, datetime) for d in values]):
         raise ZenpyException("*_between only works with dates!")
     key = key.replace('_between', '')
     dates = [v.strftime(self.ZENDESK_DATE_FORMAT) for v in values]
     return "%s>%s %s<%s" % (key, dates[0], key, dates[1])
Ejemplo n.º 6
0
 def format_between(self, key, values):
     if not is_iterable_but_not_string(values):
         raise ZenpyException("*_between requires an iterable (list, set, tuple etc)")
     elif not len(values) == 2:
         raise ZenpyException("*_between requires exactly 2 items!")
     elif not all([isinstance(d, datetime) for d in values]):
         raise ZenpyException("*_between only works with dates!")
     key = key.replace('_between', '')
     dates = [v.strftime(self.ZENDESK_DATE_FORMAT) for v in values]
     return "%s>%s %s<%s" % (key, dates[0], key, dates[1])
Ejemplo n.º 7
0
 def __call__(self, query='', **kwargs):
     processed_kwargs = dict()
     for key, value in kwargs.items():
         if isinstance(value, datetime):
             processed_kwargs[key] = value.strftime(self.ZENDESK_DATE_FORMAT)
         elif is_iterable_but_not_string(value):
             processed_kwargs[key] = ",".join(value)
         else:
             processed_kwargs[key] = value
     processed_kwargs['query'] = query
     return Url(self.endpoint, params=processed_kwargs)
Ejemplo n.º 8
0
 def __call__(self, query='', **kwargs):
     query = 'query={}&'.format(query)
     processed_kwargs = dict()
     for key, value in kwargs.items():
         if isinstance(value, datetime):
             processed_kwargs[key] = value.strftime(ZENDESK_DATE_FORMAT)
         elif is_iterable_but_not_string(value):
             processed_kwargs[key] = ",".join(value)
         else:
             processed_kwargs[key] = value
     return self.endpoint + query + '&'.join(
         ("{}={}".format(k, v) for k, v in processed_kwargs.items()))
Ejemplo n.º 9
0
 def format_between(self, key, values):
     if not is_iterable_but_not_string(values):
         raise ZenpyException("*_between requires an iterable (list, set, tuple etc)")
     elif not len(values) == 2:
         raise ZenpyException("*_between requires exactly 2 items!")
     elif not all([isinstance(d, datetime) for d in values]):
         raise ZenpyException("*_between only works with dates!")
     key = key.replace('_between', '')
     if values[0].tzinfo is None or values[1].tzinfo is None:
         dates = [v.strftime(self.ISO_8601_FORMAT) for v in values]
     else:
         dates = [str(v.replace(microsecond=0).isoformat()) for v in values]
     return "%s>%s %s<%s" % (key, dates[0], key, dates[1])
Ejemplo n.º 10
0
 def format_between(self, key, values):
     if not is_iterable_but_not_string(values):
         raise ValueError("*_between requires an iterable (list, set, tuple etc)")
     elif not len(values) == 2:
         raise ZenpyException("*_between requires exactly 2 items!")
     for value in values:
         if not isinstance(value, datetime):
             raise ValueError("*_between only works with datetime objects!")
         elif value.tzinfo is not None and value.utcoffset().total_seconds() != 0:
             log.warning("search parameter '{}' requires UTC time, results likely incorrect.".format(key))
     key = key.replace('_between', '')
     dates = [v.strftime(self.ISO_8601_FORMAT) for v in values]
     return "%s>%s %s<%s" % (key, dates[0], key, dates[1])
Ejemplo n.º 11
0
    def __call__(self, **kwargs):
        query = ""
        modifiers = []
        for key, value in kwargs.items():
            if key == 'id':
                query += self._single(self.endpoint, value)
            elif key == 'ids':
                query += self._many(self.endpoint, value)
            elif key == 'destroy_ids':
                query += self._many(self.endpoint, value, action='destroy_many.json?ids=')
            elif key == 'create_many':
                query = "".join([self.endpoint, '/create_many.json'])
            elif key == 'create_or_update_many':
                query = self.endpoint
            elif key == 'recover_ids':
                query = self._many(self.endpoint, value, action='recover_many.json?ids=')
            elif key == 'update_many':
                query = "".join([self.endpoint, '/update_many.json'])
            elif key == 'count_many':
                query = self._many(self.endpoint, value, action='count_many.json?ids=')
            elif key in ('external_id', 'external_ids'):
                external_ids = [value] if not is_iterable_but_not_string(value) else value
                query += self._many(self.endpoint, external_ids, action='show_many.json?external_ids=')
            elif key == 'update_many_external':
                query += self._many(self.endpoint, value, action='update_many.json?external_ids=')
            elif key == 'destroy_many_external':
                query += self._many(self.endpoint, value, action='destroy_many.json?external_ids=')
            elif key in ('sort_by', 'sort_order'):
                modifiers.append((key, value))
            elif key == 'permission_set':
                modifiers.append(('permission_set', value))
            elif key == 'role':
                if isinstance(value, basestring):
                    value = [value]
                for role in value:
                    modifiers.append(('role[]', role))
            elif key == 'since':
                modifiers.append((key, value.strftime(self.ISO_8601_FORMAT)))
            elif key == 'async':
                modifiers.append(('async', str(value).lower()))

        if modifiers:
            query += '&' + "&".join(["%s=%s" % (k, v) for k, v in modifiers])

        if self.endpoint not in query:
            query = self.endpoint + '.json?' + query

        if 'sideload' in kwargs and not kwargs['sideload']:
            return query
        else:
            return query + self._format_sideload(self.sideload)
Ejemplo n.º 12
0
    def __call__(self, start_time=None, include=None):
        if start_time is None:
            raise ZenpyException("Incremental Endpoint requires a start_time parameter!")

        elif isinstance(start_time, datetime):
            unix_time = to_unix_ts(start_time)
        else:
            unix_time = start_time

        params = dict(start_time=str(unix_time))
        if include is not None:
            if is_iterable_but_not_string(include):
                params.update(dict(include=",".join(include)))
            else:
                params.update(dict(include=include))
        return Url(self.endpoint, params=params)
Ejemplo n.º 13
0
    def __call__(self, start_time=None, **kwargs):
        if start_time is None:
            raise ZenpyException("Incremental Endpoint requires a start_time parameter!")

        elif isinstance(start_time, datetime):
            unix_time = to_unix_ts(start_time)
        else:
            unix_time = start_time

        params = kwargs
        params.update(dict(start_time=str(unix_time)))

        if 'fields' in kwargs:
            if is_iterable_but_not_string(kwargs['fields']):
                f =  ",".join(kwargs['fields'])
            else:
                f = kwargs['fields']
        else:
            f = "*"
        params.update(dict(fields="chats(" + f + ")"))

        return Url(self.endpoint, params=params)
Ejemplo n.º 14
0
    def __call__(self, **kwargs):
        parameters = {}
        path = self.endpoint
        for key, value in kwargs.items():
            if key == 'id':
                path += "/{}.json".format(value)
            elif key == 'ids':
                path += '/show_many.json'
                parameters[key] = ",".join(map(str, value))
            elif key == 'destroy_ids':
                path += '/destroy_many.json'
                parameters['ids'] = ",".join(map(str, value))
            elif key == 'create_many':
                path += '/create_many.json'
            elif key == '/create_or_update_many':
                path = self.endpoint
            elif key == 'recover_ids':
                path += '/recover_many.json'
                parameters[key] = ",".join(map(str, value))
            elif key == 'update_many':
                path += '/update_many.json'
            elif key == 'count_many':
                path += '/count_many.json'
                parameters[key] = ",".join(map(str, value))
            elif key == 'external_id' and path == 'tickets':
                parameters[key] = value
            elif key in ('external_id', 'external_ids'):
                external_ids = [
                    value
                ] if not is_iterable_but_not_string(value) else value
                path += '/show_many.json'
                parameters['external_ids'] = ",".join(external_ids)
            elif key == 'update_many_external':
                path += '/update_many.json'
                parameters['external_ids'] = ",".join(map(str, value))
            elif key == 'destroy_many_external':
                path += '/destroy_many.json'
                parameters['external_ids'] = ",".join(map(str, value))
            elif key == 'label_names':
                parameters[key] = ",".join(value)
            elif key in (
                    'sort_by',
                    'sort_order',
                    'permission_set',
                    'page',
                    'limit',
                    'cursor',
                    'filter_by',
            ):
                parameters[key] = value
            elif key == 'since':
                parameters[key] = value.strftime(self.ISO_8601_FORMAT)
            elif key == 'async':
                parameters[key] = str(value).lower()
            elif key == 'include':
                if is_iterable_but_not_string(value):
                    parameters[key] = ",".join(value)
                elif value:
                    parameters[key] = value
            elif key in ('since_id', 'ticket_id',
                         'issue_id'):  # Jira integration
                parameters[key] = value

            # this is a bit of a hack
            elif key == 'role':
                if isinstance(value, basestring) or len(value) == 1:
                    parameters['role[]'] = value
                else:
                    parameters['role[]'] = value[0] + '&' + "&".join(
                        ('role[]={}'.format(role) for role in value[1:]))
            elif key.endswith('ids'):
                # if it looks like a type of unknown id, send it through as such
                parameters[key] = ",".join(map(str, value))

        if path == self.endpoint and not path.endswith('.json'):
            path += '.json'
        return Url(path=path, params=parameters)