Esempio n. 1
0
def getEndpoint(neptune_endpoint):
    session = boto3.session.Session()
    credentials = session.get_credentials()

    endpoints = Endpoints(credentials=credentials,
                          neptune_endpoint=neptune_endpoint,
                          neptune_port=8182,
                          region_name="us-east-1")
    sparqlEndpoint = endpoints.sparql_endpoint()
    return sparqlEndpoint
Esempio n. 2
0
 def post(self):
     endpoints = Endpoints()
     payload = []
     try:
         handler = tornado.escape.json_decode(self.request.body)
     except:
         handler = {}
     endpoint = handler.get("endpoint")
     payload = endpoints.match(self, endpoint)
     self.write(tornado.escape.json_encode(payload))
Esempio n. 3
0
 def post(self):
     endpoints = Endpoints()
     payload = []
     try:
         handler = tornado.escape.json_decode(self.request.body)
     except:
         handler = {}
     endpoint = handler.get('endpoint')
     payload = endpoints.match(self, endpoint)
     self.write(tornado.escape.json_encode(payload))
Esempio n. 4
0
 def _update_transactions(self):
     transactions = Endpoints.transactions_find()
     for transaction in transactions:
         log_id = transaction[const.T_LOG_ID]
         try:
             self._tables[const.TRANSACTIONS_DATA][log_id]
         except:
             self._tables[const.TRANSACTIONS_DATA] = {
                 **self._tables[const.TRANSACTIONS_DATA], log_id:
                 Endpoints.transaction_details(log_id)
             }
         time.sleep(0.2)
Esempio n. 5
0
def calculate_stats(date, game_id) -> Dict[str, Union[float, int]]:
    r = requests.get(Endpoints.box_score(date, game_id))
    r.raise_for_status()
    bs = r.json()

    r = requests.get(Endpoints.play_by_play(date, game_id))
    r.raise_for_status()
    pbp = r.json()

    stats = dict()
    stats.update(_calc_box_score_stats(bs))
    stats.update(_calc_play_by_play_stats(pbp))

    return stats
Esempio n. 6
0
def get_recenttransactions_response(name, session, intent):
    '''
        This response is build on the recenttransactions intent. Alexa will
        tell the user details about their most recent transaction.
    '''
    # ensure session attributes are passed on throughout the session
    session_attributes = session['attributes']

    transactions = Endpoints.list_transactions_by_owner(owner=name)

    recent_transaction = transactions[0]
    party = recent_transaction['counterParty']
    amount = recent_transaction['amount']
    type = recent_transaction['type']
    desc = recent_transaction['description']
    card_title = "RecentTransaction"

    line_1 = f"The party that hosted your transaction was {party}. "
    line_2 = f'The amount was {amount} cents. '
    line_3 = f'The transaction type was {type}. '
    line_4 = f'The description for the transaction is: {desc}. '

    speech_output = line_1 + line_2 + line_3 + line_4
    # If the user either does not reply to the welcome message or says something
    # that is not understood, they will be prompted again with this text.
    reprompt_text = speech_output
    should_end_session = False
    return build_response(
        session_attributes,
        build_speechlet_response(card_title, speech_output, reprompt_text,
                                 should_end_session))
Esempio n. 7
0
def get_sendmoney_response(name, session, intent):
    '''
        This is the response when the user wants to send money
    '''
    # ensure session attributes are passed on throughout the session
    session_attributes = session['attributes']
    
    # load intent values
    try:
        dest = intent['slots']['dest']['value']
        amount = intent['slots']['amount']['value']
        input_number = intent['slots']['number']['value']
        if type(input_number) == str:
            number = pos_to_int(input_number)
            
        speech_output = f"Sending {dest} {amount} cents from the {input_number} account"
    except:
        speech_output = "There was an error."
    
    res = Endpoints.transaction_between_users(
            sourceOwner=name,
            destinationOwner=dest,
            sourceAccountNumber=number,
            amount=amount)
    print(res)
    if res == 'Error':
        raise ValueError
        
    card_title = "SendMoney"
    reprompt_text = speech_output
    should_end_session = False
    return build_response(session_attributes, build_speechlet_response(
        card_title, speech_output, reprompt_text, should_end_session))
Esempio n. 8
0
def get_endpoints():
    """
    Get the Endpoints class object if one already exists, otherwise create one and save it

    :returns: the Endpoints class object
    """
    ep = getattr(g, 'endpoints', None)
    if ep is None:
        ep = g.endpoints = Endpoints()
    return ep
Esempio n. 9
0
 def get_transactions(self):
     '''
         This function will get every transaction from 'list_transactions' 
         and add it to the appropriate owner in self._tables.
     '''
     for owner in self._tables[const.OWNERS]:
         for account in self._tables[const.OWNERS][owner]:
             self._tables[const.OWNERS][owner][account][const.TRANSACTIONS] = \
                     Endpoints.list_transactions(accountID=account)[const.DATA]
     # stagger requests so they don't clog up database
     time.sleep(0.2)
Esempio n. 10
0
 def _create(self):
     '''
         This class extends Tablemap so that it can be accessed similarly
         to a dict. When a Tablemap object is created it will run the _create()
         function. Therefore, this function runs when the Connection object is
         created. It will grab all of the accounts and store it in self._tables
         by using 'list_accounts'
     '''
     self._key = const.DATA
     self._tables[const.ACCOUNTS] = \
         Endpoints.list_accounts()[const.DATA][const.ACCOUNTS]
Esempio n. 11
0
 def read(self, filename):
     try:
         with open(filename, 'r') as config_file_handle:
             config = json.load(config_file_handle)
             self.config_file_path = filename
             self.kubernetes = config['kubernetes']
             endpoints = Endpoints(config['endpoints'])
             self.container_names = config['kubernetes']['containers']
     except FileNotFoundError:
         logging.error(f'Config file {self.config_file_path} not found!'
                       'See example.config.json for config examples.')
     return endpoints
Esempio n. 12
0
 def _update_customers(self):
     customers = Endpoints.list_customers()
     for customer in customers:
         if customer:
             customer_id = customer[const.CUSTOMER_ID]
             try:
                 self._tables[const.CUSTOMER_DATA][customer_id]
             except:
                 del customer[const.CUSTOMER_ID]
                 self._tables[const.CUSTOMER_DATA] = {
                     **self._tables[const.CUSTOMER_DATA], customer_id:
                     customer
                 }
Esempio n. 13
0
def get_createaccount_response(name, session, intent):
    '''
        The user wishes to create an account
    '''
    # ensure session attributes are passed on throughout the session
    session_attributes = session['attributes']

    data = Endpoints.create_account(owner=name, balance=100)

    speech_output = f'Created an account for {name}. Your account has a balance of 100 cents.'
    # If the user either does not reply to the welcome message or says something
    # that is not understood, they will be prompted again with this text.
    reprompt_text = speech_output
    card_title = 'CreateAccount'
    should_end_session = False
    return build_response(
        session_attributes,
        build_speechlet_response(card_title, speech_output, reprompt_text,
                                 should_end_session))
Esempio n. 14
0
def get_accountbynumber_response(name, session, intent):
    """ This response is built when the accountbynumber intent is triggered.
        The user will request ('tell me about my first account') and this is
        the response.
    """
    # ensure session attributes are passed on throughout the session
    session_attributes = session['attributes']

    # the account the user wishes to access
    # if user wants to access the first account = accounts[0]
    input_number = intent['slots']['number']['value']

    number = pos_to_int(input_number)

    # load accounts by owner. if the function fails to find the owner name,
    # it will return with 'Error'

    data = Endpoints.accounts_by_owner(owner=name)
    if data != 'Error':
        accounts = data['accounts']
        num_accounts = len(accounts)

    if number == -1:
        speech_output = f'Account number out of bounds'
    elif data in ['Error']:
        speech_output = f'User {name} not found.'
    elif number <= num_accounts:
        balance = accounts[number]['balance']
        speech_output = f'The balance in your {input_number} account is {balance} cents'
    else:
        speech_output = f'{number} account not found.'

    card_title = "PosAccount"
    reprompt_text = speech_output
    should_end_session = False
    return build_response(
        session_attributes,
        build_speechlet_response(card_title, speech_output, reprompt_text,
                                 should_end_session))
Esempio n. 15
0
def rate_games(args) -> None:
    dates = set()
    if args.range:
        for r in args.range:
            start_date = min(r[0], r[1])
            end_date = max(r[0], r[1])
            while start_date <= end_date:
                dates.add(start_date)
                start_date += datetime.timedelta(days=1)
    dates.update(set(args.date))
    if not dates:
        dates.add(datetime.date.today() - datetime.timedelta(days=1))

    games = []
    for d in dates:
        r = requests.get(Endpoints.games(d))
        r.raise_for_status()
        games_data = r.json()
        for game in games_data['sports_content']['games']['game']:
            try:
                stats = calculate_stats(d, game['id'])
                rating, partial_ratings = calculate_rating(stats)
                stats.update(partial_ratings, rating=rating, id=game['id'], name=game['game_url'])
                games.append(stats)
            except Exception as e:
                print(e)
    if not games:
        return

    df = pd.DataFrame(games)
    df.sort_values('rating', ascending=False, inplace=True)

    if args.clipboard:
        df.to_clipboard()
    if args.output_csv:
        df.to_csv(args.output_csv)

    for index, row in df.iterrows():
        print(row['name'], row['rating'])
def get_accountlist_response(name, session):
    """ This is the response for the account list response. Alexa will tell you
        how many accounts you have.
    """
    # ensure session attributes are passed on throughout the session
    session_attributes = session['attributes']

    # attempt to load accounts with the owner name. If the owner name does not
    # have any accounts, the function will return with "Error"
    data = Endpoints.accounts_by_owner(owner=name)

    if data != 'Error':
        accounts = data['accounts']
        speech_output = f'You have {len(accounts)} accounts.'
    else:
        speech_output = f'User {name} not found.'

    card_title = "NumAccounts"
    reprompt_text = speech_output
    should_end_session = False
    return build_response(
        session_attributes,
        build_speechlet_response(card_title, speech_output, reprompt_text,
                                 should_end_session))
Esempio n. 17
0
 def _update_store(self):
     store = Endpoints.get_store()
     self._tables[const.STORE_DATA] = {store[const.API_STORE_ID]: store}
Esempio n. 18
0
class RobinhoodAPI():

    CLIENT_ID = "c82SH0WZOsabOXGP2sxqcj34FxkvfnWRZBKlBjFS"  #constant
    username = None
    password = None
    session = None
    access_token = None
    refresh_token = None

    endpoint_manager = Endpoints()

    def __init__(self):
        self.session = requests.Session()

        self.session.headers = {
            "Accept": "*/*",  #accept any type
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "en-US,en;q=0.9",
            "User-Agent":
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
            "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
            "X-Robinhood-API-Version": "1.265.0",
            "Connection": "keep-alive"
        }

        print("input your login credentials below")
        is_logged_in = self.login()

        while (is_logged_in == False):
            print("incorrect credentials, try again!")
            is_logged_in = self.login()

        print("Login succesful")

    #as of now, we aren't doing any checking for the case that the user has 2FA enabled, but maybe later
    def login(self):
        self.username = input("Username: "******"client_id": self.CLIENT_ID,
            "grant_type": "password",
            "password": self.password,
            "username": self.username
        }

        response = self.session.post(self.endpoint_manager.login_endpoint(),
                                     data=login_payload)
        response_data = response.json

        if (response.status_code !=
                200):  #error checking for correct credentials
            return False

        if 'access_token' in response_data.keys(
        ) and 'refresh_token' in response_data.keys():
            self.access_token = response_data['access_token']
            self.refresh_token = response_data['refresh_token']
            return True

        return False
Esempio n. 19
0
    day = transaction[const.BUSINESS_DAY][const.DATE_TIME]

    return f'Amount: {amount}, Time: {day}'


if __name__ == '__main__':

    # init context
    _LOGGER.info('initializing context')
    from context.context import Context
    Context.initialize(CONFIG_FILE_PATH)

    # init endpoints
    _LOGGER.info('initializing endpoints')
    from endpoints import Endpoints
    Endpoints.initialize()

    # init firebase
    _LOGGER.info('initializing firebase')
    import firebase_admin
    from firebase_admin import credentials
    from firebase_admin import db
    with FIREBASE_CRED_PATH.open() as file:
        FIREBASE_DATA = json.loads(file.read())
        cred = credentials.Certificate(FIREBASE_DATA)

    firebase_admin.initialize_app(
        cred, {const.DB_URL: Context.data()[const.FIREBASE][const.DB_URL]})

    _LOGGER.info('initializing storage')
    from storage.storage import Storage
Esempio n. 20
0
class RobinhoodAPI():
  
  CLIENT_ID = "c82SH0WZOsabOXGP2sxqcj34FxkvfnWRZBKlBjFS" #constant
  username = None
  password = None
  session = None
  access_token = None  #the auth token
  refresh_token = None 
  #to find this device token, log out robinhood on your browser,
  #inspect, go to network, and where it says filter, type token
  #log in to robinhood and click on token, then go down to 
  #request payload, where you'll see the device token
  DEVICE_TOKEN = "bd16f778-5814-4f14-9e5c-e7b053584529"
  user_account_number = None

  endpoint_manager = Endpoints()

  def __init__(self):
    self.session = requests.Session()

    self.session.headers = {
      "Accept": "*/*", #accept any type
      "Accept-Encoding": "gzip, deflate, br",
      "Accept-Language": "en-US,en;q=0.9",
      "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36",
      "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
      "X-Robinhood-API-Version": "1.265.0",
      "Connection": "keep-alive"
    }
    
    print("input your login credentials below")
    is_logged_in = self.login()

    while(is_logged_in == False):
      print("incorrect credentials, try again!")
      is_logged_in = self.login()

    print("Login succesful")

    self.get_user_account_info()


  #as of now, we aren't doing any checking for the case that the user has 2FA enabled, but maybe later
  def login(self):
    self.username = input("Username: "******"Password: "******"grant_type": "password",
      "scope": "internal",
      "client_id": self.CLIENT_ID,
      "expires_in": 86400,
      "device_token": self.DEVICE_TOKEN,
      "password": self.password,
      "username": self.username
    }

    response = self.session.post(self.endpoint_manager.login_endpoint(), data=login_payload)
    response_data = response.json()

    if(response.status_code != 200): #error checking for correct credentials
      return False


    if 'access_token' in response_data.keys() and 'refresh_token' in response_data.keys():
      self.access_token = response_data['access_token']
      self.refresh_token = response_data['refresh_token']
      self.session.headers['Authorization'] = 'Bearer ' + self.access_token
      return True
    
    return False


  def pretty_print_response(self, json_response):
    print(json.dumps(json_response, indent=4))


  #################### GETTING USER DATA ####################

  def get_transfer_history(self):
    response = self.session.get(self.endpoint_manager.transfers(), timeout=15)
    # response.raise_for_status()

    response_data = response.json()

    transfer_history = response_data['results']

    self.pretty_print_response(transfer_history)


  def get_dividends(self):
    response = self.session.get(self.endpoint_manager.dividends(), timeout=15)

    response_data = response.json()

    dividends_history = response_data['results']
    
    self.pretty_print_response(dividends_history)



  def get_user_account_info(self, print_info = False):
    response = self.session.get(self.endpoint_manager.account_info())

    response_data = response.json()

    if 'account_number' in response_data['results'][0].keys():
      self.user_account_number = response_data['results'][0]['account_number']

    if(print_info):
      self.pretty_print_response(response_data['results'][0])



  def get_user_portfolio(self):
    response = self.session.get(self.endpoint_manager.portfolio(self.user_account_number))

    response_data = response.json()

    self.pretty_print_response(response_data)

  
  def get_user_positions(self):
    response = self.session.get(self.endpoint_manager.positions(self.user_account_number))

    response_data = response.json()

    self.pretty_print_response(response_data)
  


  #################### GET ROBINHOOD DATA ####################

  def get_current_top_movers(self): #this doesn't provide their market data
    response = self.session.get(self.endpoint_manager.top_movers(), timeout=15)

    response_data = response.json()

    top_movers_list = response_data['instruments'] 

    for x in top_movers_list:
      self.get_instrument(x)


  #this accepts only instrument (stock) endpoint. this wont work with just a stock
  def get_instrument(self, instrument_endpoint):
    inst_response = self.session.get(instrument_endpoint, timeout=15)
    response_data = inst_response.json()

    self.pretty_print_response(response_data)


  def get_stock_news(self, stock_ticker):
    response = self.session.get(self.endpoint_manager.stock_news(stock_ticker.upper()))

    response_data = response.json()

    self.pretty_print_response(response_data)
    
  
  def get_stock_data(self, stock_ticker):

    stock_id = self.get_stock_endpoint(stock_ticker)

    if(len(stock_id) == 0):
      print("no such stock ticker")
      return

    response = self.session.get(self.endpoint_manager.stock_data(stock_id), timeout=15)

    response_data = response.json()

    self.pretty_print_response(response_data)
    

  def get_stock_endpoint(self, stock_ticker):
    #look up how the queries work
    response = self.session.get(self.endpoint_manager.instruments(), params={'query': stock_ticker.upper()}, timeout=15)
    

    response_data = response.json()
    
    response_results = response_data['results'][0]
    
    return response_results['id']
Esempio n. 21
0
    logging.basicConfig(level=env.LOGGING_LEVEL,
                        format='%(asctime)s %(message)s')

_LOGGER = logging.getLogger(__name__)

if __name__ == '__main__':

    # init context
    _LOGGER.info('initializing context')
    from context.context import Context
    Context.initialize(CONFIG_FILE_PATH)

    # init endpoints
    _LOGGER.info('initializing endpoints')
    from endpoints import Endpoints
    Endpoints.initialize()

    # Endpoints.post_transaction(
    #     accountID='88efgiTlszS1z2TqSlPj',
    #     counterParty='suntrust',
    #     transactionType='debit',
    #     description='ATM Withdrawal',
    #     amount='20'
    # )

    # Endpoints.post_transaction(
    #     accountID='88efgiTlszS1z2TqSlPj',
    #     counterParty='suntrust',
    #     transactionType='credit',
    #     description='ATM Deposit',
    #     amount='100'
Esempio n. 22
0
#!/usr/bin/env python
from tornado.log import enable_pretty_logging
from endpoints import Endpoints, jobs_handler
import tornado.ioloop
import tornado.web
import settings
import logging
import urls

enable_pretty_logging()
endpoints = Endpoints()

endpoints.register('jobs', jobs_handler)


def create_app():
    return tornado.web.Application(urls.base_urls, **settings.APP)


if __name__ == '__main__':
    app = create_app()
    app.listen(settings.PORT)
    tornado.ioloop.IOLoop.current().start()