class TopicManager(object):
    """
    classdocs
    """
    __FINDER_BATCH_SIZE = 100

    # ----------------------------------------------------------------------------------------------------------------

    def __init__(self, http_client, api_key):
        """
        Constructor
        """
        self.__rest_client = RESTClient(http_client, api_key)

    # ----------------------------------------------------------------------------------------------------------------

    def find(self, topic_path):
        if topic_path is None:
            return None

        request_path = '/v1/topics/' + urllib.parse.quote(topic_path, '')

        # request...
        self.__rest_client.connect()

        try:
            response_jdict = self.__rest_client.get(request_path)
        except RuntimeError:
            response_jdict = None

        self.__rest_client.close()

        topic = TopicMetadata.construct_from_jdict(response_jdict)

        return topic

    def find_for_org(self, org_id, partial_topic_path=None, topic_schema=None):
        topics = []

        # request...
        self.__rest_client.connect()

        try:
            for batch in self.__find(org_id, partial_topic_path, topic_schema):
                topics.extend(batch)

        finally:
            self.__rest_client.close()

        return topics

    def find_for_user(self, user_id):
        topics = []

        # request...
        self.__rest_client.connect()

        try:
            for batch in self.__find_for_user(user_id):
                topics.extend(batch)

        finally:
            self.__rest_client.close()

        return topics

    def find_for_device(self, client_id, start_date, end_date):
        request_path = '/v1/messages/device/' + client_id
        params = {
            'start-date': start_date.as_iso8601(),
            'end-date': end_date.as_iso8601()
        }

        topics = {}

        # request...
        self.__rest_client.connect()

        try:
            while True:
                jdict = self.__rest_client.get(request_path, params)

                # messages...
                for message in jdict['messages']:
                    if message['topic'] not in topics:
                        topics[message[
                            'topic']] = DeviceTopic.construct_from_message_jdict(
                                message)

                # next...
                next_query = NextMessageQuery.construct_from_uri(
                    jdict.get('next'))

                if next_query is None:
                    break

                params['start-date'] = next_query.start_date.as_iso8601()
                params['end-date'] = next_query.end_date.as_iso8601()

            sorted_topics = OrderedDict(sorted(topics.items()))

            return list(sorted_topics.values())

        finally:
            self.__rest_client.close()

    # ----------------------------------------------------------------------------------------------------------------

    def __find(self, org_id, partial_topic_path=None, topic_schema=None):
        request_path = '/v2/orgs/' + org_id + '/topics'
        params = {'offset': 0, 'count': self.__FINDER_BATCH_SIZE}

        while True:
            topics = []

            # request...
            response_jdict = self.__rest_client.get(request_path, params)

            if response_jdict is None:
                return

            # topics...
            topics_jdict = response_jdict.get('topics')

            if topics_jdict:
                for topic_jdict in topics_jdict:
                    topic = TopicSummary.construct_from_jdict(topic_jdict)

                    if partial_topic_path is not None and partial_topic_path not in topic.path:
                        continue

                    if topic_schema is not None and (topic.schema_id !=
                                                     topic_schema):
                        continue

                    topics.append(topic)

            yield topics

            if len(topics_jdict) == 0:
                return

            # next...
            params['offset'] += len(topics_jdict)

    def __find_for_user(self, user_id):
        request_path = '/v1/users/' + user_id + '/topics'
        params = {'offset': 0, 'count': self.__FINDER_BATCH_SIZE}

        while True:
            # request...
            topics_jdict = self.__rest_client.get(request_path, params)

            # topics...
            topics = [
                UserTopic.construct_from_jdict(topic_jdict)
                for topic_jdict in topics_jdict
            ]

            yield topics

            if len(topics_jdict) == 0:
                return

            # next...
            params['offset'] += len(topics_jdict)

    # ----------------------------------------------------------------------------------------------------------------

    def create(self, topic):
        request_path = '/v2/topics'

        # request...
        self.__rest_client.connect()

        try:
            response = self.__rest_client.post(request_path, topic.as_json())

        finally:
            self.__rest_client.close()

        success = response == topic.path

        return success

    def update(self, topic_path, topic):
        request_path = '/v1/topics/' + topic_path

        # request...
        self.__rest_client.connect()

        try:
            self.__rest_client.put(
                request_path,
                topic.as_json())  # TODO: check what it looks like
        finally:
            self.__rest_client.close()

    def delete(self, topic_path):
        request_path = '/v1/topics/' + urllib.parse.quote(topic_path, '')

        # request...
        self.__rest_client.connect()

        try:
            response = self.__rest_client.delete(request_path)

        finally:
            self.__rest_client.close()

        success = response == ''

        return success

    # ----------------------------------------------------------------------------------------------------------------

    def __str__(self, *args, **kwargs):
        return "TopicManager:{rest_client:%s}" % self.__rest_client
Exemple #2
0
class DeviceManager(object):
    """
    classdocs
    """
    __FINDER_BATCH_SIZE = 100

    # ----------------------------------------------------------------------------------------------------------------

    def __init__(self, http_client, api_key):
        """
        Constructor
        """
        self.__rest_client = RESTClient(http_client, api_key)

    # ----------------------------------------------------------------------------------------------------------------

    def find(self, org_id, client_id):
        request_path = '/v1/orgs/' + org_id + '/devices/' + client_id

        # request...
        self.__rest_client.connect()

        try:
            response_jdict = self.__rest_client.get(request_path)
        except RuntimeError:
            response_jdict = None

        self.__rest_client.close()

        device = Device.construct_from_jdict(response_jdict)

        return device

    def find_for_name(self, org_id, name):
        devices = self.find_all_for_org(org_id)

        for device in devices:  # warning: unique only by convention
            if device.name == name:
                return self.find(org_id, device.client_id)

        return None

    def find_all_for_user(self, user_id):
        request_path = '/v1/users/' + user_id + '/devices'
        devices = []

        # request...
        self.__rest_client.connect()

        try:
            for batch in self.__find(request_path, {'user-id': user_id}):
                devices.extend(batch)

        finally:
            self.__rest_client.close()

        return devices

    def find_all_for_org(self, org_id):
        request_path = '/v1/orgs/' + org_id + '/devices'
        devices = []

        # request...
        self.__rest_client.connect()

        try:
            for batch in self.__find(request_path):
                devices.extend(batch)

        finally:
            self.__rest_client.close()

        return devices

    # ----------------------------------------------------------------------------------------------------------------

    def __find(self, request_path, params=None):
        if params is None:
            params = {}

        params['offset'] = 0
        params['count'] = self.__FINDER_BATCH_SIZE

        while True:
            # request...
            response_jdict = self.__rest_client.get(request_path, params)

            devices = [
                DeviceSummary.construct_from_jdict(jdict)
                for jdict in response_jdict
            ] if response_jdict else []

            yield devices

            if len(devices) == 0:
                break

            # next...
            params['offset'] += len(devices)

    # ----------------------------------------------------------------------------------------------------------------

    def create(self, user_id, device):
        request_path = '/v1/users/' + user_id + '/devices'

        # request...
        self.__rest_client.connect()

        try:
            response_jdict = self.__rest_client.post(request_path,
                                                     device.as_json())
        finally:
            self.__rest_client.close()

        device = Device.construct_from_jdict(response_jdict)

        return device

    def update(self, org_id, system_id, device):
        request_path = '/v1/orgs/' + org_id + '/devices/' + system_id

        # request...
        self.__rest_client.connect()

        try:
            self.__rest_client.put(request_path, device.as_json())
        finally:
            self.__rest_client.close()

    def delete(self, user_id, client_id):
        request_path = '/v1/users/' + user_id + '/devices/' + client_id

        # request...
        self.__rest_client.connect()

        try:
            self.__rest_client.delete(request_path)
        finally:
            self.__rest_client.close()

    # ----------------------------------------------------------------------------------------------------------------

    def __str__(self, *args, **kwargs):
        return "DeviceManager:{rest_client:%s}" % self.__rest_client