def get_agent_tasks_by_id(platform_access: PlatformAccess, agent_data_id: int) -> Optional[List[Dict]]: """ Returns all the agent's AgentTasks by the given AgentDataID API-referenece: https://github.com/own-dev/own-agent-open/blob/master/docs/APIDescription.md#get-agentdataagentdataidagenttasks :param platform_access: PlatformAccess of a user which has access to the agent (or of an agent itself) :param agent_data_id: AgentData's ID to get AgentTasks from :return: AgentTasks that are assigned to the agent """ # Get all the forms response = make_request( platform_access=platform_access, http_method='GET', url_postfix=f'agentdata/{agent_data_id}/agenttasks', detail='agentTask', data=None, values={}) if not response: return None data: Dict = json.loads(response.text) tasks: str = data.get('agentTasks', None) return json.loads(tasks) if tasks else None
def post_agent_data(platform_access: PlatformAccess, data: Dict) -> Optional[Dict]: """ Creates new instance of AgentDataConfiguration on the back-end :param platform_access: :param data: agentData-like dict TODO: Check if it is dict or str :return: New JSON-data (with IDs) if the request was successful, otherwise None """ try: http_method = 'POST' detail = 'agentData' postfix = 'agentdata' data['agentData']['agentsUserId'] = platform_access.get_user_id() response = make_request(platform_access=platform_access, http_method=http_method, url_postfix=postfix, detail=detail, data=data) response.raise_for_status() except (HTTPError, ConnectionError) as excpt: logger.error(OWN_ADAPTER_NAME, f'Error while updating database: {excpt}', response) else: logger.debug(OWN_ADAPTER_NAME, f'Successfully updated the database: {response}', response) if response: return response.json() return None
def get_boards(self) -> Optional[List[Board]]: """ Returns all the boards agent is invited to :return: This agent's boards, or None if there was a network or an auth. error """ http_method = 'GET' detail = 'boards' values = {} url_postfix = 'boards' response = None try: response = make_request(platform_access=self.__platform_access, http_method=http_method, url_postfix=url_postfix, detail=detail, values=values) response.raise_for_status() response_data = response.json() boards = self.__create_boards_from_dict(response_data) return boards except HTTPError as http_error: logger.exception(OWN_ADAPTER_NAME, f'Could not retrieve boards data: {http_error}', response) return None except ConnectionError as conect_error: logger.exception( OWN_ADAPTER_NAME, f'Could not get boards list. Exception message: {conect_error}', response) return None
def remove_agent_task_by_id(platform_access: PlatformAccess, agent_task_id: int, agent_data_id: int = None) -> Optional[Response]: """ Removes AgentTask by the given IDs if it persist on the back-end :param platform_access: :param agent_data_id: :param agent_task_id: :return: Response from delete-request """ try: # Prepare request-data url = f'agentdata/{agent_data_id}/agenttasks/{agent_task_id}' detail = 'agentTaskConfiguration' response = make_request(platform_access=platform_access, http_method='DELETE', url_postfix=url, detail=detail) response.raise_for_status() return response except ConnectionError as con_err: logger.exception(OWN_ADAPTER_NAME, f'Connection error for Form: {con_err}') except RequestException as req_excpt: logger.exception( OWN_ADAPTER_NAME, f'During getting the data for Form, occurred: ' f'{req_excpt}') except KeyError as key_excpt: logger.exception(OWN_ADAPTER_NAME, f'Could not find data inside JSON: {key_excpt}') except Exception as error: logger.exception(OWN_ADAPTER_NAME, f'Could not prepare a request for Form: {error}') return None
def delete_agent_data(platform_access: PlatformAccess, agent_data_id: int) -> Optional[Dict]: """ Removes AgentData on a back-end for the given AgentData ID Reference: https://github.com/own-dev/own-agent-open/blob/master/docs/APIDescription.md#delete-agentdataagentdataid :param platform_access: :param agent_data_id: Not to confuse with Agent/User ID!.. :return: Request's response if it was successful, otherwise None """ http_method = 'DELETE' detail = 'agentData' postfix = f'agentdata/{agent_data_id}' try: response = make_request(platform_access=platform_access, http_method=http_method, url_postfix=postfix, detail=detail) response.raise_for_status() except (HTTPError, ConnectionError) as error: logger.error(OWN_ADAPTER_NAME, f'Error while updating database: {error}', response) return None else: logger.debug(OWN_ADAPTER_NAME, f'Successfully removed agent-service from the database: {response}', response) return response
def put_agent_data(platform_access: PlatformAccess, data: Union[Dict, str], agent_data_id: int) -> Optional[Dict]: """ Updates the instance of AgentDataConfiguration on the back-end Reference: https://github.com/own-dev/own-agent-open/blob/master/docs/APIDescription.md#put-agentdataagentdataid :param platform_access: PlatformAccess for this Agent :param data: AgentData configuration in dictionary or JSON (str) format :param agent_data_id: ID of AgentData for the associated Agent on the back-end :return: Updated AgentData if request was successful, or None otherwise """ http_method = 'PUT' detail = 'agentData' postfix = f'agentdata/{agent_data_id}' data['agentData']['agentsUserId'] = platform_access.get_user_id() if isinstance(data, str): data = json.loads(data) try: response = make_request(platform_access=platform_access, http_method=http_method, detail=detail, url_postfix=postfix, data=data) response.raise_for_status() except (HTTPError, ConnectionError) as excpt: logger.error(OWN_ADAPTER_NAME, f'Error while updating database: {excpt}', response) return None else: logger.debug(OWN_ADAPTER_NAME, f'Successfully updated the database: {response}', response) if response: return response.json() return None
def get_agent_data_by_user_id(platform_access: PlatformAccess, user_id: int = None) -> Optional[Dict]: """ Returns agent's data :param platform_access: User's PlatformAccess, generated with login/password tuple :param user_id: Not to confuse with AgentData ID!.. :return: AgentData configuration if a request was successful, otherwise None """ if not user_id: user_id = platform_access.get_user_id() try: http_method = 'GET' detail = 'agentData' postfix = f'user/{user_id}/agentdata' response = make_request(platform_access=platform_access, http_method=http_method, url_postfix=postfix, detail=detail) response.raise_for_status() except (HTTPError, ConnectionError) as error: logger.error(OWN_ADAPTER_NAME, f'Error while updating database: {error}', response) return None else: logger.debug(OWN_ADAPTER_NAME, f'Successfully updated the database: {response}', response) if response: return response.json() return None
def get_agent_data_by_id(platform_access: PlatformAccess, agent_data_id: int) -> Optional[Dict]: """ Returns AgentData сonfiguration by the given AgentData ID Reference: https://github.com/own-dev/own-agent-open/blob/master/docs/APIDescription.md#put-agentdataagentdataid :param platform_access: PlatformAccess instance for this Agent/User :param agent_data_id: Not to confuse with User ID!.. :return: AgentData from JSON if request was successful, otherwise, None """ try: http_method = 'GET' detail = 'agentData' postfix = f'agentdata/{agent_data_id}' response = make_request(platform_access=platform_access, http_method=http_method, url_postfix=postfix, detail=detail) response.raise_for_status() except (HTTPError, ConnectionError) as error: logger.error(OWN_ADAPTER_NAME, f'Error while updating database: {error}', response) else: logger.debug(OWN_ADAPTER_NAME, f'Successfully updated the database: {response}', response) if response: return response.json() return None
def _get_remote_agent_tasks(self) -> [Dict, None]: """ Returns all the AgentTasks a user has access to :return: None or a dict where a key is an agent_data_id and a value is a list of tasks """ agent_tasks = dict() local_configs = self._get_agents_configs_local() platform_access = PlatformAccess(LOGIN, PASSWORD) user_id = platform_access.get_user_id() # Execute GET-request to get AgentData response = make_request(platform_access=platform_access, http_method='GET', url_postfix='agentdata', detail='agentsData') if not response: return None data = response.json() if 'agentsData' in data: for agent in data['agentsData']: if user_id != str(agent['agentsUser']['id']): continue for config in local_configs.values(): agent_name = config['agentData']['name'] credentials = self.find_agent_credentials(agent_name) if not credentials[0]: continue # Add AgentTasks to the dictionary agent_tasks[f'{agent["id"]}'] = agent['agentTasks'], credentials, agent_name return agent_tasks
def get_all_agents_data(platform_access: PlatformAccess) -> Optional[List[Dict]]: """ Returns AgentData for all agents Reference: https://github.com/own-dev/own-agent-open/blob/master/docs/APIDescription.md#get-agentdata :return: [ { "id": int, "description": str, "salary": float, "capacity": int, "status": str, "agentsUser": { "id": int, "firstName": str, "lastName": str, "email": str }, "_links": [ { "rel": str, "href": str }, { "rel": str, "href": str } ] }, .. ] """ try: http_method = 'GET' detail = 'agentData' postfix = 'agentdata' response = make_request(platform_access=platform_access, http_method=http_method, url_postfix=postfix, detail=detail) response.raise_for_status() except Exception as excpt: logger.error(OWN_ADAPTER_NAME, f'Error while updating database: {excpt}', response) return None else: logger.debug(OWN_ADAPTER_NAME, f'Successfully updated the database: {response}', response) if response: return response.json().get('agentsData', None) return []
def set_name(self, new_caption: str) -> Optional[requests.Response]: """ Sets new caption for the element :param new_caption: New name to be set as caption :return: Returns `requests.Response` if the given parameters were correct, otherwise None """ if not new_caption: logger.error( OWN_ADAPTER_NAME, f'No new_caption received for set_name: {new_caption}') return None if not isinstance(new_caption, str): logger.error(OWN_ADAPTER_NAME, f'Received new_caption is not string: {new_caption}') return None # Update the local caption self.__name = new_caption # Prepare the data to update request method = 'PUT' detail = 'element' elem_id = self.get_id() # TODO: Fix self.get_id() returns '/boards/{board_id}/elements/{elem_id}' url = elem_id[1:] data = {'element': {'caption': new_caption}} # Update the remote caption response = make_request(platform_access=self.__platform_access, http_method=method, url_postfix=url, detail=detail, data=data) if response: logger.debug(OWN_ADAPTER_NAME, f'Caption successfully changed to [{new_caption}].', response) else: logger.error(OWN_ADAPTER_NAME, f'Caption was not set up: {response}') # FIXME: Shouldn't we return status_code instead? return response
def get_all_agent_tasks(platform_access: PlatformAccess, agent_data_id: int) -> Optional[List[Dict]]: """ Retrieves all the agent tasks for each agent-service :param platform_access: :param agent_data_id: :return: """ if not (platform_access and agent_data_id): return None http_method = 'GET' detail = 'agentTask' postfix = f'agentdata/{agent_data_id}/agenttasks' response = make_request(platform_access=platform_access, http_method=http_method, url_postfix=postfix, detail=detail) if response: return response.json() return None
def get_agent_task_answers_by_id(platform_access: PlatformAccess, agent_task_id: int, board_id: int, element_id: int, agent_data_id: int) -> Optional[Dict]: """ Returns JSON from the given AgentDataID and AgentTaskID :param element_id: an agent task id :param board_id: an agent board id :param agent_task_id: an agent task id :param agent_data_id: an agent data id :param platform_access: a platform access :return: a dict containing response from the server """ try: # Prepare request-data url = f'agentdata/{agent_data_id}/agenttasks/' \ f'{agent_task_id}/boards/{board_id}/elements/{element_id}/answers' detail = 'agentTaskElement' response = make_request(platform_access=platform_access, http_method='GET', url_postfix=url, detail=detail) response.raise_for_status() return response.json() except ConnectionError as con_err: logger.exception(OWN_ADAPTER_NAME, f'Connection error for Form: {con_err}') except RequestException as req_excpt: logger.exception( OWN_ADAPTER_NAME, f'During getting the data for Form, occurred: ' f'{req_excpt}') except KeyError as key_excpt: logger.exception(OWN_ADAPTER_NAME, f'Could not find data inside JSON: {key_excpt}') except Exception as error: logger.exception(OWN_ADAPTER_NAME, f'Could not prepare a request for Form: {error}') return None
def get_agent_task_by_id(platform_access: PlatformAccess, agent_task_id: int, agent_data_id: int) -> Optional[Dict]: """ Returns JSON from the given AgentDataID and AgentTaskID :param agent_task_id: an agent task id :param agent_data_id: an agent data id :param platform_access: a platform access :return: Response's data from a back-end if no error occurred, otherwise None """ if not (agent_task_id and agent_data_id): return None try: # Prepare request-data url = f'agentdata/{agent_data_id}/agenttasks/{agent_task_id}/configuration' detail = 'agentTaskConfiguration' response = make_request(platform_access=platform_access, http_method='GET', url_postfix=url, detail=detail) response.raise_for_status() return response.json() except ConnectionError as con_err: logger.exception(OWN_ADAPTER_NAME, f'Connection error for Form: {con_err}') except RequestException as req_excpt: logger.exception( OWN_ADAPTER_NAME, f'During getting the data for Form, occurred: ' f'{req_excpt}') except KeyError as key_excpt: logger.exception(OWN_ADAPTER_NAME, f'Could not find data inside JSON: {key_excpt}') except Exception as error: logger.exception(OWN_ADAPTER_NAME, f'Could not prepare a request for Form: {error}') return None
def upload_changed_agent_task(platform_access: PlatformAccess, agent_data_id: int, agent_task: Dict) -> Optional[Dict]: """ Update an agent task :param agent_task: New AgentTask's data :param agent_data_id: an id of agent_data :param platform_access: a platform access :return: Complete updated AgentTask if request was successful, otherwise None """ try: # Prepare request data for retrieving Input detail = 'agentTaskConfiguration' url = f'agentdata/{agent_data_id}/agenttasks/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 retrieved).') response.raise_for_status() return response.json() 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}, ' f'{req_excpt.__class__} occurred: {req_excpt}') except Exception as error: logger.exception(OWN_ADAPTER_NAME, f'Could not retrieve data from {url}: {error}') return None
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