Debugged Code

This commit is contained in:
Kaushal Kumar Agarwal 2018-10-01 20:14:09 +05:30
parent 3b17810e63
commit ffaa7e27ed

290
main.py
View File

@ -3,6 +3,7 @@ from tkinter import *
from tkinter import messagebox from tkinter import messagebox
import subprocess import subprocess
import os import os
import sys
import webbrowser import webbrowser
import json import json
import math import math
@ -23,12 +24,12 @@ def findHash(data):
return str(result.hexdigest()) return str(result.hexdigest())
def isConnected(): def isConnected():
try: try:
socket.create_connection(("www.github.com", 80)) socket.create_connection(("www.github.com", 80))
return True return True
except: except:
messagebox.showerror('FLOappStore', "Unable to Connect to GitHub!\nPlease check Internet connectivity and firewall!") messagebox.showerror('FLOappStore', "Unable to Connect to GitHub!\nPlease check Internet connectivity and firewall!")
return False return False
def readUnitFromBlockchain(txid): def readUnitFromBlockchain(txid):
rawtx = subprocess.check_output(["flo-cli","--testnet", "getrawtransaction", str(txid)]) rawtx = subprocess.check_output(["flo-cli","--testnet", "getrawtransaction", str(txid)])
@ -41,14 +42,17 @@ def readUnitFromBlockchain(txid):
def Dappend(Dapps,app): def Dappend(Dapps,app):
i = searchDict(Dapps,'id',app['id']) i = searchDict(Dapps,'id',app['id'])
#print(str(i))
if (i!=-1): if (i!=-1):
del(Dapps[i]) del(Dapps[i])
#print(app.keys())
if ('remove' not in app.keys()): if ('remove' not in app.keys()):
Dapps = Dapps + [app] Dapps = Dapps + [app]
return Dapps return Dapps
def verifyHash(localHash,txid): def verifyHash(localHash,txid):
content = readUnitFromBlockchain(txid) content = readUnitFromBlockchain(txid)
#print(content)
try: try:
if(json.loads(content)['hash'] == localHash): if(json.loads(content)['hash'] == localHash):
return True return True
@ -59,13 +63,19 @@ def verifyHash(localHash,txid):
def getJsonData(Dapps, lastTx): def getJsonData(Dapps, lastTx):
r = requests.get("https://testnet.florincoin.info/ext/getaddress/"+JsonAddress) try:
data = json.loads(r.content) r = requests.get("https://testnet.florincoin.info/ext/getaddress/"+JsonAddress)
#print(data) data = json.loads(r.content)
except:
isConnected()
return
#print(Dapps)
localHash = findHash(str(Dapps)) localHash = findHash(str(Dapps))
try: try:
if(lastTx == -1 or not verifyHash(localHash,data['last_txs'][lastTx]['addresses'])): if(lastTx == -1 or not verifyHash(localHash,data['last_txs'][lastTx]['addresses'])):
lastTx = 0 lastTx = 0
else:
lastTx = lastTx+1
except: except:
lastTx = 0 lastTx = 0
#print(lastTx) #print(lastTx)
@ -86,152 +96,152 @@ def getJsonData(Dapps, lastTx):
return (Dapps,len(data['last_txs'])-1) return (Dapps,len(data['last_txs'])-1)
class FLOappStore: class FLOappStore:
def __init__(self, root): def __init__(self, root):
self.root = root self.root = root
self.maxRow=5 self.maxRow=5
self.maxCol=2 self.maxCol=2
def start(self): def start(self):
self.MainFrame = Frame(self.root) self.MainFrame = Frame(self.root)
self.MainFrame.pack() self.MainFrame.pack()
WelcomeLabel = Label(self.MainFrame,text="FLO AppStore",font=("Arial", 20)) WelcomeLabel = Label(self.MainFrame,text="FLO AppStore",font=("Arial", 20))
WelcomeLabel.grid(row=1,column = 1,columnspan=2) WelcomeLabel.grid(row=1,column = 1,columnspan=2)
self.searchBox=Entry(self.MainFrame) self.searchBox=Entry(self.MainFrame)
self.searchBox.grid(row=2,column=1,sticky="E") self.searchBox.grid(row=2,column=1,sticky="E")
self.searchButton=Button(self.MainFrame,text="Search",command = self.searchApps) self.searchButton=Button(self.MainFrame,text="Search",command = self.searchApps)
self.searchButton.grid(row=2,column=2,sticky="W") self.searchButton.grid(row=2,column=2,sticky="W")
self.searchApps() self.searchApps()
def clearSearch(self): def clearSearch(self):
self.searchBox.delete(0, 'end') self.searchBox.delete(0, 'end')
self.searchApps() self.searchApps()
def searchApps(self): def searchApps(self):
try: try:
self.clearSearchButton.destroy() self.clearSearchButton.destroy()
except: except:
None None
self.searchResult=[] self.searchResult=[]
searchText=self.searchBox.get() searchText=self.searchBox.get()
if(searchText != ""): if(searchText != ""):
self.clearSearchButton=Button(self.MainFrame,text="Clear Search",command = self.clearSearch) self.clearSearchButton=Button(self.MainFrame,text="Clear Search",command = self.clearSearch)
self.clearSearchButton.grid(row=2,column=2,sticky="N") self.clearSearchButton.grid(row=2,column=2,sticky="N")
for app in apps: for app in apps:
if (searchText.lower() in app["name"].lower()): if (searchText.lower() in app["name"].lower()):
self.searchResult = self.searchResult + [app] self.searchResult = self.searchResult + [app]
self.totalPage = math.ceil(len(self.searchResult)/(self.maxRow*self.maxCol)) self.totalPage = math.ceil(len(self.searchResult)/(self.maxRow*self.maxCol))
self.listApps(1) self.listApps(1)
def listApps(self,pageNum): def listApps(self,pageNum):
try: try:
self.listFrame.destroy() self.listFrame.destroy()
except: except:
None None
self.listFrame = Frame(self.MainFrame) self.listFrame = Frame(self.MainFrame)
if not len(self.searchResult): if not len(self.searchResult):
noResultLabel = Label(self.listFrame,text="No Apps found!") noResultLabel = Label(self.listFrame,text="No Apps found!")
noResultLabel.grid() noResultLabel.grid()
self.listFrame.grid(column=1,columnspan=2) self.listFrame.grid(column=1,columnspan=2)
return return
if pageNum<1: if pageNum<1:
pageNum=self.totalPage pageNum=self.totalPage
elif pageNum>self.totalPage: elif pageNum>self.totalPage:
pageNum=1 pageNum=1
self.icon=[] self.icon=[]
self.appButton=[] self.appButton=[]
Xrow=1 Xrow=1
Xcol=1 Xcol=1
startIndex=(pageNum-1)*(self.maxRow*self.maxCol) startIndex=(pageNum-1)*(self.maxRow*self.maxCol)
for app in self.searchResult[startIndex:]: for app in self.searchResult[startIndex:]:
try: try:
img=PhotoImage(file=app["icon"]) img=PhotoImage(file=app["icon"])
except: except:
img=PhotoImage(file='Icon/noimage.png') img=PhotoImage(file='Icon/noimage.png')
self.icon= self.icon+[img] self.icon= self.icon+[img]
self.appButton = self.appButton + [Button(self.listFrame,text=app["name"],image = self.icon[-1],compound="left",width="500",height="50",command=lambda app=app:self.execute(app))] self.appButton = self.appButton + [Button(self.listFrame,text=app["name"],image = self.icon[-1],compound="left",width="500",height="50",command=lambda app=app:self.execute(app))]
self.appButton[-1].grid(row = Xrow,column = Xcol) self.appButton[-1].grid(row = Xrow,column = Xcol)
Xcol=Xcol+1 Xcol=Xcol+1
if (Xcol>self.maxCol): if (Xcol>self.maxCol):
Xcol=1 Xcol=1
Xrow=Xrow+1 Xrow=Xrow+1
if (Xrow>self.maxRow): if (Xrow>self.maxRow):
break break
prevButton = Button(self.listFrame,text="Prev",command=lambda :self.listApps(pageNum-1)) prevButton = Button(self.listFrame,text="Prev",command=lambda :self.listApps(pageNum-1))
nextButton = Button(self.listFrame,text="Next",command=lambda :self.listApps(pageNum+1)) nextButton = Button(self.listFrame,text="Next",command=lambda :self.listApps(pageNum+1))
pageLabel = Label(self.listFrame,text=f"{pageNum}/{self.totalPage}") pageLabel = Label(self.listFrame,text=f"{pageNum}/{self.totalPage}")
prevButton.grid(row=self.maxRow+1,column=1,columnspan=self.maxCol,sticky="W") prevButton.grid(row=self.maxRow+1,column=1,columnspan=self.maxCol,sticky="W")
nextButton.grid(row=self.maxRow+1,column=1,columnspan=self.maxCol,sticky="NE") nextButton.grid(row=self.maxRow+1,column=1,columnspan=self.maxCol,sticky="NE")
pageLabel.grid(row=self.maxRow+1,column=1,columnspan=self.maxCol,sticky="N") pageLabel.grid(row=self.maxRow+1,column=1,columnspan=self.maxCol,sticky="N")
self.listFrame.grid(column=1,columnspan=2) self.listFrame.grid(column=1,columnspan=2)
def execute(self,app): def execute(self,app):
print(app["name"]) #print(app["name"])
isConnected() isConnected()
self.appWin = Toplevel() self.appWin = Toplevel()
self.appWin.title(app["name"]) self.appWin.title(app["name"])
#self.appWin.geometry("500x100") #self.appWin.geometry("500x100")
#self.appWin.resizable(0,0) #self.appWin.resizable(0,0)
if(app["type"] == "Gui" or app["type"] == "Cmdline"): if(app["type"] == "Gui" or app["type"] == "Cmdline"):
if(os.path.isdir(app["location"]) and subprocess.Popen("git config --get remote.origin.url",cwd=app["location"],stdout=subprocess.PIPE,shell=True).communicate()[0].decode("utf-8").strip()==app["github"]): if(os.path.isdir(app["location"]) and subprocess.Popen("git config --get remote.origin.url",cwd=app["location"],stdout=subprocess.PIPE,shell=True).communicate()[0].decode("utf-8").strip()==app["github"]):
openButton = Button(self.appWin,text="Open App",command=lambda :self.openApp(app)) openButton = Button(self.appWin,text="Open App",command=lambda :self.openApp(app))
openButton.pack() openButton.pack()
if(subprocess.Popen("git diff --raw",cwd=app["location"],stdout=subprocess.PIPE,shell=True).communicate()[0].decode("utf-8")!=""): if(subprocess.Popen("git diff --raw",cwd=app["location"],stdout=subprocess.PIPE,shell=True).communicate()[0].decode("utf-8")!=""):
updateButton = Button(self.appWin,text="Update App",command=lambda :self.updateApp(app)) updateButton = Button(self.appWin,text="Update App",command=lambda :self.updateApp(app))
updateButton.pack() updateButton.pack()
removeButton = Button(self.appWin,text="Remove App",command=lambda :self.removeApp(app)) removeButton = Button(self.appWin,text="Remove App",command=lambda :self.removeApp(app))
removeButton.pack() removeButton.pack()
else: else:
downloadButton = Button(self.appWin,text="Download App",command=lambda :self.downloadApp(app)) downloadButton = Button(self.appWin,text="Download App",command=lambda :self.downloadApp(app))
downloadButton.pack() downloadButton.pack()
elif(app["type"] == "Webapp"): elif(app["type"] == "Webapp"):
openButton = Button(self.appWin,text="Open Browser",command=lambda :self.openBrowserApp(app)) openButton = Button(self.appWin,text="Open Browser",command=lambda :self.openBrowserApp(app))
openButton.pack() openButton.pack()
self.appWin.mainloop() self.appWin.mainloop()
def downloadApp(self,app): def downloadApp(self,app):
self.appWin.destroy() self.appWin.destroy()
subprocess.Popen(['rm', '-rf', app['location']]) subprocess.Popen(['rm', '-rf', app['location']])
if(not isConnected()): if(not isConnected()):
return return
subprocess.Popen("gnome-terminal -- git clone %s"%(app["github"]),cwd="apps/",shell=True) subprocess.Popen("gnome-terminal -- git clone %s"%(app["github"]),cwd="apps/",shell=True)
messagebox.showinfo(app['name'], f"Downloading {app['name']}...\n Please Wait until the downloader closes") messagebox.showinfo(app['name'], f"Downloading {app['name']}...\n Please Wait until the downloader closes")
def removeApp(self,app): def removeApp(self,app):
self.appWin.destroy() self.appWin.destroy()
subprocess.Popen(['rm', '-rf', app['location']]) subprocess.Popen(['rm', '-rf', app['location']])
messagebox.showinfo(app['name'], f"Removed {app['name']}...") messagebox.showinfo(app['name'], f"Removed {app['name']}...")
def updateApp(self,app): def updateApp(self,app):
self.appWin.destroy() self.appWin.destroy()
if(not isConnected()): if(not isConnected()):
return return
subprocess.Popen("gnome-terminal -- git pull --all",cwd=app['location'],shell=True) subprocess.Popen("gnome-terminal -- git pull --all",cwd=app['location'],shell=True)
subprocess.Popen("gnome-terminal -- git reset --hard HEAD ",cwd=app['location'],shell=True) subprocess.Popen("gnome-terminal -- git reset --hard HEAD ",cwd=app['location'],shell=True)
messagebox.showinfo(app['name'], f"Updating {app['name']}...\n Please Wait until the updater closes") messagebox.showinfo(app['name'], f"Updating {app['name']}...\n Please Wait until the updater closes")
def openApp(self,app): def openApp(self,app):
self.appWin.destroy() self.appWin.destroy()
if(app["type"] == "Gui"): if(app["type"] == "Gui"):
subprocess.Popen(app["exec"], cwd=app["location"]) subprocess.Popen(app["exec"], cwd=app["location"])
elif(app["type"] == "Cmdline"): elif(app["type"] == "Cmdline"):
subprocess.Popen("gnome-terminal --command 'bash -c %s;bash'"%(app["exec"]),cwd=app["location"],stdout=subprocess.PIPE,shell=True) subprocess.Popen("gnome-terminal --command 'bash -c %s;bash'"%(app["exec"]),cwd=app["location"],stdout=subprocess.PIPE,shell=True)
def openBrowserApp(self,app): def openBrowserApp(self,app):
self.appWin.destroy() self.appWin.destroy()
webbrowser.open(app["url"],new=1) webbrowser.open(app["url"],new=1)
''' '''
if(isConnected()): if(isConnected()):
subprocess.call("git pull",shell=True) subprocess.call("git pull",shell=True)
else: else:
exit(0) exit(0)
with open('AppData.json',encoding='utf-8') as F: with open('AppData.json',encoding='utf-8') as F:
apps=json.loads(F.read())["Dapps"] apps=json.loads(F.read())["Dapps"]
''' '''
try: try:
with open('Apps.json','r') as F: with open('Apps.json','r') as F:
@ -242,7 +252,11 @@ except:
apps = [] apps = []
lastTx = -1 lastTx = -1
(apps,lastTx) = getJsonData(apps,lastTx) try:
(apps,lastTx) = getJsonData(apps,lastTx)
except:
sys.exit(1)
with open('Apps.json','w+') as F: with open('Apps.json','w+') as F:
data = json.dumps({'Dapps':apps ,'lastTx':lastTx}) data = json.dumps({'Dapps':apps ,'lastTx':lastTx})