diff --git a/slskd_api/apis/application.py b/slskd_api/apis/application.py index 7954859..db3e323 100644 --- a/slskd_api/apis/application.py +++ b/slskd_api/apis/application.py @@ -14,24 +14,26 @@ def state(self) -> dict: return response.json() -# Getting Error 'Unauthorized' even with admin API-Key: - # def stop(self): - # """ - # Stops the application. - # """ - # url = self.api_url + '/application' - # response = requests.delete(url, headers=self.header) - # return response.ok + def stop(self) -> bool: + """ + Stops the application. Only works with token (usr/pwd login). 'Unauthorized' with API-Key. + + :return: True if successful. + """ + url = self.api_url + '/application' + response = requests.delete(url, headers=self.header) + return response.ok -# Getting Error 'Unauthorized' even with admin API-Key: - # def restart(self): - # """ - # Restarts the application. - # """ - # url = self.api_url + '/application' - # response = requests.put(url, headers=self.header) - # return response.json() + def restart(self) -> bool: + """ + Restarts the application. Only works with token (usr/pwd login). 'Unauthorized' with API-Key. + + :return: True if successful. + """ + url = self.api_url + '/application' + response = requests.put(url, headers=self.header) + return response.ok def version(self) -> str: diff --git a/slskd_api/apis/options.py b/slskd_api/apis/options.py index 622f480..8d3ed3c 100644 --- a/slskd_api/apis/options.py +++ b/slskd_api/apis/options.py @@ -23,7 +23,7 @@ def get_startup(self) -> dict: return response.json() -# Getting error 'Unauthorized': +# Getting error 'Unauthorized'(API-Key) or 'Forbidden' (token): # def get_debug(self) -> dict: # """ # Gets the debug view of the current application options. diff --git a/slskd_api/client.py b/slskd_api/client.py index 8596f38..94d4aaa 100644 --- a/slskd_api/client.py +++ b/slskd_api/client.py @@ -10,6 +10,7 @@ class SlskdClient: """ The main class that allows access to the different APIs of a slskd instance. An API-Key with appropriate permissions (`readwrite` for most use cases) must be set in slskd config file. + Alternatively, provide your username and password. Usage:: slskd = slskd_api.SlskdClient(host, api_key, url_base) app_status = slskd.application.state() @@ -17,14 +18,23 @@ class SlskdClient: def __init__(self, host: str, - api_key: str, - url_base: str = '/' + api_key: str = None, + url_base: str = '/', + username: str = None, + password: str = None, ): api_url = reduce(urljoin, [host, f'{url_base}/', f'api/{API_VERSION}']) - header = { - 'accept': '*/*', - 'X-API-Key': api_key - } + + header = {'accept': '*/*'} + + if api_key: + header['X-API-Key'] = api_key + elif username and password: + header['Authorization'] = 'Bearer ' + \ + SessionApi(api_url, header).login(username, password)['token'] + else: + raise ValueError('Please provide an API-Key or a valid username/password pair.') + base_args = (api_url, header) self.application = ApplicationApi(*base_args)