Files
OpenBB/openbb_terminal/core/session/local_model.py
montezdesousa 475ebb5acd [WIP] Migrate user, feature flags and configurations to dataclass (#4309)
* implement user and change is guest

* replace User methods

* move remaining functions to user

* fix bug

* portfolio test

* fix tests

* fix tests

* uncomment skip

* ruff

* start credentials model implementation

* change deault structure

* refacto quandl

* change default struct and file names

* bug

* start using global user

* add comments

* move update flair

* change cfg references in keys model

* reddit & fmp

* refactore additional keys

* remaing config keys

* remove unsude imports and fix hub keys

* ruff

* fix line too long

* unblock unittests

* fix keys model tests

* remove os patch

* fix account controller tests

* fix account controller tests

* fix account model

* account fixed

* fix user tests

* User Model

* User Model

* User Model

* Move session folder

* User Model : grouping the models

* User Model : fix bugs

* Config Plot + bug fix

* User Model : Refactoring plots

* Feature flags

* Remove dup

* clean comments a fix some vars

* fix feature flags controller

* refactor obbff from settings controller

* refactor a bunch of obbff variables

* fix bug blocking terminal

* fix integration tests

* refactor controllers with obbff

* refactor remaining ffs

* remove comments

* log not started

* mispelled variable

* set current user on local model

* User Model : moving files + updating

* User Preferences

* User : Refactor is_guest function + bug fix

* User : refactor is_guest function

* Fix conftest.py

* remove lost obbffs

* typo on fileoverwrite

* Plot config: move variables and start plot dpi

* User : tests

* refactor plot dpi references

* remove plot dpi imports

* refactor some config terminal leftover

* /account/sync : fix bug

* remove configs reload

* start path refactor

* installation paths vs user paths

* remove cfg_plot

* Tests : User Refactoring

* user prefix only for preferences

* user prefix only for preferences

* move user paths

* remove comment

* update apply remote configs

* fix tz not updating

* save some copys

* small fix

* create interface for credentials and preferences

* wrong docstrings fixed

* ruff core

* fix some pref setting

* login is better

* ruff

* ruff

* remove Literal

* add small comment

* Tests : User Refactoring

* Credentials Model : add DataBento

* Fix helper_funcs

* Fixing code

* Tests : fixing

* User Model : freezing the models

* Fixed Income + Databento

* Tests : fixing keys

* black

* ruff

* Tests : user model

* Tests : user model

* Fix linting

* Fix linting

* Linting

* Linting

* Fixing code and tests

* Fix tests

* mypy

* SDK

* Clean ruff cache

* Fix syntax issue

* Update fred_view

* Black

* Linting

* Update code

* Update tests

* Linting

* Linting

* Tests

* Black

* Linting

* Linting

* Mock os.listdir to avoid looking for file that doesnt exist

* Mock options paths

* lint

* Tests : fix

* Code : update

* Tests + Linting

* Tests

* Ruff

* Code : update

* Tests

* Code : update

* Fix workflow

* Code : update

---------

Co-authored-by: Chavithra PARANA <chavithra@gmail.com>
Co-authored-by: luqazino@gmail.com <luqazino@gmail.com>
Co-authored-by: James Maslek <jmaslek11@gmail.com>
2023-03-05 00:37:19 +01:00

222 lines
5.1 KiB
Python

import json
import os
from pathlib import Path
from typing import Optional, Union
from openbb_terminal.core.config.paths import (
HIST_FILE_PATH,
SETTINGS_DIRECTORY,
)
from openbb_terminal.core.session.credentials_handler import set_credential
from openbb_terminal.core.session.current_user import get_current_user
from openbb_terminal.core.session.preferences_handler import set_preference
from openbb_terminal.rich_config import console
SESSION_FILE_PATH = SETTINGS_DIRECTORY / "session.json"
def save_session(data: dict, file_path: Path = SESSION_FILE_PATH):
"""Save the login info to a file.
Parameters
----------
data : dict
The data to write.
file_path : Path
The file path.
"""
try:
with open(file_path, "w") as file:
file.write(json.dumps(data))
except Exception:
console.print("[red]Failed to save session info.[/red]")
def get_session(file_path: Path = SESSION_FILE_PATH) -> dict:
"""Get the session info from the file.
Parameters
----------
file_path : Path
The file path.
Returns
-------
dict
The session info.
"""
try:
if os.path.isfile(file_path):
with open(file_path) as file:
return json.load(file)
except Exception:
console.print("\n[red]Failed to get login info.[/red]")
return {}
def remove_session_file(file_path: Path = SESSION_FILE_PATH) -> bool:
"""Remove the session file.
Parameters
----------
file_path : Path
The file path.
Returns
-------
bool
The status of the removal.
"""
try:
if os.path.isfile(file_path):
os.remove(file_path)
return True
return True
except Exception:
console.print("\n[red]Failed to remove login file.[/red]")
return False
def remove_cli_history_file(file_path: Path = HIST_FILE_PATH) -> bool:
"""Remove the cli history file.
Parameters
----------
file_path : Path
The file path.
Returns
-------
bool
The status of the removal.
"""
try:
if os.path.isfile(file_path):
os.remove(file_path)
return True
return True
except Exception:
console.print("\n[red]Failed to remove terminal history file.[/red]")
return False
def apply_configs(configs: dict):
"""Apply configurations.
Parameters
----------
configs : dict
The configurations.
"""
if configs:
settings = configs.get("features_settings", {})
sync = update_sync_flag(settings)
if sync:
if settings:
for k, v in settings.items():
set_preference(k, v, login=True)
keys = configs.get("features_keys", {})
if keys:
for k, v in keys.items():
set_credential(k, v, login=True)
def update_sync_flag(settings: dict) -> bool:
"""Update the sync flag.
Parameters
----------
settings : dict
The settings.
Returns
-------
bool
The sync flag.
"""
sync = not (settings and settings.get("SYNC_ENABLED", "true").lower() == "false")
set_preference("SYNC_ENABLED", sync, login=True)
return sync
def get_routine(file_name: str, folder: Optional[Path] = None) -> Optional[str]:
"""Get the routine.
Returns
-------
file_name : str
The routine.
folder : Optional[Path]
The routines folder.
"""
current_user = get_current_user()
if folder is None:
folder = current_user.preferences.USER_ROUTINES_DIRECTORY
try:
user_folder = folder / current_user.profile.get_uuid()
file_path = (
user_folder / file_name
if os.path.exists(user_folder / file_name)
else folder / file_name
)
with open(file_path) as f:
routine = "".join(f.readlines())
return routine
except Exception:
console.print("[red]Failed to find routine.[/red]")
return None
def save_routine(
file_name: str,
routine: str,
folder: Optional[Path] = None,
force: bool = False,
) -> Union[Optional[Path], str]:
"""Save the routine.
Parameters
----------
file_name : str
The routine.
routine : str
The routine.
folder : Path
The routines folder.
force : bool
Force the save.
Returns
-------
Optional[Path, str]
The path to the routine or None.
"""
current_user = get_current_user()
if folder is None:
folder = current_user.preferences.USER_ROUTINES_DIRECTORY
try:
uuid = current_user.profile.get_uuid()
user_folder = folder / uuid
if not os.path.exists(user_folder):
os.makedirs(user_folder)
file_path = user_folder / file_name
if os.path.exists(file_path) and not force:
return "File already exists"
with open(file_path, "w") as f:
f.write(routine)
return user_folder / file_name
except Exception:
console.print("[red]\nFailed to save routine.[/red]")
return None