Skip to content

Commit

Permalink
Merge pull request #84 from MathNodes/main
Browse files Browse the repository at this point in the history
Update to 1.8.0
  • Loading branch information
MathNodes authored Jan 13, 2024
2 parents 4004625 + 80a3a40 commit 027d668
Show file tree
Hide file tree
Showing 7 changed files with 118 additions and 59 deletions.
6 changes: 3 additions & 3 deletions src/cli/sentinel.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ def get_nodes(self, latency, *kwargs):


def GetHealthCheckData(self):
Request = HTTPRequests.MakeRequest(TIMEOUT=2)
Request = HTTPRequests.MakeRequest(TIMEOUT=4)
http = Request.hadapter()
try:
r = http.get(HTTParams.HEALTH_CHECK) #specify a constant in konstants.py
Expand All @@ -150,7 +150,7 @@ def GetHealthCheckData(self):
print(str(e))

def GetNodeScores(self):
Request = HTTPRequests.MakeRequest(TIMEOUT=2)
Request = HTTPRequests.MakeRequest(TIMEOUT=4)
http = Request.hadapter()
try:
r = http.get(HTTParams.SERVER_URL + HTTParams.NODE_SCORE_ENDPOINT)
Expand All @@ -163,7 +163,7 @@ def GetNodeScores(self):
print(str(e))

def GetNodeLocations(self):
Request = HTTPRequests.MakeRequest(TIMEOUT=2)
Request = HTTPRequests.MakeRequest(TIMEOUT=4)
http = Request.hadapter()
try:
r = http.get(HTTParams.SERVER_URL + HTTParams.NODE_LOCATION_ENDPOINT)
Expand Down
64 changes: 34 additions & 30 deletions src/fiat/fiat_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@
import requests
from requests.auth import HTTPBasicAuth

import stripe
import stripe
import time
from stripe.error import CardError
from fiat.stripe_pay.charge import HotwalletFuncs as HandleWalletFunctions
import fiat.stripe_pay.charge as Charge
Expand Down Expand Up @@ -61,7 +62,8 @@ class FiatInterface(Screen):

def __init__(self, **kwargs):
super(FiatInterface, self).__init__()

self.price_api = GetPriceAPI()
self.price_cache = {}
self.CoinOptions = self.DynamicCoinOptions()
self.DVPNOptions = self.CoinOptions['dvpn']
self.DECOptions = self.CoinOptions['dec']
Expand Down Expand Up @@ -177,7 +179,6 @@ def DynamicCoinOptions(self):
MAX_SPEND = 25
coins = self.TokenOptions
CoinOptions = {coins[0] : None, coins[1] : None, coins[2] : None}
api = GetPriceAPI()

Request = HTTPRequests.MakeRequest()
http = Request.hadapter()
Expand All @@ -189,11 +190,15 @@ def DynamicCoinOptions(self):
pass

for c in coins:
response = api.get_usd(c)

qty = int(MAX_SPEND/float(response['price']))
self.refresh_price(c, cache=30)

if self.price_cache[c]["price"] == 0:
x = 0
qty = 0
else:
x = 1 /self.price_cache[c]["price"]
qty = int(MAX_SPEND/self.price_cache[c]["price"])

x = 1 / float(response['price'])

if x < 1:
factor = 0.1
Expand Down Expand Up @@ -223,33 +228,32 @@ def DynamicCoinOptions(self):

return CoinOptions


def refresh_price(self, mu_coin: str = "dvpn", cache: int = 30):
# Need check on cache or trought GetPrice api
# We don't need to call the price api if the cache is younger that 30s

if mu_coin not in self.price_cache or time.time() - self.price_cache[mu_coin]["time"] > cache:
response = self.price_api.get_usd(mu_coin)
if response['success']:
self.price_cache[mu_coin] = {
"price": float(response['price']),
"time": time.time()
}
else:
self.price_cache[mu_coin] = {
"price": float(0),
"time": time.time()
}

def set_token_price(self, token, dt):
self.ids.dvpn_price.text = "%s: $" % token.upper() + str(self.get_token_price(token))

def get_token_price(self, token):

'''
cg_api_keyword = self.CoinGeckoAPI[self.TokenOptions[0]]
for key,value in self.CoinGeckoAPI.items():
if token == key:
cg_api_keyword = value
try:
cg = CoinGeckoAPI()
cg_price = cg.get_price(ids=[cg_api_keyword], vs_currencies='usd')
token_price = cg_price[cg_api_keyword]['usd']
'''

api = GetPriceAPI()

try:
response = api.get_usd(token)
if response['success']:
token_price = response['price']
else:
raise Exception("Error getting price from CoinStats or AscenDEX")
self.refresh_price(token, cache=30)
token_price = self.price_cache[token]["price"]
if token_price == 0:
raise Exception("Error getting price from CoinStats")
except Exception as e:
print(str(e))
print("Getting price from CryptoCompare...")
Expand All @@ -258,7 +262,7 @@ def get_token_price(self, token):
HEADERS = {'authorization' : "Apikey %s" % scrtsxx.CCOMPAREAPI}
try:
r = http.get(scrtsxx.CCOMPARE_API_URL % token.upper(), headers=HEADERS)
sentinel_price = r.json()['USD']
token_price = r.json()['USD']
except Exception as e:
print(str(e))
return 0
Expand Down
Binary file removed src/fonts/Roboto-BoldItalic.ttf
Binary file not shown.
10 changes: 7 additions & 3 deletions src/typedef/konstants.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,8 @@ class HTTParams():
SERVER_URL = "https://aimokoivunen.mathnodes.com:5000"
RPC = "https://rpc.mathnodes.com:443"
# Note http://128.199.90.172:26657 is testnet ONLY!
RPCS = ['https://rpc.mathnodes.com:443', 'https://rpc.sentinel.co:443', 'https://sentinel-rpc.badgerbite.io:443',
'https://sentinel-rpc2.badgerbite.io:443', 'https://rpc.sentinel.quokkastake.io:443', 'https://rpc-sentinel.whispernode.com:443',
'https://rpc-sentinel-ia.cosmosia.notional.ventures:443']
RPCS = ['https://rpc.mathnodes.com:443', 'https://rpc.dvpn.me:443', 'https://rpc.sentinel.co:443', 'https://sentinel-rpc.badgerbite.io:443',
'https://sentinel-rpc2.badgerbite.io:443', 'https://rpc.sentinel.quokkastake.io:443', 'https://rpc-sentinel.whispernode.com:443']
GRPC = "grpc+http://aimokoivunen.mathnodes.com:9090/"
#GRPC = "grpc+http://128.199.90.172:9090/"
HEALTH_CHECK = "https://api.health.sentinel.co/v1/records"
Expand All @@ -46,6 +45,10 @@ class HTTParams():
API_RATING_ENDPOINT = "/api/rating"
SESSIONS_API_URL = '/sentinel/accounts/%s/sessions'
BALANCES_ENDPOINT = "/bank/balances/"
ICANHAZURL = "https://icanhazip.com"
ICANHAZDNS = "icanhazip.com"
IFCONFIGDNS = "ifconfig.co"
IFCONFIGURL = "https://ifconfig.co/json"


class IBCTokens():
Expand Down Expand Up @@ -77,6 +80,7 @@ class MeileColors():
MAP_MARKER = "../imgs/location_pin.png"
HEALTH_ICON = "shield-plus"
SICK_ICON = "emoticon-sick"
ARCGIS_MAP = "https://server.arcgisonline.com/arcgis/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{y}/{x}.png"

class NodeKeys():
NodesInfoKeys = ["Moniker","Address","Price","Hourly Price", "Country","Speed","Latency","Peers","Handshake","Type","Version","Status"]
Expand Down
2 changes: 0 additions & 2 deletions src/typedef/win.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
ICANHAZURL = "https://icanhazip.com"
ICANHAZDNS = "icanhazip.com"

class WindowNames():
WALLET_RESTORE = "walletrestore"
Expand Down
91 changes: 70 additions & 21 deletions src/ui/screens.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from geography.continents import OurWorld
from ui.interfaces import Tab, LatencyContent, TooltipMDIconButton
from typedef.win import WindowNames, ICANHAZURL, ICANHAZDNS
from ui.interfaces import Tab, LatencyContent, TooltipMDIconButton, ConnectionDialog
from typedef.win import WindowNames
from cli.sentinel import NodeTreeData
from typedef.konstants import NodeKeys, TextStrings, MeileColors, HTTParams, IBCTokens
from cli.sentinel import disconnect as Disconnect
Expand Down Expand Up @@ -219,16 +219,16 @@ def runNodeThread(self):
yield 0.6
thread2 = Thread(target=lambda: self.progress_load())
thread2.start()
thread = Thread(target=lambda: self.NodeTree.get_nodes("13s"))
thread = Thread(target=lambda: self.NodeTree.get_nodes("23s"))
thread.start()

Clock.schedule_interval(partial(self.update_status_text, thread), 1.6)

@delayable
def progress_load(self):
for k in range(1,1000):
for k in range(1,2000):
yield 0.0375
self.manager.get_screen(WindowNames.PRELOAD).ids.pb.value += 0.001
self.manager.get_screen(WindowNames.PRELOAD).ids.pb.value += 0.0005


def CopyBin(self):
Expand Down Expand Up @@ -341,6 +341,7 @@ class MainWindow(Screen):
ConnectedDict = {'v2ray_pid' : None, 'result' : False}
NodeWidget = None
Markers = []
LatLong = []


def __init__(self, node_tree, **kwargs):
Expand Down Expand Up @@ -392,9 +393,9 @@ def build_meile_map(self):

if not self.MeileMapBuilt:
self.MeileMap = MapView(lat=50.6394, lon=3.057, zoom=2)
source = MapSource(url="https://server.arcgisonline.com/arcgis/rest/services/Canvas/World_Dark_Gray_Base/MapServer/tile/{z}/{y}/{x}.png",
cache_key="meile-map-canvas-dark-grey-base",
tile_size=512,
source = MapSource(url=MeileColors.ARCGIS_MAP,
cache_key="meile-map-canvas-dark-grey-base-2",
tile_size=256,
image_ext="png",
attribution="@ Meile",
size_hint=(.7,1))
Expand All @@ -415,7 +416,7 @@ def AddCountryNodePins(self, clear):
try:

if clear:
for m in self.Makers:
for m in self.Markers:
self.MeileMap.remove_marker(m)
self.Markers.clear()

Expand Down Expand Up @@ -570,16 +571,33 @@ def get_ip_address(self, dt):

self.old_ip = self.ip
try:
resolver = DNSRequests.MakeDNSRequest(domain=ICANHAZDNS, timeout=1.5, lifetime=2.5)
icanhazip = resolver.DNSRequest()
if icanhazip:
print("%s:%s" % (ICANHAZDNS, icanhazip))
resolver = DNSRequests.MakeDNSRequest(domain=HTTParams.IFCONFIGDNS, timeout=3.5, lifetime=3.5)
ifconfig = resolver.DNSRequest()
if ifconfig:
print("%s:%s" % (HTTParams.IFCONFIGDNS, ifconfig))
Request = HTTPRequests.MakeRequest()
http = Request.hadapter()
req = http.get(ICANHAZURL)
self.ip = req.text

self.manager.get_screen(WindowNames.MAIN_WINDOW).ids.new_ip.text = self.ip
req = http.get(HTTParams.IFCONFIGURL)
ifJSON = req.json()
print(ifJSON)
self.ip = str(ifJSON['ip'])
self.ids.new_ip.text = self.ip
self.LatLong.clear()
try:
self.LatLong.append(ifJSON['latitude'])
self.LatLong.append(ifJSON['longitude'])
except:
print("No Lat/Long")
try:
country = ifJSON['country']
loc = self.MeileLand.CountryLatLong[country]
self.LatLong.append(loc[0])
self.LatLong.append(loc[1])
except:
print("No Country...Defaulting to my dream.")
loc = self.MeileLand.CountryLatLong["Seychelles"]
self.LatLong.append(loc[0])
self.LatLong.append(loc[1])
return True
#self.manager.get_screen(WindowNames.MAIN_WINDOW).ids.old_ip.text = "Old IP: " + self.old_ip
else:
Expand Down Expand Up @@ -761,13 +779,21 @@ def Refresh(self, latency, *kwargs):
self.remove_loading_widget(None)
self.AddCountryNodePins(True)
yield 0.314
self.add_loading_popup("Reloading Nodes...")
cd = ConnectionDialog()
self.set_conn_dialog(cd, "Reloading Nodes...")
yield 0.314
try:
self.NodeTree.NodeTree = None
thread = ThreadWithResult(target=self.NodeTree.get_nodes, args=(latency.return_latency(),))
thread.start()
thread.join()
t = Thread(target=lambda: self.NodeTree.get_nodes(latency.return_latency()))
t.start()
l = int(latency.return_latency().split('s')[0])
pool = l*100
inc = float(1/pool)
while t.is_alive():
yield 0.0365
cd.ids.pb.value += inc

cd.ids.pb.value = 1
except Exception as e:
print(str(e))
pass
Expand Down Expand Up @@ -817,6 +843,7 @@ def on_tab_switch(self, instance_tabs, instance_tab, instance_tabs_label, tab_te
pass
def get_continent_coordinates(self, c):
loc = self.MeileLand.ContinentLatLong[c]
self.MeileMap.zoom = 4
self.MeileMap.center_on(loc[0], loc[1])

def build_node_data(self, ncountry):
Expand Down Expand Up @@ -872,6 +899,28 @@ def switch_to_sub_window(self):
self.carousel.add_widget(self.NodeWidget)
self.carousel.load_slide(self.NodeWidget)

def close_sub_window(self):
self.carousel.remove_widget(self.NodeWidget)
self.carousel.load_previous()

def zoom_country_map(self):
try:
self.MeileMap.zoom = 7
self.MeileMap.center_on(self.LatLong[0],self.LatLong[1])
except Exception as e:
print(str(e))
pass

def set_conn_dialog(self, cd, title):
self.dialog = None
self.dialog = MDDialog(
title=title,
type="custom",
content_cls=cd,
md_bg_color=get_color_from_hex(MeileColors.DIALOG_BG_COLOR),
)
self.dialog.open()

def load_country_nodes(self, country, *kwargs):
mw = Meile.app.root.get_screen(WindowNames.MAIN_WINDOW)
NodeTree = NodeTreeData(Meile.app.root.get_screen(WindowNames.MAIN_WINDOW).NodeTree.NodeTree)
Expand Down
4 changes: 4 additions & 0 deletions src/ui/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -936,8 +936,12 @@ def call_ip_get(self,result, moniker, *kwargs):
if not mw.get_ip_address(None):
self.remove_loading_widget()
self.change_dns()
mw.close_sub_window()
mw.zoom_country_map()
else:
self.remove_loading_widget()
mw.close_sub_window()
mw.zoom_country_map()

@delayable
def change_dns(self):
Expand Down

0 comments on commit 027d668

Please sign in to comment.