diff --git a/.vscode/settings.json b/.vscode/settings.json index 2421e38..11b7275 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -4,5 +4,10 @@ "**/.project": true, "**/.settings": true, "**/.factorypath": true + }, + "java.completion.enabled": false, + + "files.watcherExclude": { + "**/target": true } -} \ No newline at end of file +} diff --git a/README.md b/README.md index 65d8130..bd583a2 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ TL;DR **如果有人想帮助搭国内建授权服务器的话,请按以下步骤进行:** 1. Clone 并用任意值配置好环境变量后成功运行服务 -2. Fork 此repo,并把你的新服务器地址加到这里 +2. Fork 此repo,并把你的新服务器地址加到这里 3. 创建拉取请求,然后通过 [![Join the chat at https://gitter.im/houtianze/bypy](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/houtianze/bypy?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) 或者在拉取请求里留下你的联系方式 4. 我测试新服务器可以使用后,通过Gitter/邮件把Secret Key发给你,你用正确的配置启动授权服务器 5. 新的授权服务器配置好后我合并拉取请求 diff --git a/bypy/bypy.py b/bypy/bypy.py index 2e37057..6c37239 100755 --- a/bypy/bypy.py +++ b/bypy/bypy.py @@ -68,6 +68,12 @@ raw_input = input pickleload = partial(pickle.load, encoding="bytes") +try: + import importlib.resources as pkg_resources +except ImportError: + # Try backported to PY<37 `importlib_resources`. + import importlib_resources as pkg_resources + from . import const from . import gvar from . import printer_console @@ -317,6 +323,9 @@ def __init__(self, # so if any code using this class can check the current verbose / debug level cached.verbose = self.verbose = verbose cached.debug = self.debug = debug + + self.__load_auth_server_list() + if not cached.usecache: pinfo("Forced hash recalculation, hash cache won't be used") @@ -984,20 +993,29 @@ def __local_auth_act(self, r, args): def __repr_timeout(self): return self.__timeout if self.__timeout else 'infinite' - # NO longer in use - # def __update_auth_server_list(self): - # try: - # r = requests.get('https://raw.githubusercontent.com/houtianze/bypy/master/update/auth.json') - # if r.status_code == 200: - # try: - # j = r.json() - # const.AuthServerList = j['AuthServerList'] - # except ValueError: - # self.pd("Invalid response for auth servers update, skipping.") - # else: - # self.pd("HTTP Status {} while updating auth servers, skipping.".format(r.status_code)) - # except: - # self.pd("Error occurred while updating auth servers, skipping.") + def __load_auth_server_list(self): + # https://stackoverflow.com/a/20885799/404271 + from . import res + j = json.loads(pkg_resources.read_text(res, 'auth.json')) + self.pd('Auth servers loaded: {}'.format(j)) + self.AuthServerList = j['AuthServerList'] + self.RefreshServerList = j['RefreshServerList'] + + def __update_auth_server_list(self): + try: + r = requests.get('https://raw.githubusercontent.com/houtianze/bypy/master/bypy/res/auth.json') + if r.status_code == 200: + try: + j = r.json() + self.pd('Auth servers updated: {}'.format(j)) + self.AuthServerList = j['AuthServerList'] + self.RefreshServerList = j['RefreshServerList'] + except ValueError: + self.pd("Invalid response for auth servers update, skipping.") + else: + self.pd("HTTP Status {} while updating auth servers, skipping.".format(r.status_code)) + except: + self.pd("Error occurred while updating auth servers, skipping.") def __auth(self): params = { @@ -1025,8 +1043,8 @@ def __auth(self): if not self.debug: perr = nop - # self.__update_auth_server_list() - for auth in const.AuthServerList: + self.__update_auth_server_list() + for auth in self.AuthServerList: (url, retry, msg) = auth pr(msg) result = self.__get(url, pars, self.__server_auth_act, retry = retry, addtoken = False) @@ -1093,15 +1111,44 @@ def __refresh_token_act(self, r, args): return self.__store_json(r) def __refresh_token(self): - pr('Refreshing, please be patient, it may take upto {} seconds...'.format(self.__repr_timeout())) - # How silly am I to have used server for token refresh - - # We DON'T need any server for refreshing token, we have refresh_token already after auth. - pars = { - 'grant_type' : 'refresh_token', - 'refresh_token' : self.__json['refresh_token'], - 'client_secret' : self.__secretkey, - 'client_id' : self.__apikey} - return self.__post(const.TokenUrl, pars, self.__refresh_token_act) + if self.__use_server_auth: + pr('Refreshing, please be patient, it may take upto {} seconds...'.format(self.__repr_timeout())) + + pars = { + 'bypy_version' : const.__version__, + 'refresh_token' : self.__json['refresh_token'] } + + result = None + # TODO: hacky + global perr + savedperr = perr + if not self.debug: + perr = nop + self.__update_auth_server_list() + for refresh in self.RefreshServerList: + (url, retry, msg) = refresh + pr(msg) + result = self.__get(url, pars, self.__refresh_token_act, retry = retry, addtoken = False) + if result == const.ENoError: + break + if not self.debug: + perr = savedperr + + if result == const.ENoError: + pr("Token successfully refreshed") + else: + perr("Token-refreshing on all the servers failed") + self.__prompt_clean() + sys.exit(result) + + return result + else: + pars = { + 'grant_type' : 'refresh_token', + 'refresh_token' : self.__json['refresh_token'], + 'client_secret' : self.__secretkey, + 'client_id' : self.__apikey} + return self.__post(const.TokenUrl, pars, self.__refresh_token_act) def __walk_normal_file(self, dir): #dirb = dir.encode(FileSystemEncoding) diff --git a/bypy/const.py b/bypy/const.py index 8ff89d5..d795333 100755 --- a/bypy/const.py +++ b/bypy/const.py @@ -161,17 +161,6 @@ MaxSlicePieces = 1024 MaxListEntries = 1000 # https://github.com/houtianze/bypy/issues/285 -### Auth servers -VercelUrl = 'https://bypyoauthsanic.vercel.app/api' -VercelRedirectUrl = VercelUrl + '/auth' -AliyunUrl = 'https://8.142.131.121' -AliyunRedirectUrl = AliyunUrl + '/auth' -AuthServerList = [ - # url, retry?, message - (VercelRedirectUrl, False, "Authorizing with the Vercel server ..."), - (AliyunRedirectUrl, False, "Vercel server failed. Last resort: authorizing with the Aliyun server ..."), -] - ### public static properties HelpMarker = "Usage:" diff --git a/bypy/res/__init__.py b/bypy/res/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/bypy/res/auth.json b/bypy/res/auth.json new file mode 100644 index 0000000..1b1b22c --- /dev/null +++ b/bypy/res/auth.json @@ -0,0 +1,26 @@ +{ + "AuthServerList": [ + [ + "https://bypyoauthsanic.vercel.app/api/auth", + false, + "Authorizing with the Vercel server ..." + ], + [ + "https://8.142.131.12/auth", + false, + "Vercel server failed. Last resort: authorizing with the Aliyun server ..." + ] + ], + "RefreshServerList": [ + [ + "https://bypyoauthsanic.vercel.app/api/refresh", + false, + "Refreshing with the Vercel server ..." + ], + [ + "https://8.142.131.12/refresh", + false, + "Vercel server failed. Last resort: refreshing with the Aliyun server ..." + ] + ] +} diff --git a/requirements.txt b/requirements.txt index c19f404..c9c9cef 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,4 @@ requests requests-toolbelt multiprocess +importlib-resources diff --git a/setup.py b/setup.py index 1e8916d..3ccfa8f 100755 --- a/setup.py +++ b/setup.py @@ -46,7 +46,7 @@ def getmeta(path, encoding = 'utf8'): author_email = 'houtianze@users.noreply.github.com', download_url = 'https://github.com/houtianze/bypy/tarball/' + meta['version'], #packages=find_packages(), - packages = ['bypy', 'bypy.test'], + packages = ['bypy', 'bypy.res', 'bypy.test'], package_data = { 'bypy' : ['*.rst', 'bypy/*.pem'] }, @@ -80,7 +80,8 @@ def getmeta(path, encoding = 'utf8'): install_requires = [ 'requests>=2.10.0', 'requests-toolbelt>=0.8.0', - 'multiprocess>=0.70.0'], + 'multiprocess>=0.70.0', + 'importlib-resources>=5.4.0'], include_package_data = True, **meta )