def get_application_data(artifact_dir: str, endpoint: str, auth_token: str,
                         extra_data: bool, **kwargs):
    # Tuple with (AppName, AppKey): app_info[0] = AppName; app_info[1] = AppKey
    app_info = _get_application_info(artifact_dir, endpoint, auth_token,
                                     **kwargs)
    query = "{}/{}".format(APPLICATIONS_ENDPOINT, app_info[1])
    params = {"IncludeModules": extra_data, "IncludeEnvStatus": extra_data}
    # Sends the request
    response = send_get_request(endpoint, auth_token, query, params)
    status_code = int(response["http_status"])
    if status_code == APPLICATION_SUCCESS_CODE:
        # Stores the result
        filename = "{}{}".format(app_info[0], APPLICATION_FILE)
        filename = os.path.join(APPLICATION_FOLDER, filename)
        store_data(artifact_dir, filename, response["response"])
        return response["response"]
    elif status_code == APPLICATION_FLAG_FAILED_CODE:
        raise InvalidParametersError(
            "There was an error with the 'extra_data' flag or the request was invalid when listing the application. The params used were: {}. Details: {}"
            .format(params, response["response"]))
    elif status_code == APPLICATION_NO_PERMISSION_CODE:
        raise NotEnoughPermissionsError(
            "You don't have enough permissions to see the details of that application. Details: {}"
            .format(response["response"]))
    elif status_code == APPLICATION_FAILED_CODE:
        raise EnvironmentNotFoundError(
            "Failed getting running applications because one of the environments was not found. Details: {}"
            .format(response["response"]))
    else:
        raise NotImplementedError(
            "There was an error. Response from server: {}".format(response))
def send_deployment(artifact_dir: str, endpoint: str, auth_token: str,
                    lt_api_version: int, app_keys: list, dep_note: str,
                    source_env: str, dest_env: str):
    # builds the deployment plan
    deployment_request = _create_deployment_plan(artifact_dir, endpoint,
                                                 lt_api_version, auth_token,
                                                 app_keys, dep_note,
                                                 source_env, dest_env)
    # Sends the request
    response = send_post_request(endpoint, auth_token, DEPLOYMENTS_ENDPOINT,
                                 deployment_request)
    status_code = int(response["http_status"])
    if status_code == DEPLOYMENT_SUCCESS_CODE:
        return response["response"]
    elif status_code == DEPLOYMENT_INVALID_CODE:
        raise InvalidParametersError(
            "The request is invalid. Check the body of the request for errors. Body: {}. Details: {}."
            .format(deployment_request, response["response"]))
    elif status_code == DEPLOYMENT_NO_PERMISSION_CODE:
        raise NotEnoughPermissionsError(
            "You don't have enough permissions to create the deployment. Details: {}"
            .format(response["response"]))
    elif status_code == DEPLOYMENT_NO_ENVIRONMENT_CODE:
        raise EnvironmentNotFoundError(
            "Can't find the source or target environment. Details: {}.".format(
                response["response"]))
    elif status_code == DEPLOYMENT_FAILED_CODE:
        raise ServerError(
            "Failed to create the deployment. Details: {}".format(
                response["response"]))
    else:
        raise NotImplementedError(
            "There was an error. Response from server: {}".format(response))
def _find_environment_url(artifact_dir: str, api_url: str, auth_token: str,
                          environment_name: str):
    env_url = ""
    cached_results = False
    try:
        # Try searching the key on the cache
        environments = load_data(artifact_dir, ENVIRONMENTS_FILE)
        cached_results = True
    except:
        # Query the LT API, since there's no cache
        environments = get_environments(artifact_dir, api_url, auth_token)
    for env in environments:
        if env["Name"] == environment_name:
            env_url = env["HostName"]
    # If the env key  was not found, determine if it needs to invalidate the cache or the application does not exist
    # since we explitly clear the cache, and the code is not multithreaded, it should not lead to recursion issues
    # If the cache was not used in the first place, it means the app does not exist
    if env_url == "" and not cached_results:
        raise EnvironmentNotFoundError(
            "Failed to retrieve the environment. Please make sure the environment exists. Environment name: {}"
            .format(environment_name))
    # If the cache was used, it needs to be cleared and re-fetched from the LT server
    elif env_url == "" and cached_results:
        clear_cache(artifact_dir, ENVIRONMENTS_FILE)
        return _find_environment_url(artifact_dir, api_url, auth_token,
                                     environment_name)
    return env_url
def get_environments(artifact_dir: str, endpoint: str, auth_token: str):
    # Sends the request
    response = send_get_request(endpoint, auth_token, ENVIRONMENTS_ENDPOINT,
                                None)
    status_code = int(response["http_status"])
    if status_code == ENVIRONMENTS_SUCCESS_CODE:
        # Stores the result
        store_data(artifact_dir, ENVIRONMENTS_FILE, response["response"])
        return response["response"]
    elif status_code == ENVIRONMENTS_NOT_FOUND_CODE:
        raise EnvironmentNotFoundError(
            "No environments found. Details {}".format(response["response"]))
    elif status_code == ENVIRONMENTS_FAILED_CODE:
        raise ServerError(
            "Failed to list the environments. Details: {}".format(
                response["response"]))
    else:
        raise NotImplementedError(
            "There was an error. Response from server: {}".format(response))
def export_app_oap(file_path: str, endpoint: str, auth_token: str,
                   env_key: str, app_key: str, app_version_key: str):
    query = "{}/{}/{}/{}/{}".format(APPLICATIONS_ENDPOINT, app_key,
                                    APPLICATION_VERSIONS_ENDPOINT,
                                    app_version_key,
                                    APPLICATION_VERSIONS_CONTENT)
    # Sends the request
    response = send_get_request(endpoint, auth_token, query, None)

    status_code = int(response["http_status"])
    if status_code == APPLICATIONS_SUCCESS_CODE:
        # Stores the result
        url_string = response["response"]
        url_string = url_string["url"]
        download_oap(file_path, auth_token, url_string)
        return
    elif status_code == APPLICATION_VERSION_NO_PERMISSION_CODE:
        raise NotEnoughPermissionsError(
            "You don't have enough permissions to see the details of that application. Details: {}"
            .format(response["response"]))
    elif status_code == APPLICATION_VERSION_INVALID_CODE:
        raise AppVersionsError(
            "The request is invalid for the given keys. Details: {}".format(
                response["response"]))
    elif status_code == APPLICATION_VERSIONS_EMPTY_CODE:
        raise AppDoesNotExistError(
            "No binary available for given keys. Details: {}".format(
                response["response"]))
    elif status_code == APPLICATION_VERSION_FAILED_CODE:
        raise EnvironmentNotFoundError(
            "Failed to retrieve the application. Details: {}".format(
                response["response"]))
    elif status_code == APPLICATION_VERSION_FAILED_LIST_CODE:
        raise ServerError(
            "Failed to download the oap of the application version. Details: {}"
            .format(response["response"]))
    else:
        raise NotImplementedError(
            "There was an error. Response from server: {}".format(response))
def set_application_version(endpoint: str, auth_token: str, env_key: str,
                            app_key: str, change_log: str, app_version: str):
    query = "{}/{}/{}/{}/{}".format(ENVIRONMENTS_ENDPOINT, env_key,
                                    ENVIRONMENT_APPLICATIONS_ENDPOINT, app_key,
                                    APPLICATION_VERSIONS_ENDPOINT)

    version_request = {
        "ChangeLog": change_log,
        "Version": app_version,
        "MobileVersions": None
    }

    response = send_post_request(endpoint, auth_token, query,
                                 json.dumps(version_request))

    status_code = int(response["http_status"])
    if status_code == APPLICATION_VERSION_CREATE_SUCCESS_CODE:
        return response["response"]
    elif status_code == APPLICATION_VERSION_CREATE_INVALID_CODE:
        raise InvalidParametersError(
            "The request is invalid. Check the body of the request for errors. Body: {}. Details: {}."
            .format(version_request, response["response"]))
    elif status_code == APPLICATION_VERSION_CREATE_NO_PERMISSION_CODE:
        raise NotEnoughPermissionsError(
            "You don't have enough permissions to create the version. Details: {}"
            .format(response["response"]))
    elif status_code == APPLICATION_VERSION_CREATE_NO_ENVIRONMENT_CODE:
        raise EnvironmentNotFoundError(
            "Can't find the application or target environment. Details: {}.".
            format(response["response"]))
    elif status_code == APPLICATION_VERSION_CREATE_FAILED_CODE:
        raise ServerError(
            "Failed to tag an application, or Failed to create a new version. Details: {}"
            .format(response["response"]))
    else:
        raise NotImplementedError(
            "There was an error. Response from server: {}".format(response))