maubot/maubot/cli/config.py

67 lines
2.1 KiB
Python
Raw Normal View History

2018-12-12 23:28:23 +00:00
# maubot - A plugin-based Matrix bot system.
2019-06-08 14:42:07 +00:00
# Copyright (C) 2019 Tulir Asokan
2018-12-12 23:28:23 +00:00
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from typing import Tuple, Optional, Dict, Any
2018-12-12 23:28:23 +00:00
import json
import os
2018-12-13 22:33:33 +00:00
from colorama import Fore
config: Dict[str, Any] = {
2018-12-13 18:48:52 +00:00
"servers": {},
"default_server": None,
2018-12-12 23:28:23 +00:00
}
configdir = os.environ.get("XDG_CONFIG_HOME", os.path.join(os.environ.get("HOME"), ".config"))
2018-12-13 22:33:33 +00:00
def get_default_server() -> Tuple[Optional[str], Optional[str]]:
try:
server: Optional[str] = config["default_server"]
2018-12-13 22:33:33 +00:00
except KeyError:
server = None
if server is None:
print(f"{Fore.RED}Default server not configured.{Fore.RESET}")
return None, None
return server, _get_token(server)
2018-12-13 22:33:33 +00:00
def get_token(server: str) -> Tuple[Optional[str], Optional[str]]:
if not server:
return get_default_server()
return server, _get_token(server)
def _get_token(server: str) -> Optional[str]:
2018-12-13 22:33:33 +00:00
try:
return config["servers"][server]
except KeyError:
print(f"{Fore.RED}No access token saved for {server}.{Fore.RESET}")
return None
2018-12-12 23:28:23 +00:00
def save_config() -> None:
with open(f"{configdir}/maubot-cli.json", "w") as file:
json.dump(config, file)
def load_config() -> None:
try:
with open(f"{configdir}/maubot-cli.json") as file:
loaded = json.load(file)
config["servers"] = loaded["servers"]
2018-12-13 18:48:52 +00:00
config["default_server"] = loaded["default_server"]
2018-12-12 23:28:23 +00:00
except FileNotFoundError:
pass