Esempio n. 1
0
    def get_element_by_id(element_id: int, platform_access: PlatformAccess,
                          board: 'Board') -> Optional['Element']:
        """
        Returns an Element by the given board and ID

        :param element_id: Element's ID to retrieve
        :param platform_access: PlatformAccess of a user with access rights
        :param board: Element's board

        :return: Element if found, otherwise None
        """
        # Compose the request, execute it, and retrieve its data
        http_method = 'GET'
        detail = 'elements'
        url = compose_path(platform_access.get_platform_url(), 'boards',
                           board.get_id(), 'elements', element_id)

        values = {}
        headers = platform_access.get_headers(http_method, url, values, detail)
        response = request(method=http_method, url=url, headers=headers)
        response.raise_for_status()
        response_data = response.json()

        href = response_data['element']['_links'][0]['href']
        name = response_data['element']['caption']

        element = Element(platform_access, name, href, board)
        return element
Esempio n. 2
0
 def __init__(self,
              platform_access: PlatformAccess,
              name: str = '',
              identifier: str = ''):
     """
     :param platform_access: PlatformAccess-object a(n) user/agent of that is on the board?..
     :param name: Board's name
     :param identifier: Board's ID on the platform
     """
     self.__platform_access = platform_access
     self.__name = name
     self.__url = compose_path(self.__platform_access.get_platform_url(),
                               'boards', identifier)
     self.__id = identifier
Esempio n. 3
0
    def put_message(self, message: str) -> Optional[int]:
        """
        Posts a new message on the board's activity chat
        Multiple languages are supported

        :param message: Text to post

        :return: Response's status code, or None
        """
        if not message:
            return None

        http_method = 'POST'
        url = compose_path(self.__url, 'posts')
        detail = 'post'

        payload_data = {'post': {'message': message}}
        payload = json.dumps(payload_data,
                             separators=(',', ':'),
                             ensure_ascii=False)
        values = {}
        headers = self.__platform_access.get_headers(http_method,
                                                     url,
                                                     values,
                                                     detail,
                                                     payload=payload)
        try:
            response = request(method=http_method,
                               url=url,
                               headers=headers,
                               data=payload.encode())
            response_status = response.status_code
            if response_status != HTTPStatus.CREATED:
                logger.exception(
                    OWN_ADAPTER_NAME,
                    f'Couldn\'t put new message in the {self.get_name()} board. '
                    f'{response.content}', response)
            return response_status
        except Exception as error:
            logger.exception(
                OWN_ADAPTER_NAME,
                f'Couldn\'t put new message in the {self.get_name()} board.'
                f'{error}')
            return None
Esempio n. 4
0
    def __elements_request(self) -> Optional[Dict]:
        """
        Composes board's elements

        :return: Data on/of board's elements if a request was successful, otherwise None
        """
        http_method = 'GET'
        detail = 'elements'
        url = compose_path(self.__url, 'elements')
        values = {}
        headers = self.__platform_access.get_headers(http_method, url, values,
                                                     detail)
        try:
            response = request(method=http_method, url=url, headers=headers)
            response.raise_for_status()
        except HTTPError as http_error:
            logger.exception(OWN_ADAPTER_NAME, f'{http_error}')
            return None
        except ConnectionError as connect_error:
            logger.exception(OWN_ADAPTER_NAME, f'{connect_error}')
            return None
        response_data = response.json()
        return response_data
Esempio n. 5
0
def update_agent_task_by_id(platform_access: PlatformAccess,
                            agent_data_id: int,
                            agent_task_id: int,
                            task_file_name: str = '') -> Optional[Dict]:
    """
    Updates agent task with given ID
    :param platform_access:
    :param agent_task_id:
    :param agent_task_data:
    :return: response or nothing
    """
    if not task_file_name:
        return None
    file_location = os.path.join(AGENTS_SERVICES_PATH, task_file_name)
    try:
        with open(file_location, 'r') as file:
            agent_task = json.load(file)
    except Exception as e:
        logger.exception(
            OWN_ADAPTER_NAME,
            f'Could not get an agent task from file {file_location}. Exception: {e}'
        )
        return None

    try:
        # Prepare request data for retrieving Input...
        detail = 'agentTaskConfiguration'
        url = compose_path('agentdata', agent_data_id, 'agenttasks',
                           agent_task_id, 'configuration')
        response = make_request(platform_access=platform_access,
                                http_method='PUT',
                                url_postfix=url,
                                data=agent_task,
                                detail=detail)
        logger.debug(OWN_ADAPTER_NAME,
                     'Form-request data has been successfully updated).')

        response.raise_for_status()

        response_data = response.json()
        if response_data and 'agentTask' in response_data:
            agent_data = response_data['agentTask'].get('agentData')
            if 'agentTasks' in agent_data:
                response_data['agentTask']['agentData'].pop('agentTasks', None)

            agent_input = response_data['agentTask'].get(
                'input', {}).get('indexedInputFields')
            if agent_input:
                response_data['agentTask']['input']['indexedInputFields'].sort(
                    key=lambda k: k['index'] if 'index' in k else k['id'])
            with open(file_location, 'w') as file:
                json.dump(response_data, file, indent=2)

        return response_data

    except HTTPError as http_err:
        logger.exception(OWN_ADAPTER_NAME,
                         f'HTTP error ({http_err}) while making request')
    except ConnectionError as con_err:
        logger.exception(OWN_ADAPTER_NAME,
                         f'Connection error for {url}: {con_err}')
    except RequestException as req_excpt:
        logger.exception(
            OWN_ADAPTER_NAME,
            f'During getting the data from {url}, {req_excpt.__class__} occurred:'
            f' {req_excpt}')
    except Exception as e:
        logger.exception(OWN_ADAPTER_NAME,
                         f'Could not retrieve data from {url}: {e}')
    return None
Esempio n. 6
0
    def add_element(self,
                    pos_x: int,
                    pos_y: int,
                    size_x: int = 1,
                    size_y: int = 1,
                    caption: str = '') -> Union[Element, int, None]:
        """
        Tries to add new element with the given input parameters

        :param pos_x: Start of the element on the X axis
        :param pos_y: Start of the element on the Y axis
        :param size_x: Width of the element (X axis)
        :param size_y: Height of the element (Y axis)
        :param caption: The name of the element

        :return: Either new Element object (if succeeded), or response code
        """
        # add element with an empty name (no creation of the message on the board chat)
        new_element_link = ''
        response = None
        try:
            http_method = 'POST'
            detail = 'activities'
            url = self.__url + '/elements'
            payload_data = {
                'element': {
                    'posX': pos_x,
                    'posY': pos_y,
                    'sizeX': size_x,
                    'sizeY': size_y,
                    'type': 'MultiInput',
                    'caption': caption
                }
            }
            payload_data = json.dumps(payload_data,
                                      separators=(',', ':'),
                                      ensure_ascii=False)
            values = {}
            headers = self.__platform_access.get_headers(http_method,
                                                         url,
                                                         values,
                                                         detail,
                                                         payload=payload_data)

            response = request(method=http_method,
                               url=url,
                               headers=headers,
                               data=payload_data.encode())
            response.raise_for_status()
            response_data = response.json()
            new_element_link = response_data["element"]["_links"][0]["href"]
        except HTTPError as http_error:
            logger.exception(
                OWN_ADAPTER_NAME,
                f'Error: add element to {self.get_name()} failed. '
                f'Error type: {http_error}', response)
            return response.status_code
        except ConnectionError as connect_error:
            logger.exception(
                OWN_ADAPTER_NAME,
                f'Error: add element to {self.get_name()} failed. '
                f'Error type: {connect_error}', response)
            return response.status_code
        except Exception as error:
            logger.exception(OWN_ADAPTER_NAME,
                             f'Unknown error for adding element: {error}',
                             response)
            return None
        # add element name (creation of the message on the board chat)
        try:
            http_method = 'PUT'
            detail = 'element'
            if PREFIX and PREFIX in new_element_link:
                new_element_link = new_element_link[len(PREFIX) + 1:]
            url = compose_path(self.__platform_access.get_platform_url(),
                               new_element_link)
            payload_data = {
                'element': {
                    'posX': pos_x,
                    'posY': pos_y,
                    'sizeX': size_x,
                    'sizeY': size_y,
                    'type': 'MultiInput',
                    'caption': caption
                }
            }
            payload = json.dumps(payload_data,
                                 separators=(',', ':'),
                                 ensure_ascii=False)
            values = {}
            headers = self.__platform_access.get_headers(http_method,
                                                         url,
                                                         values,
                                                         detail,
                                                         payload=payload)

            response = request(method=http_method,
                               url=url,
                               headers=headers,
                               data=payload.encode())
            response.raise_for_status()
            response_data = response.json()

            new_element = self.__create_elem_from_response(
                response_data['element'])
            return new_element

        except (HTTPError, ConnectionError) as error:
            logger.exception(
                OWN_ADAPTER_NAME,
                f'Error: add element name {caption} to {self.get_name()} failed. '
                f'Error type: {error}', response)
            return error