Files
OpenBB/openbb_terminal/sources_controller.py
montezdesousa 5953be0a42 Terminal authentication + keys/settings/routines (#4015)
* import order

* pylint

* no login, go to prompt

* add logout and whoami

* clear before prompt

* black

* these are unecessary

* error

* improve login prompt message

* login does not follow the controller pattern, so will name it differently

* nop

* move logout and change to results

* change return obj

* ruff

* pyupgrade

* remove user from statics

* message

* fetch configs at start

* remove unecessary func

* unecessary dataclass

* change user vars

* change login flow

* remote logout should not be used

* simplify

* fix double exit logout bug

* wrong exception

* apply keys

* change controller

* mypy

* save if no internet

* pylint

* logout everywhere

* breaking changes: move to local/hub models

* unused import

* fix logout bug

* whoami in guest mode

* add todo

* small bug guest allowed

* limit flair length

* fix bug on user pull

* logout working

* handle no connection

* logout user when logout

* remove keys push

* split logger funcs

* commant apply configs for now

* account to session

* rename user

* clear sounds better

* breaking changes: splitting guest from logged users

* pull imports up

* delete session model

* move logout func

* add ability to save and apply keys from remote

* no sensitive keys

* add support for feature flags

* unecessary print

* allow settings from differnt modules

* change setff to static

* change way to set ff

* fix bug in applying configs

* simplify obbff application

* bug on setting configs

* allow text ff

* obbff in settings

* add upload to cfg_plot 1

* data sources + backend

* this solves circular import?

* move create_session to model

* rever logs changes, not needed for now

* sync optionally

* outline account controller interface

* don't sync when guest

* block guest on installer

* or not and

* start routines

* fix bug on ff, settings

* is installer

* implementing chavi suggestions

* fix colors on installer prompt

* Logging login (#4046)

* basic logging for the login

* removing unused import

* hacking the logs custom filter to not filter the email

* black

* cooping with the new changes

* removing redundant method

* ruff

* ruff

* mypy

* SDK login (#4051)

* sdk login

* adding to the trail map

* minor fix

* improve sdk expirience

* adapting to new changes

* add docstrings

* block guest from account

* change guest msg

* change guest messages

* add sync on/off

* display onoff

* missing paragraph

* fix glitch on logout

* add sys clear

* filtering password

* filtering the email from user

* avoid writing to multiple log files if a user logs out

* fix bug, guest allowed in installer without connection

* log user on the sdk

* split login from lauch

* add clear and change messages on account

* docstrings

* start pull cmd

* change account menu description

* Fix login bug and decouple some logic (#4056)

* fix bug, guest allowed in installer without connection

* split login from lauch

* improvements on the sdk login

---------

Co-authored-by: hjoaquim <h.joaquim@campus.fct.unl.pt>

* sync fix

* change account controller description

* ruff

* add help on account cmds

* update clear prompt

* fix email not in jwt

* remove jwt from requiremnts

* pull command output

* remove character

* pull cmd when no data

* add space below whoami

* fix log filenotfound exception

* changed arg name

* delete .hist on logout

* add asteriscs to password

* pylint

* uncomment rich config

* show only diffs on pull

* black#

* warn when no changes#

* pull msg was switched

* apply diff only

* breaking?: strbool change

* reduce some code

* add timeout to hub requests

* black

* add remote logout

* success msg only if success

* remove colors in prompt

* update docstrings

* keep timeout outside funcs

* update clear

* clear and patch

* delete session

* routine upload

* move .his file to .openbb folder

* change apply configs

* refactor logout

* remove mixed portfolio changes

* fix bug in lock file

* fix bug pwidth, pheight are floats

* fix sources command & add choices

* refactor timezone setting

* userdata

* fix flair

* need to cast paths

* cast on diff

* fix flair default

* save session test

* get session

* data

* test remove

* test remove with assert

* add bad test cases

* add exception cases to unittests

* test remove cli hist file

* black

* test apply configs

* test apply with sync flag

* test create session, session model

* login tests, session model

* some tests for the hub_model

* test logout user

* black

* test clear vars, reload

* test create session

* update user-json to user

* update user class

* add user tests

* tests sdk session

* tests for hub_model

* start account controller tsts

* unused import

* tests account controller: clear, pull

* tests for session_controller

* logout success bugfix

* add integration test for account

* black

* move routine related commands to other PR

* test for the user input

* completed tests for session controller

* convert to hist to str)

* fix import errors

* ruff

* ruff tests

* fix qa

* add help to settings cmds

* ruff

* fix pull keys bug

* point to dev

* account model tests

* black

* ruff

* fix for empty feature settings

* ruff

* don't display config msg if wrong token

* general msgs

* remove print

* ruff

* fix sources not updated real time

* missing return doc

* add guest if no email

* Routine remote storage (#4143)

* add upload routine command

* remove prints

* point to local again

* add commands

* add delete

* add download command and upload 409

* list comprehension

* add download & save plus upload fixe

* add user uuid folder

* add list command

* ruff

* en.yml detail

* provide choices to delete & download

* add choices to upload

* change menu text

* starting adding unit tests

* bad english

* Update test_print_help.txt

* genearl msgs

* remove print

* add docstrings

* add unit tests to account controller

* change parser

* fix routine upload test

* add to be implemented tests hub

* add to be implemented tests local

* add total pages to title

* split list into model and view

* add docstring

* print msg if character

* add local model tests

* hub tests routines

* fix test

* point to dev and glob

* fix small bug on upload

* missing return

* log decorators missing

* black

* ruff

* change prompt display

* rewrite test

* rewrite expected

* rewrite call

* try passing git action

* change .yml everywhere

---------

Co-authored-by: Henrique Joaquim <h.joaquim@campus.fct.unl.pt>
Co-authored-by: James Maslek <jmaslek11@gmail.com>
2023-02-09 13:35:44 +00:00

267 lines
11 KiB
Python

"""Sources Controller Module"""
__docformat__ = "numpy"
# IMPORTATION STANDARD
import argparse
import json
import logging
import os
from pathlib import Path
from typing import Dict, List
# IMPORTATION THIRDPARTY
# IMPORTATION INTERNAL
from openbb_terminal import feature_flags as obbff
from openbb_terminal.core.config.paths import USER_DATA_SOURCES_DEFAULT_FILE
from openbb_terminal.custom_prompt_toolkit import NestedCompleter
from openbb_terminal.decorators import log_start_end
from openbb_terminal.menu import session
from openbb_terminal.parent_classes import BaseController
from openbb_terminal.rich_config import MenuText, console
# pylint: disable=too-many-lines,no-member,too-many-public-methods,C0302
# pylint:disable=import-outside-toplevel
logger = logging.getLogger(__name__)
def unique(sequence):
seen = set()
return [x for x in sequence if not (x in seen or seen.add(x))]
class SourcesController(BaseController):
"""Sources Controller class"""
CHOICES_COMMANDS: List[str] = [
"get",
"set",
]
PATH = "/sources/"
def __init__(self, queue: List[str] = None):
"""Constructor"""
super().__init__(queue)
self.commands_with_sources: Dict[str, List[str]] = {}
self.load_sources_json()
if session and obbff.USE_PROMPT_TOOLKIT:
choices: dict = {c: {} for c in self.controller_choices}
choices["get"] = {c: None for c in list(self.commands_with_sources.keys())}
choices["set"] = {c: None for c in list(self.commands_with_sources.keys())}
for cmd in list(self.commands_with_sources.keys()):
choices["set"][cmd] = {c: None for c in self.commands_with_sources[cmd]}
self.completer = NestedCompleter.from_nested_dict(choices)
def load_sources_json(self):
"""Load the .json file"""
# Loading in both source files: default sources and user sources
default_data_source = USER_DATA_SOURCES_DEFAULT_FILE
user_data_source = Path(obbff.PREFERRED_DATA_SOURCE_FILE)
# Opening default sources file from the repository root
with open(str(default_data_source)) as json_file:
self.json_doc = json.load(json_file)
# If the user has added sources to their own sources file in OpenBBUserData, then use that
if (
not os.getenv("TEST_MODE")
and user_data_source.exists()
and user_data_source.stat().st_size > 0
):
with open(str(user_data_source)) as json_file:
self.json_doc = json.load(json_file)
for context in self.json_doc:
for menu in self.json_doc[context]:
if isinstance(self.json_doc[context][menu], Dict):
for submenu in self.json_doc[context][menu]:
if isinstance(self.json_doc[context][menu][submenu], Dict):
for subsubmenu in self.json_doc[context][menu][submenu]:
self.commands_with_sources[
f"{context}_{menu}_{submenu}_{subsubmenu}"
] = self.json_doc[context][menu][submenu][subsubmenu]
else:
self.commands_with_sources[
f"{context}_{menu}_{submenu}"
] = self.json_doc[context][menu][submenu]
else:
self.commands_with_sources[f"{context}_{menu}"] = self.json_doc[
context
][menu]
def print_help(self):
"""Print help"""
mt = MenuText("sources/")
mt.add_info("_info_")
mt.add_cmd("get")
mt.add_cmd("set")
console.print(text=mt.menu_text, menu="Data Sources")
@log_start_end(log=logger)
def call_get(self, other_args):
"""Process get command"""
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="get",
description="Get sources associated with a command and the one selected by default, using 'get <command>'.",
)
parser.add_argument(
"-c",
"--cmd",
action="store",
dest="cmd",
choices=list(self.commands_with_sources.keys()),
required="-h" not in other_args,
help="Command that we want to check the available data sources and the default one.",
metavar="COMMAND",
)
if other_args and "-" not in other_args[0][0]:
other_args.insert(0, "-c")
ns_parser = self.parse_simple_args(parser, other_args)
if ns_parser:
self.load_sources_json()
try:
the_item = self.commands_with_sources[ns_parser.cmd]
except KeyError:
console.print(
[f"[red]'{ns_parser.cmd}' is not a valid command.[/red]\n"]
)
return
if the_item:
console.print(
f"\n[param]Default :[/param] {self.commands_with_sources[ns_parser.cmd][0]}"
)
console.print(
f"[param]Available :[/param] {', '.join(self.commands_with_sources[ns_parser.cmd])}\n"
)
else:
console.print("This command has no data sources available.\n")
# pylint: disable=R0912
@log_start_end(log=logger)
def call_set(self, other_args):
"""Process set command"""
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="set",
description="Set a default data sources associated with a command, using 'set <command> <source>'.",
)
parser.add_argument(
"-c",
"--cmd",
action="store",
dest="cmd",
choices=list(self.commands_with_sources.keys()),
help="Command that we to select the default data source.",
metavar="COMMAND",
)
parser.add_argument(
"-s",
"--source",
action="store",
dest="source",
type=str,
help="Data source to use by default on specified command.",
)
if other_args and "-" not in other_args[0][0]:
other_args.insert(0, "-c")
if "-s" not in other_args and "--source" not in other_args:
other_args.insert(2, "-s")
ns_parser = self.parse_simple_args(parser, other_args)
if ns_parser:
self.load_sources_json()
menus = ns_parser.cmd.split("_")
num_menus = len(menus)
success = True
valid_sources = list()
# Update dictionary
if num_menus == 1:
if ns_parser.source not in self.json_doc[menus[0]]:
success = False
valid_sources = self.json_doc[menus[0]]
else:
self.json_doc[menus[0]] = unique(
[ns_parser.source] + self.json_doc[menus[0]]
)
elif num_menus == 2:
if ns_parser.source not in self.json_doc[menus[0]][menus[1]]:
success = False
valid_sources = self.json_doc[menus[0]][menus[1]]
else:
self.json_doc[menus[0]][menus[1]] = unique(
[ns_parser.source] + self.json_doc[menus[0]][menus[1]]
)
elif num_menus == 3:
if ns_parser.source not in self.json_doc[menus[0]][menus[1]][menus[2]]:
success = False
valid_sources = self.json_doc[menus[0]][menus[1]][menus[2]]
else:
self.json_doc[menus[0]][menus[1]][menus[2]] = unique(
[ns_parser.source] + self.json_doc[menus[0]][menus[1]][menus[2]]
)
elif num_menus == 4:
if (
ns_parser.source
not in self.json_doc[menus[0]][menus[1]][menus[2]][menus[3]]
):
success = False
valid_sources = self.json_doc[menus[0]][menus[1]][menus[2]][
menus[3]
]
else:
self.json_doc[menus[0]][menus[1]][menus[2]][menus[3]] = unique(
[ns_parser.source]
+ self.json_doc[menus[0]][menus[1]][menus[2]][menus[3]]
)
if success:
try:
with open(obbff.PREFERRED_DATA_SOURCE_FILE, "w") as f:
json.dump(self.json_doc, f, indent=4)
console.print(
"[green]The data source was specified successfully.\n[/green]"
)
# Update dictionary so if we "get" the change is reflected
for context in self.json_doc:
for menu in self.json_doc[context]:
if isinstance(self.json_doc[context][menu], Dict):
for submenu in self.json_doc[context][menu]:
if isinstance(
self.json_doc[context][menu][submenu], Dict
):
for subsubmenu in self.json_doc[context][menu][
submenu
]:
self.commands_with_sources[
f"{context}_{menu}_{submenu}_{subsubmenu}"
] = self.json_doc[context][menu][submenu][
subsubmenu
]
else:
self.commands_with_sources[
f"{context}_{menu}_{submenu}"
] = self.json_doc[context][menu][submenu]
else:
self.commands_with_sources[
f"{context}_{menu}"
] = self.json_doc[context][menu]
except Exception as e:
console.print(
f"[red]Failed to write preferred data sources to file: "
f"{obbff.PREFERRED_DATA_SOURCE_FILE}[/red]"
)
console.print(f"[red]{e}[/red]")
else:
console.print(
f"[red]The data source selected is not valid, select one from: {', '.join(valid_sources)}.\n[/red]"
)