rename api endpoints

This commit is contained in:
Alex Grintsvayg 2017-01-03 14:13:01 -05:00
parent a67aab0797
commit 962edb8e4c
8 changed files with 575 additions and 513 deletions

5
.gitignore vendored
View file

@ -9,12 +9,11 @@
/build
/dist
/lbrynet.egg-info
.idea/.name
.coverage
.DS_Store
lbrynet.egg-info/PKG-INFO
# temporary files from the twisted.trial test runner
_trial_temp/
_trial_temp/

5
FAQ.md
View file

@ -77,8 +77,9 @@ Note: the lbry api can only be used while either the app or lbrynet-daemon comma
sys.exit(0)
api = JSONRPCProxy.from_url(API_CONNECTION_STRING)
if not api.is_running():
print api.daemon_status()
status = api.status()
if not status['is_running']:
print status
else:
for func in api.help():
print "%s:\n%s" % (func, api.help({'function': func}))

View file

@ -49,8 +49,9 @@ except:
API_CONNECTION_STRING = "http://localhost:5279/lbryapi"
api = JSONRPCProxy.from_url(API_CONNECTION_STRING)
if not api.is_running():
print api.daemon_status()
status = api.status()
if not status['is_running']:
print status
else:
for func in api.help():
print "%s:\n%s" % (func, api.help({'function': func}))

View file

@ -182,10 +182,6 @@ class Wallet(object):
"""This class implements the Wallet interface for the LBRYcrd payment system"""
implements(IWallet)
_FIRST_RUN_UNKNOWN = 0
_FIRST_RUN_YES = 1
_FIRST_RUN_NO = 2
def __init__(self, storage):
if not isinstance(storage, MetaDataStorage):
raise ValueError('storage must be an instance of MetaDataStorage')
@ -209,7 +205,6 @@ class Wallet(object):
self._manage_count = 0
self._balance_refresh_time = 3
self._batch_count = 20
self._first_run = self._FIRST_RUN_UNKNOWN
def start(self):
def start_manage():
@ -703,20 +698,6 @@ class Wallet(object):
def get_available_balance(self):
return float(self.wallet_balance - self.total_reserved_points)
def is_first_run(self):
if self._first_run == self._FIRST_RUN_UNKNOWN:
d = self._check_first_run()
def set_first_run(is_first):
self._first_run = self._FIRST_RUN_YES if is_first else self._FIRST_RUN_NO
d.addCallback(set_first_run)
else:
d = defer.succeed(self._FIRST_RUN_YES if self._first_run else self._FIRST_RUN_NO)
d.addCallback(lambda _: self._first_run == self._FIRST_RUN_YES)
return d
def _get_status_of_claim(self, claim_outpoint, name, sd_hash):
d = self.get_claims_from_tx(claim_outpoint['txid'])
@ -819,9 +800,6 @@ class Wallet(object):
def _get_claims_for_name(self, name):
return defer.fail(NotImplementedError())
def _check_first_run(self):
return defer.fail(NotImplementedError())
def _send_name_claim(self, name, val, amount):
return defer.fail(NotImplementedError())
@ -865,13 +843,13 @@ class LBRYumWallet(Wallet):
self._config = config
self.network = None
self.wallet = None
self.first_run = False
self.is_first_run = False
self.printed_retrieving_headers = False
self._start_check = None
self._catch_up_check = None
self._caught_up_counter = 0
self._lag_counter = 0
self.blocks_behind_alert = 0
self.blocks_behind = 0
self.catchup_progress = 0
self.max_behind = 0
@ -884,7 +862,6 @@ class LBRYumWallet(Wallet):
alert.info("Loading the wallet...")
return defer.succeed(self.network.start())
d = setup_network()
def check_started():
@ -941,7 +918,7 @@ class LBRYumWallet(Wallet):
storage = lbryum.wallet.WalletStorage(path)
wallet = lbryum.wallet.Wallet(storage)
if not storage.file_exists:
self.first_run = True
self.is_first_run = True
seed = wallet.make_seed()
wallet.add_seed(seed, None)
wallet.create_master_keys(None)
@ -957,7 +934,13 @@ class LBRYumWallet(Wallet):
local_height = self.network.get_catchup_progress()
remote_height = self.network.get_server_height()
if remote_height != 0 and remote_height - local_height <= 5:
if remote_height == 0:
return
height_diff = remote_height - local_height
if height_diff <= 5:
self.blocks_behind = 0
msg = ""
if self._caught_up_counter != 0:
msg += "All caught up. "
@ -966,27 +949,29 @@ class LBRYumWallet(Wallet):
self._catch_up_check.stop()
self._catch_up_check = None
blockchain_caught_d.callback(True)
return
elif remote_height != 0:
past_blocks_behind = self.blocks_behind_alert
self.blocks_behind_alert = remote_height - local_height
if self.blocks_behind_alert < past_blocks_behind:
self._lag_counter = 0
self.is_lagging = False
else:
self._lag_counter += 1
if self._lag_counter >= 900:
self.is_lagging = True
if height_diff < self.blocks_behind:
# We're making progress in catching up
self._lag_counter = 0
self.is_lagging = False
else:
# No progress. Might be lagging
self._lag_counter += 1
if self._lag_counter >= 900:
self.is_lagging = True
if self.blocks_behind_alert > self.max_behind:
self.max_behind = self.blocks_behind_alert
self.catchup_progress = int(100 * (self.blocks_behind_alert / (5 + self.max_behind)))
if self._caught_up_counter == 0:
alert.info('Catching up with the blockchain...showing blocks left...')
if self._caught_up_counter % 30 == 0:
alert.info('%d...', (remote_height - local_height))
self.blocks_behind = height_diff
self._caught_up_counter += 1
if self.blocks_behind > self.max_behind:
self.max_behind = self.blocks_behind
self.catchup_progress = int(100 * (self.blocks_behind / (5 + self.max_behind)))
if self._caught_up_counter == 0:
alert.info('Catching up with the blockchain')
if self._caught_up_counter % 30 == 0:
alert.info('Blocks left: %d', (remote_height - local_height))
self._caught_up_counter += 1
def log_error(err):
log.warning(err.getErrorMessage())
@ -1052,9 +1037,6 @@ class LBRYumWallet(Wallet):
def get_name_claims(self):
return self._run_cmd_as_defer_succeed('getnameclaims')
def _check_first_run(self):
return defer.succeed(self.first_run)
def _get_claims_for_name(self, name):
return self._run_cmd_as_defer_to_thread('getclaimsforname', name)

File diff suppressed because it is too large Load diff

View file

@ -2,17 +2,11 @@ import sys
import argparse
import json
from lbrynet import conf
import os
from lbrynet.lbrynet_daemon.auth.client import LBRYAPIClient
from lbrynet.lbrynet_daemon.Daemon import LOADING_WALLET_CODE
from jsonrpc.common import RPCError
help_msg = "Usage: lbrynet-cli method kwargs\n" \
+ "Examples: " \
+ "lbrynet-cli resolve_name name=what\n" \
+ "lbrynet-cli get_balance\n" \
+ "lbrynet-cli help function=resolve_name\n" \
+ "\n******lbrynet-cli functions******\n"
from urllib2 import URLError
def guess_type(x):
@ -31,35 +25,41 @@ def guess_type(x):
def get_params_from_kwargs(params):
params_for_return = {}
for i in params:
if '=' not in i:
print 'WARNING: Argument "' + i + '" is missing a parameter name. Please use name=value'
continue
eq_pos = i.index('=')
k, v = i[:eq_pos], i[eq_pos+1:]
k, v = i[:eq_pos], i[eq_pos + 1:]
params_for_return[k] = guess_type(v)
return params_for_return
def main():
conf.initialize_settings()
api = LBRYAPIClient.config()
api = LBRYAPIClient.get_client()
try:
status = api.daemon_status()
assert status.get('code', False) == "started"
except Exception:
try:
conf.settings.update({'use_auth_http': not conf.settings.use_auth_http})
api = LBRYAPIClient.config()
status = api.daemon_status()
assert status.get('code', False) == "started"
except Exception:
print "lbrynet-daemon isn't running"
sys.exit(1)
status = api.status()
except URLError:
print "Could not connect to lbrynet-daemon. Are you sure it's running?"
sys.exit(1)
if status['startup_status']['code'] != "started":
print "Daemon is in the process of starting. Please try again in a bit."
message = status['startup_status']['message']
if message:
if status['startup_status']['code'] == LOADING_WALLET_CODE \
and status['blocks_behind'] > 0:
message += '. Blocks left: ' + str(status['blocks_behind'])
print " Status: " + message
sys.exit(1)
parser = argparse.ArgumentParser()
parser.add_argument('method', nargs=1)
parser.add_argument('params', nargs=argparse.REMAINDER, default=None)
args = parser.parse_args()
meth = args.method[0]
method = args.method[0]
params = {}
if len(args.params) > 1:
@ -70,34 +70,41 @@ def main():
except ValueError:
params = get_params_from_kwargs(args.params)
msg = help_msg
for f in api.help():
msg += f + "\n"
if method in ['--help', '-h', 'help']:
helpmsg = api.help(params).strip()
if params is not None and 'function' in params:
print "\n" + params['function'] + ": " + helpmsg + "\n"
else:
print "Usage: lbrynet-cli method [params]\n" \
+ "Examples: \n" \
+ " lbrynet-cli get_balance\n" \
+ " lbrynet-cli resolve_name name=what\n" \
+ " lbrynet-cli help function=resolve_name\n" \
+ "\nAvailable functions:\n" \
+ helpmsg + "\n"
if meth in ['--help', '-h', 'help']:
print msg
sys.exit(1)
if meth in api.help():
elif method not in api.commands():
print "Error: function \"" + method + "\" does not exist.\n" + \
"See \"" + os.path.basename(sys.argv[0]) + " help\""
else:
try:
if params:
result = LBRYAPIClient.config(service=meth, params=params)
else:
result = LBRYAPIClient.config(service=meth, params=params)
print json.dumps(result, sort_keys=True)
result = api.call(method, params)
print json.dumps(result, sort_keys=True, indent=2)
except RPCError as err:
# TODO: The api should return proper error codes
# and messages so that they can be passed along to the user
# instead of this generic message.
# https://app.asana.com/0/158602294500137/200173944358192
print "Something went wrong, here's the usage for %s:" % meth
print api.help({'function': meth})
print "Something went wrong, here's the usage for %s:" % method
print api.help({'function': method})
print "Here's the traceback for the error you encountered:"
print err.msg
else:
print "Unknown function"
print msg
except KeyError as err:
print "Something went wrong, here's the usage for %s:" % method
print api.help({'function': method})
if hasattr(err, 'msg'):
print "Here's the traceback for the error you encountered:"
print err.msg
if __name__ == '__main__':

View file

@ -23,8 +23,7 @@ class JSONRPCException(Exception):
class AuthAPIClient(object):
def __init__(self, key, timeout, connection, count, service, cookies, auth, url, login_url):
self.__service_name = service
def __init__(self, key, timeout, connection, count, cookies, auth, url, login_url):
self.__api_key = key
self.__service_url = login_url
self.__id_count = count
@ -35,26 +34,21 @@ class AuthAPIClient(object):
def __getattr__(self, name):
if name.startswith('__') and name.endswith('__'):
# Python internal stuff
raise AttributeError
if self.__service_name is not None:
name = "%s.%s" % (self.__service_name, name)
return AuthAPIClient(key=self.__api_key,
timeout=HTTP_TIMEOUT,
connection=self.__conn,
count=self.__id_count,
service=name,
cookies=self.__cookies,
auth=self.__auth_header,
url=self.__url,
login_url=self.__service_url)
raise AttributeError # Python internal stuff
def __call__(self, *args):
def f(*args):
return self.call(name, args)
return f
def call(self, method, params={}):
self.__id_count += 1
pre_auth_postdata = {'version': '1.1',
'method': self.__service_name,
'params': args,
'id': self.__id_count}
pre_auth_postdata = {
'version': '1.1',
'method': method,
'params': params,
'id': self.__id_count
}
to_auth = get_auth_message(pre_auth_postdata)
token = self.__api_key.get_hmac(to_auth)
pre_auth_postdata.update({'hmac': token})
@ -67,10 +61,12 @@ class AuthAPIClient(object):
req = requests.Request(method='POST',
url=service_url,
data=postdata,
headers={'Host': host,
'User-Agent': USER_AGENT,
'Authorization': auth_header,
'Content-type': 'application/json'},
headers={
'Host': host,
'User-Agent': USER_AGENT,
'Authorization': auth_header,
'Content-type': 'application/json'
},
cookies=cookies)
r = req.prepare()
http_response = self.__conn.send(r)
@ -163,15 +159,6 @@ class AuthAPIClient(object):
class LBRYAPIClient(object):
@staticmethod
def config(service=None, params=None):
if conf.settings.use_auth_http:
if service is None:
return AuthAPIClient.config()
log.error("Try auth")
if params is not None:
return AuthAPIClient.config(service=service)(params)
return AuthAPIClient.config(service=service)()
url = conf.settings.API_CONNECTION_STRING
if service is None:
return JSONRPCProxy.from_url(url)
return JSONRPCProxy.from_url(url).call(service, params)
def get_client():
return AuthAPIClient.config() if conf.settings.use_auth_http else \
JSONRPCProxy.from_url(conf.settings.API_CONNECTION_STRING)

View file

@ -11,7 +11,7 @@ from lbrynet import conf
class LBRYURIHandler(object):
def __init__(self):
self.started_daemon = False
self.daemon = LBRYAPIClient.config()
self.daemon = LBRYAPIClient.get_client()
def handle_osx(self, lbry_name):
self.check_daemon()