forked from LBRYCommunity/lbry-sdk
rename api endpoints
This commit is contained in:
parent
a67aab0797
commit
962edb8e4c
8 changed files with 575 additions and 513 deletions
5
.gitignore
vendored
5
.gitignore
vendored
|
@ -9,12 +9,11 @@
|
||||||
|
|
||||||
/build
|
/build
|
||||||
/dist
|
/dist
|
||||||
|
/lbrynet.egg-info
|
||||||
|
|
||||||
.idea/.name
|
.idea/.name
|
||||||
.coverage
|
.coverage
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
lbrynet.egg-info/PKG-INFO
|
|
||||||
|
|
||||||
# temporary files from the twisted.trial test runner
|
# temporary files from the twisted.trial test runner
|
||||||
_trial_temp/
|
_trial_temp/
|
||||||
|
|
5
FAQ.md
5
FAQ.md
|
@ -77,8 +77,9 @@ Note: the lbry api can only be used while either the app or lbrynet-daemon comma
|
||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
|
|
||||||
api = JSONRPCProxy.from_url(API_CONNECTION_STRING)
|
api = JSONRPCProxy.from_url(API_CONNECTION_STRING)
|
||||||
if not api.is_running():
|
status = api.status()
|
||||||
print api.daemon_status()
|
if not status['is_running']:
|
||||||
|
print status
|
||||||
else:
|
else:
|
||||||
for func in api.help():
|
for func in api.help():
|
||||||
print "%s:\n%s" % (func, api.help({'function': func}))
|
print "%s:\n%s" % (func, api.help({'function': func}))
|
||||||
|
|
|
@ -49,8 +49,9 @@ except:
|
||||||
API_CONNECTION_STRING = "http://localhost:5279/lbryapi"
|
API_CONNECTION_STRING = "http://localhost:5279/lbryapi"
|
||||||
|
|
||||||
api = JSONRPCProxy.from_url(API_CONNECTION_STRING)
|
api = JSONRPCProxy.from_url(API_CONNECTION_STRING)
|
||||||
if not api.is_running():
|
status = api.status()
|
||||||
print api.daemon_status()
|
if not status['is_running']:
|
||||||
|
print status
|
||||||
else:
|
else:
|
||||||
for func in api.help():
|
for func in api.help():
|
||||||
print "%s:\n%s" % (func, api.help({'function': func}))
|
print "%s:\n%s" % (func, api.help({'function': func}))
|
||||||
|
|
|
@ -182,10 +182,6 @@ class Wallet(object):
|
||||||
"""This class implements the Wallet interface for the LBRYcrd payment system"""
|
"""This class implements the Wallet interface for the LBRYcrd payment system"""
|
||||||
implements(IWallet)
|
implements(IWallet)
|
||||||
|
|
||||||
_FIRST_RUN_UNKNOWN = 0
|
|
||||||
_FIRST_RUN_YES = 1
|
|
||||||
_FIRST_RUN_NO = 2
|
|
||||||
|
|
||||||
def __init__(self, storage):
|
def __init__(self, storage):
|
||||||
if not isinstance(storage, MetaDataStorage):
|
if not isinstance(storage, MetaDataStorage):
|
||||||
raise ValueError('storage must be an instance of MetaDataStorage')
|
raise ValueError('storage must be an instance of MetaDataStorage')
|
||||||
|
@ -209,7 +205,6 @@ class Wallet(object):
|
||||||
self._manage_count = 0
|
self._manage_count = 0
|
||||||
self._balance_refresh_time = 3
|
self._balance_refresh_time = 3
|
||||||
self._batch_count = 20
|
self._batch_count = 20
|
||||||
self._first_run = self._FIRST_RUN_UNKNOWN
|
|
||||||
|
|
||||||
def start(self):
|
def start(self):
|
||||||
def start_manage():
|
def start_manage():
|
||||||
|
@ -703,20 +698,6 @@ class Wallet(object):
|
||||||
def get_available_balance(self):
|
def get_available_balance(self):
|
||||||
return float(self.wallet_balance - self.total_reserved_points)
|
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):
|
def _get_status_of_claim(self, claim_outpoint, name, sd_hash):
|
||||||
d = self.get_claims_from_tx(claim_outpoint['txid'])
|
d = self.get_claims_from_tx(claim_outpoint['txid'])
|
||||||
|
|
||||||
|
@ -819,9 +800,6 @@ class Wallet(object):
|
||||||
def _get_claims_for_name(self, name):
|
def _get_claims_for_name(self, name):
|
||||||
return defer.fail(NotImplementedError())
|
return defer.fail(NotImplementedError())
|
||||||
|
|
||||||
def _check_first_run(self):
|
|
||||||
return defer.fail(NotImplementedError())
|
|
||||||
|
|
||||||
def _send_name_claim(self, name, val, amount):
|
def _send_name_claim(self, name, val, amount):
|
||||||
return defer.fail(NotImplementedError())
|
return defer.fail(NotImplementedError())
|
||||||
|
|
||||||
|
@ -865,13 +843,13 @@ class LBRYumWallet(Wallet):
|
||||||
self._config = config
|
self._config = config
|
||||||
self.network = None
|
self.network = None
|
||||||
self.wallet = None
|
self.wallet = None
|
||||||
self.first_run = False
|
self.is_first_run = False
|
||||||
self.printed_retrieving_headers = False
|
self.printed_retrieving_headers = False
|
||||||
self._start_check = None
|
self._start_check = None
|
||||||
self._catch_up_check = None
|
self._catch_up_check = None
|
||||||
self._caught_up_counter = 0
|
self._caught_up_counter = 0
|
||||||
self._lag_counter = 0
|
self._lag_counter = 0
|
||||||
self.blocks_behind_alert = 0
|
self.blocks_behind = 0
|
||||||
self.catchup_progress = 0
|
self.catchup_progress = 0
|
||||||
self.max_behind = 0
|
self.max_behind = 0
|
||||||
|
|
||||||
|
@ -884,7 +862,6 @@ class LBRYumWallet(Wallet):
|
||||||
alert.info("Loading the wallet...")
|
alert.info("Loading the wallet...")
|
||||||
return defer.succeed(self.network.start())
|
return defer.succeed(self.network.start())
|
||||||
|
|
||||||
|
|
||||||
d = setup_network()
|
d = setup_network()
|
||||||
|
|
||||||
def check_started():
|
def check_started():
|
||||||
|
@ -941,7 +918,7 @@ class LBRYumWallet(Wallet):
|
||||||
storage = lbryum.wallet.WalletStorage(path)
|
storage = lbryum.wallet.WalletStorage(path)
|
||||||
wallet = lbryum.wallet.Wallet(storage)
|
wallet = lbryum.wallet.Wallet(storage)
|
||||||
if not storage.file_exists:
|
if not storage.file_exists:
|
||||||
self.first_run = True
|
self.is_first_run = True
|
||||||
seed = wallet.make_seed()
|
seed = wallet.make_seed()
|
||||||
wallet.add_seed(seed, None)
|
wallet.add_seed(seed, None)
|
||||||
wallet.create_master_keys(None)
|
wallet.create_master_keys(None)
|
||||||
|
@ -957,7 +934,13 @@ class LBRYumWallet(Wallet):
|
||||||
local_height = self.network.get_catchup_progress()
|
local_height = self.network.get_catchup_progress()
|
||||||
remote_height = self.network.get_server_height()
|
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 = ""
|
msg = ""
|
||||||
if self._caught_up_counter != 0:
|
if self._caught_up_counter != 0:
|
||||||
msg += "All caught up. "
|
msg += "All caught up. "
|
||||||
|
@ -966,27 +949,29 @@ class LBRYumWallet(Wallet):
|
||||||
self._catch_up_check.stop()
|
self._catch_up_check.stop()
|
||||||
self._catch_up_check = None
|
self._catch_up_check = None
|
||||||
blockchain_caught_d.callback(True)
|
blockchain_caught_d.callback(True)
|
||||||
|
return
|
||||||
|
|
||||||
elif remote_height != 0:
|
if height_diff < self.blocks_behind:
|
||||||
past_blocks_behind = self.blocks_behind_alert
|
# We're making progress in catching up
|
||||||
self.blocks_behind_alert = remote_height - local_height
|
self._lag_counter = 0
|
||||||
if self.blocks_behind_alert < past_blocks_behind:
|
self.is_lagging = False
|
||||||
self._lag_counter = 0
|
else:
|
||||||
self.is_lagging = False
|
# No progress. Might be lagging
|
||||||
else:
|
self._lag_counter += 1
|
||||||
self._lag_counter += 1
|
if self._lag_counter >= 900:
|
||||||
if self._lag_counter >= 900:
|
self.is_lagging = True
|
||||||
self.is_lagging = True
|
|
||||||
|
|
||||||
if self.blocks_behind_alert > self.max_behind:
|
self.blocks_behind = height_diff
|
||||||
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._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):
|
def log_error(err):
|
||||||
log.warning(err.getErrorMessage())
|
log.warning(err.getErrorMessage())
|
||||||
|
@ -1052,9 +1037,6 @@ class LBRYumWallet(Wallet):
|
||||||
def get_name_claims(self):
|
def get_name_claims(self):
|
||||||
return self._run_cmd_as_defer_succeed('getnameclaims')
|
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):
|
def _get_claims_for_name(self, name):
|
||||||
return self._run_cmd_as_defer_to_thread('getclaimsforname', name)
|
return self._run_cmd_as_defer_to_thread('getclaimsforname', name)
|
||||||
|
|
||||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -2,17 +2,11 @@ import sys
|
||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
from lbrynet import conf
|
from lbrynet import conf
|
||||||
|
import os
|
||||||
from lbrynet.lbrynet_daemon.auth.client import LBRYAPIClient
|
from lbrynet.lbrynet_daemon.auth.client import LBRYAPIClient
|
||||||
|
from lbrynet.lbrynet_daemon.Daemon import LOADING_WALLET_CODE
|
||||||
from jsonrpc.common import RPCError
|
from jsonrpc.common import RPCError
|
||||||
|
from urllib2 import URLError
|
||||||
|
|
||||||
|
|
||||||
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"
|
|
||||||
|
|
||||||
|
|
||||||
def guess_type(x):
|
def guess_type(x):
|
||||||
|
@ -31,35 +25,41 @@ def guess_type(x):
|
||||||
def get_params_from_kwargs(params):
|
def get_params_from_kwargs(params):
|
||||||
params_for_return = {}
|
params_for_return = {}
|
||||||
for i in params:
|
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('=')
|
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)
|
params_for_return[k] = guess_type(v)
|
||||||
return params_for_return
|
return params_for_return
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
conf.initialize_settings()
|
conf.initialize_settings()
|
||||||
api = LBRYAPIClient.config()
|
api = LBRYAPIClient.get_client()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
status = api.daemon_status()
|
status = api.status()
|
||||||
assert status.get('code', False) == "started"
|
except URLError:
|
||||||
except Exception:
|
print "Could not connect to lbrynet-daemon. Are you sure it's running?"
|
||||||
try:
|
sys.exit(1)
|
||||||
conf.settings.update({'use_auth_http': not conf.settings.use_auth_http})
|
|
||||||
api = LBRYAPIClient.config()
|
if status['startup_status']['code'] != "started":
|
||||||
status = api.daemon_status()
|
print "Daemon is in the process of starting. Please try again in a bit."
|
||||||
assert status.get('code', False) == "started"
|
message = status['startup_status']['message']
|
||||||
except Exception:
|
if message:
|
||||||
print "lbrynet-daemon isn't running"
|
if status['startup_status']['code'] == LOADING_WALLET_CODE \
|
||||||
sys.exit(1)
|
and status['blocks_behind'] > 0:
|
||||||
|
message += '. Blocks left: ' + str(status['blocks_behind'])
|
||||||
|
print " Status: " + message
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
parser.add_argument('method', nargs=1)
|
parser.add_argument('method', nargs=1)
|
||||||
parser.add_argument('params', nargs=argparse.REMAINDER, default=None)
|
parser.add_argument('params', nargs=argparse.REMAINDER, default=None)
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
meth = args.method[0]
|
method = args.method[0]
|
||||||
params = {}
|
params = {}
|
||||||
|
|
||||||
if len(args.params) > 1:
|
if len(args.params) > 1:
|
||||||
|
@ -70,34 +70,41 @@ def main():
|
||||||
except ValueError:
|
except ValueError:
|
||||||
params = get_params_from_kwargs(args.params)
|
params = get_params_from_kwargs(args.params)
|
||||||
|
|
||||||
msg = help_msg
|
if method in ['--help', '-h', 'help']:
|
||||||
for f in api.help():
|
helpmsg = api.help(params).strip()
|
||||||
msg += f + "\n"
|
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']:
|
elif method not in api.commands():
|
||||||
print msg
|
print "Error: function \"" + method + "\" does not exist.\n" + \
|
||||||
sys.exit(1)
|
"See \"" + os.path.basename(sys.argv[0]) + " help\""
|
||||||
|
else:
|
||||||
if meth in api.help():
|
|
||||||
try:
|
try:
|
||||||
if params:
|
result = api.call(method, params)
|
||||||
result = LBRYAPIClient.config(service=meth, params=params)
|
print json.dumps(result, sort_keys=True, indent=2)
|
||||||
else:
|
|
||||||
result = LBRYAPIClient.config(service=meth, params=params)
|
|
||||||
print json.dumps(result, sort_keys=True)
|
|
||||||
except RPCError as err:
|
except RPCError as err:
|
||||||
# TODO: The api should return proper error codes
|
# TODO: The api should return proper error codes
|
||||||
# and messages so that they can be passed along to the user
|
# and messages so that they can be passed along to the user
|
||||||
# instead of this generic message.
|
# instead of this generic message.
|
||||||
# https://app.asana.com/0/158602294500137/200173944358192
|
# https://app.asana.com/0/158602294500137/200173944358192
|
||||||
print "Something went wrong, here's the usage for %s:" % meth
|
print "Something went wrong, here's the usage for %s:" % method
|
||||||
print api.help({'function': meth})
|
print api.help({'function': method})
|
||||||
print "Here's the traceback for the error you encountered:"
|
print "Here's the traceback for the error you encountered:"
|
||||||
print err.msg
|
print err.msg
|
||||||
|
except KeyError as err:
|
||||||
else:
|
print "Something went wrong, here's the usage for %s:" % method
|
||||||
print "Unknown function"
|
print api.help({'function': method})
|
||||||
print msg
|
if hasattr(err, 'msg'):
|
||||||
|
print "Here's the traceback for the error you encountered:"
|
||||||
|
print err.msg
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
|
|
@ -23,8 +23,7 @@ class JSONRPCException(Exception):
|
||||||
|
|
||||||
|
|
||||||
class AuthAPIClient(object):
|
class AuthAPIClient(object):
|
||||||
def __init__(self, key, timeout, connection, count, service, cookies, auth, url, login_url):
|
def __init__(self, key, timeout, connection, count, cookies, auth, url, login_url):
|
||||||
self.__service_name = service
|
|
||||||
self.__api_key = key
|
self.__api_key = key
|
||||||
self.__service_url = login_url
|
self.__service_url = login_url
|
||||||
self.__id_count = count
|
self.__id_count = count
|
||||||
|
@ -35,26 +34,21 @@ class AuthAPIClient(object):
|
||||||
|
|
||||||
def __getattr__(self, name):
|
def __getattr__(self, name):
|
||||||
if name.startswith('__') and name.endswith('__'):
|
if name.startswith('__') and name.endswith('__'):
|
||||||
# Python internal stuff
|
raise AttributeError # 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)
|
|
||||||
|
|
||||||
def __call__(self, *args):
|
def f(*args):
|
||||||
|
return self.call(name, args)
|
||||||
|
|
||||||
|
return f
|
||||||
|
|
||||||
|
def call(self, method, params={}):
|
||||||
self.__id_count += 1
|
self.__id_count += 1
|
||||||
pre_auth_postdata = {'version': '1.1',
|
pre_auth_postdata = {
|
||||||
'method': self.__service_name,
|
'version': '1.1',
|
||||||
'params': args,
|
'method': method,
|
||||||
'id': self.__id_count}
|
'params': params,
|
||||||
|
'id': self.__id_count
|
||||||
|
}
|
||||||
to_auth = get_auth_message(pre_auth_postdata)
|
to_auth = get_auth_message(pre_auth_postdata)
|
||||||
token = self.__api_key.get_hmac(to_auth)
|
token = self.__api_key.get_hmac(to_auth)
|
||||||
pre_auth_postdata.update({'hmac': token})
|
pre_auth_postdata.update({'hmac': token})
|
||||||
|
@ -67,10 +61,12 @@ class AuthAPIClient(object):
|
||||||
req = requests.Request(method='POST',
|
req = requests.Request(method='POST',
|
||||||
url=service_url,
|
url=service_url,
|
||||||
data=postdata,
|
data=postdata,
|
||||||
headers={'Host': host,
|
headers={
|
||||||
'User-Agent': USER_AGENT,
|
'Host': host,
|
||||||
'Authorization': auth_header,
|
'User-Agent': USER_AGENT,
|
||||||
'Content-type': 'application/json'},
|
'Authorization': auth_header,
|
||||||
|
'Content-type': 'application/json'
|
||||||
|
},
|
||||||
cookies=cookies)
|
cookies=cookies)
|
||||||
r = req.prepare()
|
r = req.prepare()
|
||||||
http_response = self.__conn.send(r)
|
http_response = self.__conn.send(r)
|
||||||
|
@ -163,15 +159,6 @@ class AuthAPIClient(object):
|
||||||
|
|
||||||
class LBRYAPIClient(object):
|
class LBRYAPIClient(object):
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def config(service=None, params=None):
|
def get_client():
|
||||||
if conf.settings.use_auth_http:
|
return AuthAPIClient.config() if conf.settings.use_auth_http else \
|
||||||
if service is None:
|
JSONRPCProxy.from_url(conf.settings.API_CONNECTION_STRING)
|
||||||
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)
|
|
||||||
|
|
|
@ -11,7 +11,7 @@ from lbrynet import conf
|
||||||
class LBRYURIHandler(object):
|
class LBRYURIHandler(object):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.started_daemon = False
|
self.started_daemon = False
|
||||||
self.daemon = LBRYAPIClient.config()
|
self.daemon = LBRYAPIClient.get_client()
|
||||||
|
|
||||||
def handle_osx(self, lbry_name):
|
def handle_osx(self, lbry_name):
|
||||||
self.check_daemon()
|
self.check_daemon()
|
||||||
|
|
Loading…
Add table
Reference in a new issue