outline account controller interface

This commit is contained in:
Diogo Sousa
2023-01-26 13:33:53 +00:00
parent 83a5130340
commit ff979e3615
7 changed files with 164 additions and 32 deletions

View File

@@ -0,0 +1,88 @@
import logging
from typing import List, Dict
from pathlib import Path
from prompt_toolkit.completion import NestedCompleter
from openbb_terminal.featflags_controller import FeatureFlagsController
from openbb_terminal.parent_classes import BaseController
from openbb_terminal.rich_config import console, MenuText
from openbb_terminal.decorators import log_start_end
from openbb_terminal.core.config.paths import (
USER_ROUTINES_DIRECTORY,
)
from openbb_terminal import feature_flags as obbff
from openbb_terminal.menu import session
from openbb_terminal.session.user import User
logger = logging.getLogger(__name__)
class AccountController(BaseController):
"""Account Controller Class"""
CHOICES_COMMANDS = [
"sync",
"force",
"upload",
"download",
]
PATH = "/account/"
def __init__(self, queue: List[str] = None):
super().__init__(queue)
self.ROUTINE_FILES: Dict[str, Path] = {}
self.ROUTINE_CHOICES: Dict[str, None] = {}
self.update_runtime_choices()
def update_runtime_choices(self):
"""Update runtime choices"""
self.ROUTINE_FILES = {
filepath.name: filepath
for filepath in USER_ROUTINES_DIRECTORY.rglob("*.openbb")
}
self.ROUTINE_CHOICES = {filename: None for filename in self.ROUTINE_FILES}
if session and obbff.USE_PROMPT_TOOLKIT:
choices: dict = {c: {} for c in self.controller_choices}
choices["send"] = self.ROUTINE_CHOICES
self.completer = NestedCompleter.from_nested_dict(choices)
def print_help(self):
"""Print help"""
mt = MenuText("account/", 100)
mt.add_info("_info_")
mt.add_cmd("sync")
mt.add_cmd("force")
mt.add_raw("\n")
mt.add_info("_routines_")
mt.add_cmd("upload")
mt.add_cmd("download")
console.print(text=mt.menu_text, menu="Account")
@log_start_end(log=logger)
def call_sync(self, _):
"""Sync"""
FeatureFlagsController.set_feature_flag(
"OPENBB_SYNC_ENABLED", not obbff.SYNC_ENABLED, force=True
)
User.update_flair()
def call_force(self, _):
"""Force sync"""
console.print("Pull, Diff, Push")
pass
@log_start_end(log=logger)
def call_upload(self, _):
"""Upload"""
console.print("Upload routine")
pass
@log_start_end(log=logger)
def call_download(self, _):
"""Download"""
console.print("Download routine")
pass

View File

@@ -81,7 +81,7 @@ class FeatureFlagsController(BaseController):
console.print(text=mt.menu_text, menu="Feature Flags")
@staticmethod
def set_feature_flag(name: str, value: Union[bool, str]):
def set_feature_flag(name: str, value: Union[bool, str], force: bool = False):
"""Set feature flag
Parameters
@@ -90,8 +90,8 @@ class FeatureFlagsController(BaseController):
Environment variable name
value : str
Environment variable value
persist : bool, optional
Persist feature flag, by default False
force : bool, optional
Force set feature flag, by default False
"""
if User.is_guest():
@@ -105,7 +105,7 @@ class FeatureFlagsController(BaseController):
setattr(obbff, name, value)
# Send feature flag to server
if User.is_sync_enabled():
if User.is_sync_enabled() or force:
patch_user_configs(
key=name,
value=str(value),

View File

@@ -27,6 +27,8 @@ except ImportError:
else:
WITH_GIT = True
# Sync with OpenBB server
SYNC_ENABLED = load_env_vars("OPENBB_SYNC_ENABLED", strtobool, True, "featflags")
# Always overwrite exported files
FILE_OVERWITE = load_env_vars("OPENBB_FILE_OVERWRITE", strtobool, False, "featflags")

View File

@@ -16,6 +16,12 @@ en:
intro: introduction on the OpenBB Terminal
_configure_: Configure your own terminal
_main_menu_: Main menu
account/_info_: Synchronization
account/sync: Enable/disable sync
account/force: Force synchronization
account/_routines_: Routines
account/upload: Upload routine
account/download: Download routine
keys/_keys_: This menu allows you to set your own API keys. Type 'about' for more information
keys/mykeys: get your defined keys
keys/_status_: Status
@@ -88,7 +94,7 @@ en:
forecast: timeseries forecasting with machine learning
portfolio: perform portfolio optimization and look at portfolio performance and attribution
dashboards: interactive dashboards using voila and jupyter notebooks
stocks/filings: the most-recent form submissions to the SEC
stocks/filings: the most-recent form submissions to the SEC
stocks/search: search a specific stock ticker for analysis
stocks/load: load a specific stock ticker and additional info for analysis
stocks/_ticker: Stock

View File

@@ -8,6 +8,7 @@ from openbb_terminal import feature_flags as obbff
from openbb_terminal import config_terminal as cfg
from openbb_terminal import config_plot as cfg_plot
from openbb_terminal.base_helpers import strtobool
from openbb_terminal.session.user import User
SESSION_FILE_PATH = SETTINGS_DIRECTORY / "session.json"
@@ -84,23 +85,45 @@ def apply_configs(configs: dict):
The configurations.
"""
console.print(configs, style="red")
if configs:
keys = configs.get("features_keys", {})
if keys:
for k, v in keys.items():
if hasattr(cfg, k):
setattr(cfg, k, v)
# Since settings come from different files we use the format {var_name: "path:value"}
if configs:
settings = configs.get("features_settings", {})
if settings:
for k, v in settings.items():
if hasattr(obbff, k):
cast_set_attr(obbff, k, v)
elif hasattr(cfg, k):
cast_set_attr(cfg, k, v)
elif hasattr(cfg_plot, k):
cast_set_attr(cfg_plot, k, v)
obbff.SYNC_ENABLED = is_sync_enabled(settings)
User.update_flair()
if obbff.SYNC_ENABLED:
console.print("Applying...", style="red")
if settings:
for k, v in settings.items():
if hasattr(obbff, k):
cast_set_attr(obbff, k, v)
elif hasattr(cfg, k):
cast_set_attr(cfg, k, v)
elif hasattr(cfg_plot, k):
cast_set_attr(cfg_plot, k, v)
keys = configs.get("features_keys", {})
if keys:
for k, v in keys.items():
if hasattr(cfg, k):
setattr(cfg, k, v)
def is_sync_enabled(settings: dict) -> bool:
"""Check if sync is enabled.
Parameters
----------
settings : dict
The settings.
Returns
-------
bool
The status of sync.
"""
if settings.get("SYNC_ENABLED", "").lower() == "false":
return False
return True
def cast_set_attr(obj, name, value):

View File

@@ -10,7 +10,6 @@ class User:
_TOKEN: str = ""
_EMAIL: str = ""
_UUID: str = ""
_SYNC_ENABLED: bool = True
@classmethod
def load_user_info(cls, session: dict):
@@ -29,15 +28,21 @@ class User:
decoded_info = jwt.decode(User._TOKEN, options={"verify_signature": False})
User._EMAIL = decoded_info.get("sub", "")
MAX_FLAIR_LEN = 20
User.update_flair()
if obbff.USE_FLAIR == ":openbb":
username = User._EMAIL[: User._EMAIL.find("@")]
if User._SYNC_ENABLED:
flair = "[" + username[:MAX_FLAIR_LEN] + "] 🟢"
else:
flair = "[" + username[:MAX_FLAIR_LEN] + "] 🔴"
setattr(obbff, "USE_FLAIR", flair)
@staticmethod
def update_flair():
MAX_FLAIR_LEN = 20
username = User._EMAIL[: User._EMAIL.find("@")]
username = "[" + username[:MAX_FLAIR_LEN] + "]"
if obbff.USE_FLAIR == ":openbb" or username in obbff.USE_FLAIR:
if obbff.SYNC_ENABLED:
flair = username + " 🟢"
else:
flair = username + " 🔴"
setattr(obbff, "USE_FLAIR", flair)
@classmethod
def whoami(cls):
@@ -45,7 +50,7 @@ class User:
if User._UUID:
console.print(f"[info]email:[/info] {User._EMAIL}")
console.print(f"[info]uuid:[/info] {User._UUID}")
if User._SYNC_ENABLED:
if obbff.SYNC_ENABLED:
sync = "enabled"
else:
sync = "disabled"
@@ -70,12 +75,12 @@ class User:
@classmethod
def is_sync_enabled(cls):
"""Check if sync is enabled."""
return User._SYNC_ENABLED
return obbff.SYNC_ENABLED
@classmethod
def toggle_sync(cls):
"""Toggle sync."""
User._SYNC_ENABLED = not User._SYNC_ENABLED
obbff.SYNC_ENABLED = not obbff.SYNC_ENABLED
@classmethod
def get_token(cls):

View File

@@ -82,6 +82,7 @@ class TerminalController(BaseController):
"""Terminal Controller class."""
CHOICES_COMMANDS = [
"account",
"keys",
"settings",
"survey",
@@ -166,6 +167,7 @@ class TerminalController(BaseController):
mt.add_cmd("stop")
mt.add_raw("\n")
mt.add_info("_configure_")
mt.add_menu("account")
mt.add_menu("keys")
mt.add_menu("featflags")
mt.add_menu("sources")
@@ -354,6 +356,12 @@ class TerminalController(BaseController):
"https://openbb.co/products/terminal#get-started\n"
)
def call_account(self, _):
"""Process account command."""
from openbb_terminal.account.account_controller import AccountController
self.queue = self.load_class(AccountController, self.queue)
def call_keys(self, _):
"""Process keys command."""
from openbb_terminal.keys_controller import KeysController