diff --git a/.gitignore b/.gitignore index 07ebf02..4083645 100644 --- a/.gitignore +++ b/.gitignore @@ -10,4 +10,5 @@ __pycache__/ .vscode/ cooks/*.yaml control/ -site/ \ No newline at end of file +site/ +admin/ \ No newline at end of file diff --git a/BD/emptydatabase.db b/BD/emptydatabase.db index df8146e..e27cf54 100644 Binary files a/BD/emptydatabase.db and b/BD/emptydatabase.db differ diff --git a/api.py b/api.py index 1dcf324..f1947bb 100644 --- a/api.py +++ b/api.py @@ -1,14 +1,16 @@ #!/usr/bin/python3 BUILD = 24 -API_VER = 1 -##It can be run directly with "waitress-serve --port=3333 api:api" -import falcon +API_VER = 2 +from flask import Flask, request import random import os import time import sql # SQL work file import json,yaml from datetime import datetime +import base64 + +app = Flask(__name__) sqlAddComputers = sql.retOption('AddComputers') @@ -27,6 +29,7 @@ def retPassword(): except: return "" + ## # getComputerExists: Know if computer exists and matches UUID # /get/computerexists? @@ -37,37 +40,37 @@ def retPassword(): # 2: Computer and UUID not match database # 3: Computer doesn't exists in database ## -class getComputerExists(object): - def on_get(self, request, response): - logit(request) - ComputerName,UUID = None, None - for key, value in request.params.items(): - if key == "ComputerName": - ComputerName = value - if key == "UUID": - UUID = value +@app.route("/get/computerexists",methods=['POST']) +def getComputerExists(): + logit(request.base_url) + ComputerName,UUID = None, None + for key, value in request.args.to_dict().items(): + if key == "ComputerName": + ComputerName = value + if key == "UUID": + UUID = value - if ComputerName is None: - response.media = {'TEXT':'No params','RESULT': 'ERROR','EXITCODE':'1'} - else: - result = sql.select("SELECT COUNT(*) 'RESULT' FROM COMPUTERS WHERE Name='"+ComputerName+"' AND UUID='"+UUID+"'") + if ComputerName is None: + return str({'TEXT':'No params','RESULT': 'ERROR','EXITCODE':'1'}) + else: + result = sql.select("SELECT COUNT(*) 'RESULT' FROM COMPUTERS WHERE Name='"+ComputerName+"' AND UUID='"+UUID+"'") - if result[0]['RESULT'] == 0: # 0 or 1 - if sql.select("SELECT COUNT(*) 'RESULT' FROM COMPUTERS WHERE Name='"+ComputerName+"' AND UUID IS NULL")[0]['RESULT'] != 0: #UUID doesn't in database, insert it - sql.insert("UPDATE COMPUTERS SET UUID='"+UUID+"' WHERE Name='"+ComputerName+"'") - response.media = {'RESULT': '1'} - return - elif sql.select("SELECT COUNT(*) 'RESULT' FROM COMPUTERS WHERE Name='"+ComputerName+"'")[0]['RESULT'] != 0: #Not UUID match, but computer exists - response.media = {'TEXT': 'Error, computer and UUID doesn\'t match in database', 'RESULT': 'ERROR','EXITCODE':'2'} - return - if sqlAddComputers == True: #Computer doesn't exist, but you have enabled add all computers - sql.insert("INSERT INTO COMPUTERS (`Name`,`UUID`) VALUES('"+ComputerName+"','"+UUID+"')") - response.media = {'RESULT': '1'} - else: #Computer doesn't exist and you don't want to be added - response.media = {'TEXT':'Error: Computer not exists in database', 'RESULT': 'ERROR','EXITCODE':'3'} + if result[0]['RESULT'] == 0: # 0 or 1 + if sql.select("SELECT COUNT(*) 'RESULT' FROM COMPUTERS WHERE Name='"+ComputerName+"' AND UUID IS NULL")[0]['RESULT'] != 0: #UUID doesn't in database, insert it + sql.insert("UPDATE COMPUTERS SET UUID='"+UUID+"' WHERE Name='"+ComputerName+"'") + return str({'RESULT': '1'}) + return + elif sql.select("SELECT COUNT(*) 'RESULT' FROM COMPUTERS WHERE Name='"+ComputerName+"'")[0]['RESULT'] != 0: #Not UUID match, but computer exists + return str({'TEXT': 'Error, computer and UUID doesn\'t match in database', 'RESULT': 'ERROR','EXITCODE':'2'}) + return + if sqlAddComputers == True: #Computer doesn't exist, but you have enabled add all computers + sql.insert("INSERT INTO COMPUTERS (`Name`,`UUID`) VALUES('"+ComputerName+"','"+UUID+"')") + return str({'RESULT': '1'}) + else: #Computer doesn't exist and you don't want to be added + return str({'TEXT':'Error: Computer not exists in database', 'RESULT': 'ERROR','EXITCODE':'3'}) - else: #Exists - response.media = {'RESULT': '1'} + else: #Exists + return str({'RESULT': '1'}) ## @@ -75,44 +78,45 @@ class getComputerExists(object): # /get/groups? # @param ComputerName/ComputerID -> Computer to see groups (Not neccesary) ## -class getGroups(object): #Get local groups of a Computer - def on_get(self,request, response): - logit(request) - ComputerID=None - for key, value in request.params.items(): - if key == "ComputerName": - ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) - if key == "ComputerID": - ComputerID = value +@app.route("/get/groups",methods=['POST']) +def getGroups(): #Get local groups of a Computer + logit(request.base_url) + ComputerID=None + for key, value in request.args.to_dict().items(): + if key == "ComputerName": + ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) + if key == "ComputerID": + ComputerID = value - if ComputerID is None: - data = sql.select("SELECT * FROM GROUPS ORDER BY Name ASC") - response.media = data - else: - data = sql.select("SELECT * FROM GROUPS WHERE ID_G IN (SELECT ID_G FROM COMPUTER_GROUP WHERE ID_C = '"+ComputerID+"') ORDER BY Name ASC") - response.media = data + if ComputerID is None: + data = sql.select("SELECT * FROM GROUPS ORDER BY Name ASC") + return str(data) + else: + data = sql.select("SELECT * FROM GROUPS WHERE ID_G IN (SELECT ID_G FROM COMPUTER_GROUP WHERE ID_C = '"+ComputerID+"') ORDER BY Name ASC") + return str(data) ## # getComputers: List all computers with data # /get/computers? # @param ComputerID/ComputerName -> To see all data only for one computer ## -class getComputers(object): - def on_get(self,request, response): - logit(request) - ComputerID=None - for key, value in request.params.items(): - if key == "ComputerName": - ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"' LIMIT 1")[0]['ID_C']) - if key == "ComputerID": - ComputerID = value +@app.route("/get/computers",methods=['POST']) +def getComputers(): + + logit(request.base_url) + ComputerID=None + for key, value in request.args.to_dict().items(): + if key == "ComputerName": + ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"' LIMIT 1")[0]['ID_C']) + if key == "ComputerID": + ComputerID = value - if ComputerID is not None: # One computer - data = sql.select("SELECT * FROM COMPUTERS WHERE ID_C = '"+ComputerID+"') ORDER BY Name ASC LIMIT 1") - response.media = data - else: # All computers - data = sql.select("SELECT * FROM COMPUTERS ORDER BY Name ASC") - response.media = data + if ComputerID is not None: # One computer + data = sql.select("SELECT * FROM COMPUTERS WHERE ID_C = '"+ComputerID+"') ORDER BY Name ASC LIMIT 1") + return str(data) + else: # All computers + data = sql.select("SELECT * FROM COMPUTERS ORDER BY Name ASC") + return str(data) ## @@ -120,28 +124,28 @@ class getComputers(object): # /get/computersgrp? # @param GroupName/GroupID -> Group to see computers ## -class getComputersGrp(object): #List of computers in a group - def on_get(self,request, response): - logit(request) - GroupID=None - for key, value in request.params.items(): - if key == "GroupName": - GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) - if key == "GroupID": - GroupID = value - data = sql.select("SELECT * FROM COMPUTERS WHERE ID_C IN (SELECT ID_C FROM COMPUTER_GROUP WHERE ID_G='"+GroupID+"') ORDER BY Name") - response.media = data +@app.route("/get/computersgrp",methods=['POST']) +def getComputersGrp(): + logit(request.base_url) + GroupID=None + for key, value in request.args.to_dict().items(): + if key == "GroupName": + GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) + if key == "GroupID": + GroupID = value + data = sql.select("SELECT * FROM COMPUTERS WHERE ID_C IN (SELECT ID_C FROM COMPUTER_GROUP WHERE ID_G='"+GroupID+"') ORDER BY Name") + return str(data) ## # getCookAll: Get the list of cooks added at least to one group # /get/cookall? # NoParams ## -class getCookAll(object): - def on_get(self,request, response): - logit(request) - data = sql.select("SELECT DISTINCT CookName FROM COOKS_IDG ORDER BY CookName ASC") #All cooks - response.media = data +@app.route("/get/cookall",methods=['POST']) +def getCookAll(): + logit(request.base_url) + data = sql.select("SELECT DISTINCT CookName FROM COOKS_IDG ORDER BY CookName ASC") #All cooks + return str(data) ## @@ -152,41 +156,42 @@ class getCookAll(object): # @param SeeAll: Send all cooks from this computer # @param UUID: Check UUID validation of this computer (Not implemented yet) ## -class getCookPend(object): # Get the list of cooks for a computer to implement (Var all=1 for see all of, implemented or not) - def on_get(self,request, response): - logit(request) - ComputerID,GroupID, SeeAll =None, None, None - for key, value in request.params.items(): - if key == "ComputerName": - ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) - if key == "ComputerID": - ComputerID = value - if key == "GroupName": - GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) - if key == "GroupID": - GroupID = value - if key == "SeeAll": - SeeAll = str(value) +@app.route("/get/cookpend",methods=['POST']) +def getCookPend(): # Get the list of cooks for a computer to implement (Var all=1 for see all of, implemented or not) + + logit(request.base_url) + ComputerID,GroupID, SeeAll =None, None, None + for key, value in request.args.to_dict().items(): + if key == "ComputerName": + ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) + if key == "ComputerID": + ComputerID = value + if key == "GroupName": + GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) + if key == "GroupID": + GroupID = value + if key == "SeeAll": + SeeAll = str(value) - if ComputerID is None and GroupID is None: # Error of null parameters - response.media = {'TEXT': 'I need a Group or Computer to search','RESULT':'ERROR'} - elif ComputerID is not None and SeeAll is None: - data = sql.select("SELECT DISTINCT CookName FROM COOKS_IDG WHERE ID_G IN (SELECT ID_G FROM COMPUTER_GROUP WHERE ID_C = '"+ComputerID+"')") #All cooks for this computer - fordelete = [] - for i in range(len(data)): - for key, value in data[i].items(): #Iterate in a dict (json) - if key == 'CookName': - CookName = value #Name - with open('cooks/'+CookName+'.yaml', 'r') as myfile: - filecook = myfile.read() - coun = sql.select("SELECT COUNT(*) 'RESULT' FROM COOKS_STATUS WHERE ID_C='"+ComputerID+"' AND CookName='"+CookName+"' AND Revision='"+str(yaml.safe_load(filecook)['revision'])+"' AND `Error`='0'") - if coun[0]['RESULT'] == 1: - fordelete.append(i) #Its good, do not say to client - for x in reversed(fordelete): #Deleting cooks that are implemented in client. Reverse order (Because is an array and index..) - data.pop(x) - response.media = data - else: # SeeAll. Send all cooks - response.media = sql.select("SELECT DISTINCT CookName FROM COOKS_IDG WHERE ID_G IN (SELECT ID_G FROM COMPUTER_GROUP WHERE ID_C = '"+ComputerID+"') ORDER BY CookName ASC") #All cooks for this computer + if ComputerID is None and GroupID is None: # Error of null parameters + return str({'TEXT': 'I need a Group or Computer to search','RESULT':'ERROR'}) + elif ComputerID is not None and SeeAll is None: + data = sql.select("SELECT DISTINCT CookName FROM COOKS_IDG WHERE ID_G IN (SELECT ID_G FROM COMPUTER_GROUP WHERE ID_C = '"+ComputerID+"')") #All cooks for this computer + fordelete = [] + for i in range(len(data)): + for key, value in data[i].items(): #Iterate in a dict (json) + if key == 'CookName': + CookName = value #Name + with open('cooks/'+CookName+'.yaml', 'r') as myfile: + filecook = myfile.read() + coun = sql.select("SELECT COUNT(*) 'RESULT' FROM COOKS_STATUS WHERE ID_C='"+ComputerID+"' AND CookName='"+CookName+"' AND Revision='"+str(yaml.safe_load(filecook)['revision'])+"' AND `Error`='0'") + if coun[0]['RESULT'] == 1: + fordelete.append(i) #Its good, do not say to client + for x in reversed(fordelete): #Deleting cooks that are implemented in client. Reverse order (Because is an array and index..) + data.pop(x) + return str(data) + else: # SeeAll. Send all cooks + return str(sql.select("SELECT DISTINCT CookName FROM COOKS_IDG WHERE ID_G IN (SELECT ID_G FROM COMPUTER_GROUP WHERE ID_C = '"+ComputerID+"') ORDER BY CookName ASC")) #All cooks for this computer ## # addCookGrp: Assign Cook to group @@ -195,29 +200,30 @@ class getCookPend(object): # Get the list of cooks for a computer to implement ( # @param CookName -> Cook to assign # @param Password -> Password to validate ## -class addCookGrp(object): #Assign Cook to group - def on_get(self, request, response): - logit(request) - GroupID, CookName, Password = None, None, None # Initialize - for key, value in request.params.items(): - if key == "CookName": - exists = os.path.isfile('cooks/'+value+'.yaml') - CookName = value - if key == "GroupName": - GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) - if key == "GroupID": - GroupID = value - if key == "Password" and value == retPassword(): - Password=value - if GroupID is None or exists is False: - response.media = {'TEXT': 'GroupID is not defined or Cook not exists','RESULT':'ERROR'} - elif Password is None: # Validate password - response.media = {'TEXT': 'Invalid password','RESULT':'ERROR'} - elif int(sql.select("SELECT COUNT(*) 'COUNT' FROM COOKS_IDG WHERE `ID_G`='"+GroupID+"' AND `CookName`='"+CookName+"'")[0]['COUNT']) > 0: - response.media = {'TEXT': 'This union GROUP-CookName exists','RESULT':'0'} - else: - result = sql.insert("INSERT INTO COOKS_IDG (`ID_G`,`CookName`) VALUES ('"+GroupID+"','"+CookName+"')") - response.media = {'TEXT': 'OK'} +@app.route("/add/cookgrp",methods=['POST']) +def addCookGrp(): #Assign Cook to group + + logit(request.base_url) + GroupID, CookName, Password = None, None, None # Initialize + for key, value in request.args.to_dict().items(): + if key == "CookName": + exists = os.path.isfile('cooks/'+value+'.yaml') + CookName = value + if key == "GroupName": + GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) + if key == "GroupID": + GroupID = value + if key == "Password" and value == retPassword(): + Password=value + if GroupID is None or exists is False: + return str({'TEXT': 'GroupID is not defined or Cook not exists','RESULT':'ERROR'}) + elif Password is None: # Validate password + return str({'TEXT': 'Invalid password','RESULT':'ERROR'}) + elif int(sql.select("SELECT COUNT(*) 'COUNT' FROM COOKS_IDG WHERE `ID_G`='"+GroupID+"' AND `CookName`='"+CookName+"'")[0]['COUNT']) > 0: + return str({'TEXT': 'This union GROUP-CookName exists','RESULT':'0'}) + else: + result = sql.insert("INSERT INTO COOKS_IDG (`ID_G`,`CookName`) VALUES ('"+GroupID+"','"+CookName+"')") + return str({'TEXT': 'OK'}) ## # delCookGrp: Delete cook from a group @@ -225,46 +231,48 @@ class addCookGrp(object): #Assign Cook to group # @param GroupName/GroupID -> Group to show cooks # @param CookName -> Cook to assign ## -class delCookGrp(object): #Delete cook from a group - def on_get(self,request,response): - logit(request) - GroupID, CookName = None, None # Initialize - for key, value in request.params.items(): - if key == "CookName": - exists = os.path.isfile('cooks/'+value+'.yaml') - if exists: - CookName = value - if key == "GroupName": - GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) - if key == "GroupID": - GroupID = value +@app.route("/del/cookgrp",methods=['POST']) +def delCookGrp(): #Delete cook from a group + + logit(request.base_url) + GroupID, CookName = None, None # Initialize + for key, value in request.args.to_dict().items(): + if key == "CookName": + exists = os.path.isfile('cooks/'+value+'.yaml') + if exists: + CookName = value + if key == "GroupName": + GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) + if key == "GroupID": + GroupID = value - if GroupID is not None and CookName is not None: - result = sql.insert("DELETE FROM COOKS_IDG WHERE ID_G='"+GroupID+"' AND CookName='"+CookName+"'") - response.media = result - else: - response.media = {'TEXT': 'Error, no Group, or CookName does\'t exists','RESULT':'ERROR'} + if GroupID is not None and CookName is not None: + result = sql.insert("DELETE FROM COOKS_IDG WHERE ID_G='"+GroupID+"' AND CookName='"+CookName+"'") + return str(result) + else: + return str({'TEXT': 'Error, no Group, or CookName does\'t exists','RESULT':'ERROR'}) ## # delEmptyPcsGroup: Delete all computers from from a group # /del/emptypcsgroup? # @param GroupName/GroupID -> Group to delete computers ## -class delEmptyPcsGroup(object): #Delete all computers from a group - def on_get(self,request,response): - logit(request) - GroupID = None # Initialize - for key, value in request.params.items(): - if key == "GroupName": - GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) - if key == "GroupID": - GroupID = value +@app.route("/del/emptypcsgroup",methods=['POST']) +def delEmptyPcsGroup(): + + logit(request.base_url) + GroupID = None # Initialize + for key, value in request.args.to_dict().items(): + if key == "GroupName": + GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) + if key == "GroupID": + GroupID = value - if GroupID is not None: - result = sql.insert("DELETE FROM COMPUTER_GROUP WHERE ID_G='"+GroupID+"'") - response.media = result - else: - response.media = {'TEXT': 'Error, this group doesn\'t exists','RESULT':'ERROR'} + if GroupID is not None: + result = sql.insert("DELETE FROM COMPUTER_GROUP WHERE ID_G='"+GroupID+"'") + return str(result) + else: + return str({'TEXT': 'Error, this group doesn\'t exists','RESULT':'ERROR'}) ## @@ -272,145 +280,152 @@ class delEmptyPcsGroup(object): #Delete all computers from a group # /get/cookgrp? # @param GroupName/GroupID -> Group to show cooks ## -class getCookGrp(object): - def on_get(self,request,response): - logit(request) - GroupID = None # Initialize - for key, value in request.params.items(): - if key == "GroupName": - GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) - if key == "GroupID": - GroupID = value +@app.route("/get/cookgrp",methods=['POST']) +def getCookGrp(): + + logit(request.base_url) + GroupID = None # Initialize + for key, value in request.args.to_dict().items(): + if key == "GroupName": + GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) + if key == "GroupID": + GroupID = value - if GroupID is not None: - result = sql.select("SELECT * FROM COOKS_IDG WHERE ID_G='"+GroupID+"' ORDER BY CookName ASC") - response.media = result - else: - response.media = {'TEXT': 'Error, no Group selected','RESULT':'ERROR'} + if GroupID is not None: + result = sql.select("SELECT * FROM COOKS_IDG WHERE ID_G='"+GroupID+"' ORDER BY CookName ASC") + return str(result) + else: + return str({'TEXT': 'Error, no Group selected','RESULT':'ERROR'}) ## # getGrpCook: Get groups from a Cook # /get/grpcook? # @param CookName -> Cook to show groups ## -class getGrpCook(object): # Get Groups of a Cook - def on_get(self,request,response): - logit(request) - CookName = None # Initialize - for key, value in request.params.items(): - if key == "CookName": - exists = os.path.isfile('cooks/'+value+'.yaml') - if exists: - CookName = value +@app.route("/get/grpcook",methods=['POST']) +def getGrpCook(): + + logit(request.base_url) + CookName = None # Initialize + for key, value in request.args.to_dict().items(): + if key == "CookName": + exists = os.path.isfile('cooks/'+value+'.yaml') + if exists: + CookName = value - if CookName is not None: - response.media = sql.select("SELECT Name FROM GROUPS WHERE ID_G IN (SELECT ID_G FROM COOKS_IDG WHERE CookName='"+CookName+"') ORDER BY Name ASC") - else: - response.media = {'TEXT': 'Error, no Cook selected','RESULT':'ERROR'} + if CookName is not None: + return str(sql.select("SELECT Name FROM GROUPS WHERE ID_G IN (SELECT ID_G FROM COOKS_IDG WHERE CookName='"+CookName+"') ORDER BY Name ASC")) + else: + return str({'TEXT': 'Error, no Cook selected','RESULT':'ERROR'}) ## # getStatusCook: Get groups from a Cook # /get/statuscook? # @param CookName -> Cook to show detailed status ## -class getStatusCook(object): # Get Status of a Cook (If Brief=1 is sent too, brief status (Completed:X, updated:X..)) - def on_get(self,request,response): - logit(request) - CookName = None # Initialize - for key, value in request.params.items(): - if key == "CookName": - exists = os.path.isfile('cooks/'+value+'.yaml') - if exists: - CookName = value +@app.route("/get/statuscook",methods=['POST']) +def getStatusCook(): # Get Status of a Cook (If Brief=1 is sent too, brief status (Completed:X, updated:X..)) + + logit(request.base_url) + CookName = None # Initialize + for key, value in request.args.to_dict().items(): + if key == "CookName": + exists = os.path.isfile('cooks/'+value+'.yaml') + if exists: + CookName = value - if CookName is not None: - response.media = sql.select("SELECT Name, Revision, Error FROM COMPUTERS,COOKS_STATUS WHERE CookName = '"+CookName+"' AND COMPUTERS.ID_C=COOKS_STATUS.ID_C") - else: - response.media = {'TEXT': 'Error, no Cook selected','RESULT':'ERROR'} + if CookName is not None: + return str(sql.select("SELECT Name, Revision, Error FROM COMPUTERS,COOKS_STATUS WHERE CookName = '"+CookName+"' AND COMPUTERS.ID_C=COOKS_STATUS.ID_C")) + else: + return str({'TEXT': 'Error, no Cook selected','RESULT':'ERROR'}) ## # getLastRevisionCook: Get last revision from a Cook # /get/lastrevisioncook? # @param CookName -> Cook to show detailed status ## -class getLastRevisionCook(object): # Get Number Revision (Revision=X) - def on_get(self,request,response): - logit(request) - CookName = None # Initialize - for key, value in request.params.items(): - if key == "CookName": - exists = os.path.isfile('cooks/'+value+'.yaml') - if exists: - CookName = value +@app.route("/get/lastrevisioncook",methods=['POST']) +def getLastRevisionCook(): # Get Number Revision (Revision=X) + + logit(request.base_url) + CookName = None # Initialize + for key, value in request.args.to_dict().items(): + if key == "CookName": + exists = os.path.isfile('cooks/'+value+'.yaml') + if exists: + CookName = value - if CookName is not None: - with open('cooks/'+CookName+'.yaml', 'r') as myfile: - filecook = myfile.read() - response.media = {'Revision': str(yaml.safe_load(filecook)['revision'])} - else: - response.media = {'TEXT': 'Error, no Cook selected','RESULT':'ERROR'} + if CookName is not None: + with open('cooks/'+CookName+'.yaml', 'r') as myfile: + filecook = myfile.read() + return str({'Revision': str(yaml.safe_load(filecook)['revision'])}) + else: + return str({'TEXT': 'Error, no Cook selected','RESULT':'ERROR'}) ## # addComputer: Add a computer in database # /add/computer? # @param ComputerName -> ComputerName to add ## -class addComputer(object): - def on_get(self, request, response): - logit(request) - ComputerName = None - for key,value in request.params.items(): - if key == "ComputerName": - ComputerName = value - - if ComputerName is None: - response.media = {'TEXT': 'Error, you need a ComputerName to add','RESULT':'ERROR'} - else: - result = sql.insert("INSERT INTO COMPUTERS (Name) VALUES ('"+ComputerName+"')") - response.media = result +@app.route("/add/computer",methods=['POST']) +def addComputer(): + + logit(request.base_url) + ComputerName = None + for key,value in request.args.to_dict().items(): + if key == "ComputerName": + ComputerName = value + + if ComputerName is None: + return str({'TEXT': 'Error, you need a ComputerName to add','RESULT':'ERROR'}) + else: + result = sql.insert("INSERT INTO COMPUTERS (Name) VALUES ('"+ComputerName+"')") + return str(result) ## # addGroup: Add a new group # /add/group? # @param GroupName -> Name of group to add ## -class addGroup(object): - def on_get(self, request, response): - logit(request) - GroupName= None - for key,value in request.params.items(): - if key == "GroupName": - GroupName = value - +@app.route("/add/group",methods=['POST']) +def addGroup(): + + logit(request.base_url) + GroupName= None + for key,value in request.args.to_dict().items(): + if key == "GroupName": + GroupName = value - if GroupName is None: - response.media = {'TEXT': 'Error, you need a GroupName to add','RESULT':'ERROR'} - else: - result = sql.insert("INSERT INTO GROUPS (Name) VALUES ('"+GroupName+"')") - response.media = result + + if GroupName is None: + return str({'TEXT': 'Error, you need a GroupName to add','RESULT':'ERROR'}) + else: + result = sql.insert("INSERT INTO GROUPS (Name) VALUES ('"+GroupName+"')") + return str(result) ## # delGroup: Delete a group and all tables that has it. # /del/group? # @param GroupName/GroupID -> Name of group to delete ## -class delGroup(object): #Delete group - def on_get(self, request, response): - logit(request) - GroupID= None - for key,value in request.params.items(): - if key == "GroupID": - GroupID = value - if key == "GroupName": - GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) - - if GroupID is None: - response.media = {'TEXT': 'Error, you need a GroupName to delete','RESULT':'ERROR'} - else: - sql.insert("DELETE FROM COMPUTER_GROUP WHERE ID_G='"+GroupID+"'") - sql.insert("DELETE FROM COOKS_IDG WHERE ID_G='"+GroupID+"'") - result = sql.insert("DELETE FROM GROUPS WHERE ID_G='"+GroupID+"'") - response.media = result +@app.route("/del/group",methods=['POST']) +def delGroup(): + + logit(request.base_url) + GroupID= None + for key,value in request.args.to_dict().items(): + if key == "GroupID": + GroupID = value + if key == "GroupName": + GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) + + if GroupID is None: + return str({'TEXT': 'Error, you need a GroupName to delete','RESULT':'ERROR'}) + else: + sql.insert("DELETE FROM COMPUTER_GROUP WHERE ID_G='"+GroupID+"'") + sql.insert("DELETE FROM COOKS_IDG WHERE ID_G='"+GroupID+"'") + result = sql.insert("DELETE FROM GROUPS WHERE ID_G='"+GroupID+"'") + return str(result) ## @@ -418,128 +433,151 @@ class delGroup(object): #Delete group # /del/cook? # @param CookName -> Name of cook to disappear ## -class delCook(object): - def on_get(self,request,response): - logit(request) - CookName = None, None # Initialize - for key, value in request.params.items(): - if key == "CookName": - exists = os.path.isfile('cooks/'+value+'.yaml') - if exists: - CookName = value +@app.route("/del/cook",methods=['POST']) +def delCook(): + + logit(request.base_url) + CookName = None, None # Initialize + for key, value in request.args.to_dict().items(): + if key == "CookName": + exists = os.path.isfile('cooks/'+value+'.yaml') + if exists: + CookName = value - if CookName is not None: - sql.insert("DELETE FROM COOKS_ONETIME WHERE CookName='"+CookName+"'") - sql.insert("DELETE FROM COOKS_STATUS WHERE CookName='"+CookName+"'") - result = sql.insert("DELETE FROM COOKS_IDG WHERE CookName='"+CookName+"'") - response.media = result - else: - response.media = {'TEXT': 'Error, CookName don\'t exists','RESULT':'ERROR'} + if CookName is not None: + sql.insert("DELETE FROM COOKS_ONETIME WHERE CookName='"+CookName+"'") + sql.insert("DELETE FROM COOKS_STATUS WHERE CookName='"+CookName+"'") + result = sql.insert("DELETE FROM COOKS_IDG WHERE CookName='"+CookName+"'") + return str(result) + else: + return str({'TEXT': 'Error, CookName don\'t exists','RESULT':'ERROR'}) ## # delGroupsCook: Delete groups of a cook # /del/groupscook? # @param CookName -> Name of cook to make his groups disappear ## -class delGroupsCook(object): - def on_get(self,request,response): - logit(request) - CookName = None, None # Initialize - for key, value in request.params.items(): - if key == "CookName": - exists = os.path.isfile('cooks/'+value+'.yaml') - if exists: - CookName = value +@app.route("/del/groupscook",methods=['POST']) +def delGroupsCook(): + + logit(request.base_url) + CookName = None, None # Initialize + for key, value in request.args.to_dict().items(): + if key == "CookName": + exists = os.path.isfile('cooks/'+value+'.yaml') + if exists: + CookName = value - if CookName is not None: - result = sql.insert("DELETE FROM COOKS_IDG WHERE CookName='"+CookName+"'") - response.media = result - else: - response.media = {'TEXT': 'Error, CookName don\'t exists','RESULT':'ERROR'} + if CookName is not None: + result = sql.insert("DELETE FROM COOKS_IDG WHERE CookName='"+CookName+"'") + return str(result) + else: + return str({'TEXT': 'Error, CookName don\'t exists','RESULT':'ERROR'}) ## # delCleanCook: Delete groups of a cook # /del/cleancook? # @param CookName -> Clean status of a cook (Restart it) ## -class delCleanCook(object): - def on_get(self,request,response): - logit(request) - CookName = None, None # Initialize - for key, value in request.params.items(): - if key == "CookName": - exists = os.path.isfile('cooks/'+value+'.yaml') - if exists: - CookName = value +@app.route("/del/cleancook",methods=['POST']) +def delCleanCook(): + + logit(request.base_url) + CookName = None, None # Initialize + for key, value in request.args.to_dict().items(): + if key == "CookName": + exists = os.path.isfile('cooks/'+value+'.yaml') + if exists: + CookName = value - if CookName is not None: - result = sql.insert("DELETE FROM COOKS_STATUS WHERE CookName='"+CookName+"'") - response.media = result + if CookName is not None: + result = sql.insert("DELETE FROM COOKS_STATUS WHERE CookName='"+CookName+"'") + return str(result) + else: + return str({'TEXT': 'Error, CookName don\'t exists','RESULT':'ERROR'}) + +## +# updGroup: Update Group Name +# /upd/group? +# @param GroupID/GroupName -> Actual ID / Name of group +# @param GroupNewName -> New name for group +## +@app.route("/upd/group",methods=['POST']) +def updGroup(): + + logit(request.base_url) + GroupID, GroupNewName= None, None + for key,value in request.args.to_dict().items(): + if key == "GroupID": + GroupID = value + if key == "GroupName": + GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) + if key == "GroupNewName": + Count = str(sql.select("SELECT COUNT(*) 'Count' FROM GROUPS WHERE Name='"+value+"'")[0]['Count']) + if Count == "0": + GroupNewName = value else: - response.media = {'TEXT': 'Error, CookName don\'t exists','RESULT':'ERROR'} + return str({'TEXT': 'Error, New group name exists','RESULT':'ERROR'}) + + if GroupID is None or GroupNewName is None: + return str({'TEXT': 'Error, you need a GroupName and new name to update name','RESULT':'ERROR'}) + else: + result = sql.insert("UPDATE GROUPS SET Name='"+GroupNewName+"' WHERE ID_G='"+GroupID+"'") + return str(result) +## +# addGrpComputer: Add computer to a group +# /add/grpcomputer? +# @param GroupID/GroupName-> ID or Name of group +# @param ComputerID/ComputerName -> ID or Name of computer +## +@app.route("/add/grpcomputer",methods=['POST']) +def addGrpComputer(): + + logit(request.base_url) + ComputerID, GroupID= None, None + for key, value in request.args.to_dict().items(): + if key == "ComputerName": + ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) + if key == "ComputerID": + ComputerID = value + if key == "GroupName": + GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) + if key == "GroupID": + GroupID = value -class updGroup(object): #Delete group - def on_get(self, request, response): - logit(request) - GroupID, GroupNewName= None, None - for key,value in request.params.items(): - if key == "GroupID": - GroupID = value - if key == "GroupName": - GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) - if key == "GroupNewName": - Count = str(sql.select("SELECT COUNT(*) 'Count' FROM GROUPS WHERE Name='"+value+"'")[0]['Count']) - if Count == "0": - GroupNewName = value - else: - response.media = {'TEXT': 'Error, New group name exists','RESULT':'ERROR'} - - if GroupID is None or GroupNewName is None: - response.media = {'TEXT': 'Error, you need a GroupName and new name to update name','RESULT':'ERROR'} - else: - result = sql.insert("UPDATE GROUPS SET Name='"+GroupNewName+"' WHERE ID_G='"+GroupID+"'") - response.media = result + if ComputerID is None or GroupID is None: + return str({'TEXT': 'Error, you need a Name and Group to add','RESULT':'ERROR'}) + else: + result = sql.insert("INSERT INTO COMPUTER_GROUP (ID_C,ID_G) VALUES ('"+ComputerID+"','"+GroupID+"')") + return str(result) -class addGrpComputer(object): #Add computer to a group (Local) - def on_get(self, request, response): - logit(request) - ComputerID, GroupID= None, None - for key, value in request.params.items(): - if key == "ComputerName": - ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) - if key == "ComputerID": - ComputerID = value - if key == "GroupName": - GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) - if key == "GroupID": - GroupID = value +## +# delGrpComputer: Delete computer from a group +# /del/grpcomputer? +# @param GroupID/GroupName-> ID or Name of group +# @param ComputerID/ComputerName -> ID or Name of computer +## +@app.route("/del/grpcomputer",methods=['POST']) +def delGrpComputer(): + + logit(request.base_url) + ComputerID, GroupID= None, None + for key, value in request.args.to_dict().items(): + if key == "ComputerName": + ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) + if key == "ComputerID": + ComputerID = value + if key == "GroupName": + GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) + if key == "GroupID": + GroupID = value - if ComputerID is None or GroupID is None: - response.media = {'TEXT': 'Error, you need a Name and Group to add','RESULT':'ERROR'} - else: - result = sql.insert("INSERT INTO COMPUTER_GROUP (ID_C,ID_G) VALUES ('"+ComputerID+"','"+GroupID+"')") - response.media = result - -class delGrpComputer(object): #Del computer from a group - def on_get(self, request, response): - logit(request) - ComputerID, GroupID= None, None - for key, value in request.params.items(): - if key == "ComputerName": - ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) - if key == "ComputerID": - ComputerID = value - if key == "GroupName": - GroupID = str(sql.select("SELECT ID_G FROM GROUPS WHERE Name='"+value+"'")[0]['ID_G']) - if key == "GroupID": - GroupID = value - - if ComputerID is None or GroupID is None: - response.media = {'TEXT': 'Error, you need a Name and Group to add','RESULT':'ERROR'} - else: - result = sql.insert("DELETE FROM COMPUTER_GROUP WHERE ID_C='"+ComputerID+"' AND ID_G='"+GroupID+"'") - response.media = result + if ComputerID is None or GroupID is None: + return str({'TEXT': 'Error, you need a Name and Group to add','RESULT':'ERROR'}) + else: + result = sql.insert("DELETE FROM COMPUTER_GROUP WHERE ID_C='"+ComputerID+"' AND ID_G='"+GroupID+"'") + return str(result) ## @@ -548,77 +586,79 @@ class delGrpComputer(object): #Del computer from a group # @param ComputerName/ComputerID -> Computer ID or Name # @param Password -> Password validated command ## -class delComputer(object): #Delete computer - def on_get(self, request, response): - logit(request) - ComputerID= None - for key, value in request.params.items(): - if key == "ComputerName": - ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) - if key == "ComputerID": - ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE ID_C='"+value+"'")[0]['ID_C']) - if key == "Password" and value == retPassword(): - Password=value - if Password is None: - response.media = {'TEXT': 'Invalid password','RESULT':'ERROR'} - elif ComputerID is None: - response.media = {'TEXT': 'Error, you need a Name/ComputerID to update data','RESULT':'ERROR'} - elif ComputerID=='': - response.media = {'TEXT': 'Error, this Name/ID is not valid','RESULT':'ERROR'} - else: - sql.insert("DELETE FROM COMPUTER_GROUP WHERE ID_C='"+ComputerID+"'") - sql.insert("DELETE FROM COOKS_STATUS WHERE ID_C='"+ComputerID+"'") - resp = sql.insert("DELETE FROM COMPUTERS WHERE ID_C='"+ComputerID+"'") - logit(resp) +@app.route("/del/computer",methods=['POST']) +def delComputer(): + + logit(request.base_url) + ComputerID= None + for key, value in request.args.to_dict().items(): + if key == "ComputerName": + ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) + if key == "ComputerID": + ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE ID_C='"+value+"'")[0]['ID_C']) + if key == "Password" and value == retPassword(): + Password=value + if Password is None: + return str({'TEXT': 'Invalid password','RESULT':'ERROR'}) + elif ComputerID is None: + return str({'TEXT': 'Error, you need a Name/ComputerID to update data','RESULT':'ERROR'}) + elif ComputerID=='': + return str({'TEXT': 'Error, this Name/ID is not valid','RESULT':'ERROR'}) + else: + sql.insert("DELETE FROM COMPUTER_GROUP WHERE ID_C='"+ComputerID+"'") + sql.insert("DELETE FROM COOKS_STATUS WHERE ID_C='"+ComputerID+"'") + resp = sql.insert("DELETE FROM COMPUTERS WHERE ID_C='"+ComputerID+"'") + logit(resp) ## -# updComputer: Upd computer data +# updComputer: Update computer data # /upd/computer? # @param ComputerID -> Computer ID # @param UUID -> UUID of computer # No need password, validate from ComputerID+UUID for updates.. ## -class updComputer(object): - def on_get(self, request, response): - logit(request) - ComputerID, UUID = None, None - for key, value in request.params.items(): - if key == "ComputerName": - try: - ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) - except: - response.media = {'TEXT': 'Error: Computer not exists in database','RESULT':'ERROR','EXITCODE':'1'} - break - if key == "ComputerID": - ComputerID = value - if key == "UUID": - UUID = value - if ComputerID is None and response.media is None: - response.media = {'TEXT': 'Error, you need a ComputerName/ComputerID to update data','RESULT':'ERROR'} - elif response.media is None and ComputerID is not None and UUID is not None: - Count = str(sql.select("SELECT COUNT(*) 'Count' FROM COMPUTERS WHERE UUID='"+UUID+"' AND ID_C='"+ComputerID+"'")[0]['Count']) - if Count == "0": - response.media = {'TEXT': 'Error, computer and UUID doesn\'t match in database','RESULT':'ERROR','EXITCODE':'2'} - else: - for key, value in request.params.items(): - if key == "SOVersion": - response.media = sql.insert("UPDATE COMPUTERS SET SOVersion ='"+value+"' WHERE ID_C='"+ComputerID+"'") - if key == "SOBit": - response.media = sql.insert("UPDATE COMPUTERS SET SOBit ='"+value+"' WHERE ID_C='"+ComputerID+"'") - if key == "SOCaption": - response.media = sql.insert("UPDATE COMPUTERS SET SOCaption ='"+value+"' WHERE ID_C='"+ComputerID+"'") - if key == "LastConnection": - response.media = sql.insert("UPDATE COMPUTERS SET LastConnection ='"+value+"' WHERE ID_C='"+ComputerID+"'") - if key == "LastUser": - response.media = sql.insert("UPDATE COMPUTERS SET LastUser='"+value+"' WHERE ID_C='"+ComputerID+"'") - if key == "RAM": - response.media = sql.insert("UPDATE COMPUTERS SET RAM='"+value+"' WHERE ID_C='"+ComputerID+"'") - if key == "CPUName": - response.media = sql.insert("UPDATE COMPUTERS SET CPUName='"+value+"' WHERE ID_C='"+ComputerID+"'") - if key == "RAMFree": - response.media = sql.insert("UPDATE COMPUTERS SET RAMFree='"+str(value)+"' WHERE ID_C='"+ComputerID+"'") - if key == "HDD": - response.media = sql.insert("UPDATE COMPUTERS SET HDD='"+str(value)+"' WHERE ID_C='"+ComputerID+"'") +@app.route("/upd/computer",methods=['POST']) +def updComputer(): + logit(request.base_url) + ComputerID, UUID = None, None + for key, value in request.args.to_dict().items(): + if key == "ComputerName": + try: + ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) + except: + return str({'TEXT': 'Error: Computer not exists in database','RESULT':'ERROR','EXITCODE':'1'}) + break + if key == "ComputerID": + ComputerID = value + if key == "UUID": + UUID = value + if ComputerID is None: + return str({'TEXT': 'Error, you need a ComputerName/ComputerID to update data','RESULT':'ERROR'}) + elif ComputerID is not None and UUID is not None: + Count = str(sql.select("SELECT COUNT(*) 'Count' FROM COMPUTERS WHERE UUID='"+UUID+"' AND ID_C='"+ComputerID+"'")[0]['Count']) + if Count == "0": + return str({'TEXT': 'Error, computer and UUID doesn\'t match in database','RESULT':'ERROR','EXITCODE':'2'}) + else: + for key, value in request.args.to_dict().items(): + if key == "SOVersion": + str(sql.insert("UPDATE COMPUTERS SET SOVersion ='"+value+"' WHERE ID_C='"+ComputerID+"'")) + if key == "SOBit": + str(sql.insert("UPDATE COMPUTERS SET SOBit ='"+value+"' WHERE ID_C='"+ComputerID+"'")) + if key == "SOCaption": + str(sql.insert("UPDATE COMPUTERS SET SOCaption ='"+value+"' WHERE ID_C='"+ComputerID+"'")) + if key == "LastConnection": + str(sql.insert("UPDATE COMPUTERS SET LastConnection ='"+value+"' WHERE ID_C='"+ComputerID+"'") ) + if key == "LastUser": + str(sql.insert("UPDATE COMPUTERS SET LastUser='"+value+"' WHERE ID_C='"+ComputerID+"'")) + if key == "RAM": + str(sql.insert("UPDATE COMPUTERS SET RAM='"+value+"' WHERE ID_C='"+ComputerID+"'")) + if key == "CPUName": + str(sql.insert("UPDATE COMPUTERS SET CPUName='"+value+"' WHERE ID_C='"+ComputerID+"'")) + if key == "RAMFree": + str(sql.insert("UPDATE COMPUTERS SET RAMFree='"+str(value)+"' WHERE ID_C='"+ComputerID+"'")) + if key == "HDD": + str(sql.insert("UPDATE COMPUTERS SET HDD='"+str(value)+"' WHERE ID_C='"+ComputerID+"'")) + return str({'RESULT':'1','TEXT':'OK','EXITCODE':'0'}) ## # updCookName: Rename cook name @@ -627,101 +667,107 @@ class updComputer(object): # @param CookNewName -> New Cook Name # @param Password -> Password validated command ## -class updCookName(object): - def on_get(self, request, response): - logit(request) - CookName, CookNewName,Password= None, None,None #Initialize - for key, value in request.params.items(): - if key == "CookName": - if os.path.isfile('cooks/'+value+'.yaml'): - CookName= value - else: - response.media = {'TEXT': 'Error: Cook not exists in folder','RESULT':'ERROR'} - if key == "CookNewName": - if os.path.isfile('cooks/'+value+'.yaml'): - response.media = {'TEXT': 'Error: There is a cook with the new name in folder!','RESULT':'ERROR'} - else: - CookNewName= value - if key == "Password" and value == retPassword(): - Password=value - if Password is None: - response.media = {'TEXT': 'Invalid password','RESULT':'ERROR'} - if response.media is not None: - pass - elif CookName is None or CookNewName is None: - response.media = {'TEXT': 'Error, you need the old and new Cook Name to update data','RESULT':'ERROR'} - else: #Do it. - old_file = os.path.join("cooks", CookName+'.yaml') - new_file = os.path.join("cooks", CookNewName+'.yaml') - os.rename(old_file, new_file) - sql.insert("UPDATE COOKS_IDG SET CookName ='"+CookNewName+"' WHERE CookName='"+CookName+"'") - response.media = sql.insert("UPDATE COOKS_STATUS SET CookName ='"+CookNewName+"' WHERE CookName='"+CookName+"'") - - -class loadCook(object): - def on_get(self, request, response): - logit(request) - CookName, ComputerID, UUID= None, None, None #Initialize - for key, value in request.params.items(): - if key == "CookName": - if os.path.isfile('cooks/'+value+'.yaml'): - CookName= value - else: - response.media = {'TEXT': 'Error: Cook not exists in folder','RESULT':'ERROR'} - break - if key == "ComputerName": - ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) - if key == "ComputerID": - ComputerID = value - if key == "UUID": - UUID = value - - if CookName is None and response.media is None: - response.media = {'TEXT': 'Error, you need a CookName to load it','RESULT':'ERROR'} - elif response.media is None: - Count = str(sql.select("SELECT COUNT(*) 'Count' FROM COMPUTERS WHERE UUID='"+UUID+"' AND ID_C='"+ComputerID+"'")[0]['Count']) - if Count == "0": - response.media = {'TEXT': 'Error, computer doesn\'t exists in database','RESULT':'ERROR'} +@app.route("/upd/cookname",methods=['POST']) +def updCookName(): + + logit(request.base_url) + CookName, CookNewName,Password= None, None,None #Initialize + for key, value in request.args.to_dict().items(): + if key == "CookName": + if os.path.isfile('cooks/'+value+'.yaml'): + CookName= value else: - with open('cooks/'+CookName+'.yaml', 'r') as myfile: - data = myfile.read() - response.media = yaml.safe_load(data) - -class setCookStatus(object): - def on_get(self, request, response): - logit(request) - CookName, ComputerID, Revision, Error,ErrorDesc= None, None, None, None, "" - for key, value in request.params.items(): - if key == "CookName": - if os.path.isfile('cooks/'+value+'.yaml'): # You have to know that cook exists. - CookName= value - else: - response.media = {'TEXT': 'Error: Cook not exists in folder','RESULT':'ERROR'} - break - if key == "ComputerName": - ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) - if key == "ComputerID": - ComputerID = value - if key == "Revision": - Revision = value - if key == "Error": - Error = value - if key == "ErrorDesc": - ErrorDesc = value - - if CookName is None and response.media is None: - response.media = {'TEXT': 'Error, you need a CookName to load it','RESULT':'ERROR'} - elif response.media is None and CookName is not None and ComputerID is not None and Revision is not None and Error is not None: - statt = sql.select("SELECT COUNT(*) 'RESULT' FROM COOKS_STATUS WHERE CookName='"+CookName+"' AND ID_C='"+ComputerID+"'")[0]['RESULT'] - if statt == 0: - #INSERT, NEW - response.media = sql.insert("INSERT INTO COOKS_STATUS (CookName,ID_C,Revision,`Error`,`ErrorDesc`) VALUES ('"+CookName+"', '"+ComputerID+"', '"+Revision+"','"+Error+"','"+ErrorDesc+"')") + return str({'TEXT': 'Error: Cook not exists in folder','RESULT':'ERROR'}) + if key == "CookNewName": + if os.path.isfile('cooks/'+value+'.yaml'): + return str({'TEXT': 'Error: There is a cook with the new name in folder!','RESULT':'ERROR'}) else: - #UPDATE, NOT NEW - response.media = sql.insert("UPDATE COOKS_STATUS SET Revision='"+Revision+"',`Error`='"+Error+"',`ErrorDesc`='"+ErrorDesc+"' WHERE ID_C='"+ComputerID+"' AND CookName='"+CookName+"'") + CookNewName= value + if key == "Password" and value == retPassword(): + Password=value + if Password is None: + return str({'TEXT': 'Invalid password','RESULT':'ERROR'}) + elif CookName is None or CookNewName is None: + return str({'TEXT': 'Error, you need the old and new Cook Name to update data','RESULT':'ERROR'}) + else: #Do it. + old_file = os.path.join("cooks", CookName+'.yaml') + new_file = os.path.join("cooks", CookNewName+'.yaml') + os.rename(old_file, new_file) + sql.insert("UPDATE COOKS_IDG SET CookName ='"+CookNewName+"' WHERE CookName='"+CookName+"'") + return str(sql.insert("UPDATE COOKS_STATUS SET CookName ='"+CookNewName+"' WHERE CookName='"+CookName+"'")) + +## +# loadCook: Load a Cook +# /load/cook? +# @param ComputerID/ComputerName -> ID or Name of computer +# @param UUID -> UUID of ComputerID +# @param CookName -> Name of the cook +## +@app.route("/load/cook",methods=['POST']) +def loadCook(): + + logit(request.base_url) + CookName, ComputerID, UUID= None, None, None #Initialize + for key, value in request.args.to_dict().items(): + if key == "CookName": + if os.path.isfile('cooks/'+value+'.yaml'): + CookName= value + else: + return str({'TEXT': 'Error: Cook not exists in folder','RESULT':'ERROR'}) + break + if key == "ComputerName": + ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) + if key == "ComputerID": + ComputerID = value + if key == "UUID": + UUID = value + + if CookName is None and response.media is None: + return str({'TEXT': 'Error, you need a CookName to load it','RESULT':'ERROR'}) + else: + Count = str(sql.select("SELECT COUNT(*) 'Count' FROM COMPUTERS WHERE UUID='"+UUID+"' AND ID_C='"+ComputerID+"'")[0]['Count']) + if Count == "0": + return str({'TEXT': 'Error, computer doesn\'t exists in database','RESULT':'ERROR'}) else: - response.media = {'TEXT': 'Error in parameters...','RESULT':'ERROR'} - logit(response.media) + with open('cooks/'+CookName+'.yaml', 'r') as myfile: + data = myfile.read() + return str(yaml.safe_load(data)) + +@app.route("/set/cookstatus",methods=['POST']) +def setCookStatus(): + logit(request.base_url) + CookName, ComputerID, Revision, Error,ErrorDesc= None, None, None, None, "" + for key, value in request.args.to_dict().items(): + if key == "CookName": + if os.path.isfile('cooks/'+value+'.yaml'): # You have to know that cook exists. + CookName= value + else: + return str({'TEXT': 'Error: Cook not exists in folder','RESULT':'ERROR'}) + break + if key == "ComputerName": + ComputerID = str(sql.select("SELECT ID_C FROM COMPUTERS WHERE Name='"+value+"'")[0]['ID_C']) + if key == "ComputerID": + ComputerID = value + if key == "Revision": + Revision = value + if key == "Error": + Error = value + if key == "ErrorDesc": + ErrorDesc = value + + if CookName is None: + return str({'TEXT': 'Error, you need a CookName to load it','RESULT':'ERROR'}) + elif CookName is not None and ComputerID is not None and Revision is not None and Error is not None: + statt = sql.select("SELECT COUNT(*) 'RESULT' FROM COOKS_STATUS WHERE CookName='"+CookName+"' AND ID_C='"+ComputerID+"'")[0]['RESULT'] + if statt == 0: + #INSERT, NEW + return str(sql.insert("INSERT INTO COOKS_STATUS (CookName,ID_C,Revision,`Error`,`ErrorDesc`) VALUES ('"+CookName+"', '"+ComputerID+"', '"+Revision+"','"+Error+"','"+ErrorDesc+"')")) + else: + #UPDATE, NOT NEW + return str(sql.insert("UPDATE COOKS_STATUS SET Revision='"+Revision+"',`Error`='"+Error+"',`ErrorDesc`='"+ErrorDesc+"' WHERE ID_C='"+ComputerID+"' AND CookName='"+CookName+"'")) + else: + return str({'TEXT': 'Error in parameters...','RESULT':'ERROR'}) + logit(response.media) ## @@ -734,27 +780,27 @@ class setCookStatus(object): # 2: Password incorrect # 3: Password not set in app yet ## -class checkPassword(object): #Check password (ERROR if password not valid or no password and 1 if valid) - def on_get(self, request, response): - logit(request) - Password= None - for key, value in request.params.items(): - if key == "Password": - Password = value +@app.route("/check/password",methods=['POST']) +def checkPassword(): #Check password (ERROR if password not valid or no password and 1 if valid) + + logit(request.base_url) + Password= None + for key, value in request.args.to_dict().items(): + if key == "Password": + Password = value - if Password is None: - response.media = {'TEXT': 'Error, you need to supply a password','RESULT':'ERROR','EXITCODE':'1'} + if Password is None: + return str({'TEXT': 'Error, you need to supply a password','RESULT':'ERROR','EXITCODE':'1'}) + else: + res = sql.select("SELECT COUNT(*) 'RESULT' FROM OPTIONS WHERE Option='Password' AND Value='"+Password+"'")[0]['RESULT'] + if res == 1: + return str({'RESULT':'1','TEXT':'OK','EXITCODE':'0'}) else: - pass - res = sql.select("SELECT COUNT(*) 'RESULT' FROM OPTIONS WHERE Option='Password' AND Value='"+Password+"'")[0]['RESULT'] - if res == 1: - response.media = {'RESULT':'1','TEXT':'OK','EXITCODE':'0'} + res = sql.select("SELECT COUNT(*) 'RESULT' FROM OPTIONS WHERE Option='Password'")[0]['RESULT'] + if res == 0: #Password doesn't exists in database + return str({'RESULT':'ERROR','TEXT':'No password set. Please set it','EXITCODE':'3'}) else: - res = sql.select("SELECT COUNT(*) 'RESULT' FROM OPTIONS WHERE Option='Password'")[0]['RESULT'] - if res == 0: #Password doesn't exists in database - response.media = {'RESULT':'ERROR','TEXT':'No password set. Please set it','EXITCODE':'3'} - else: - response.media = {'RESULT':'ERROR','TEXT':'Password incorrect','EXITCODE':'2'} + return str({'RESULT':'ERROR','TEXT':'Password incorrect','EXITCODE':'2'}) ## # updPassword: Update password @@ -762,74 +808,61 @@ class checkPassword(object): #Check password (ERROR if password not valid or no # @param OldPassword -> SHA-256 of password (Old) # @param NewPassword -> SHA-256 of password (New) ## -class updPassword(object): #Update password (ERROR if password not valid or no password and 1 if changed) - def on_get(self, request, response): - logit(request) - OldPassword,NewPassword= None, None - for key, value in request.params.items(): - if key == "NewPassword": - NewPassword = value - if key == "OldPassword": - OldPassword = value +@app.route("/upd/password",methods=['POST']) +def updPassword(): #Update password (ERROR if password not valid or no password and 1 if changed) + + logit(request.base_url) + OldPassword,NewPassword= None, None + for key, value in request.args.to_dict().items(): + if key == "NewPassword": + NewPassword = value + if key == "OldPassword": + OldPassword = value - res = sql.select("SELECT COUNT(*) 'RESULT' FROM OPTIONS WHERE Option='Password'")[0]['RESULT'] - if res == 0 and NewPassword is not None: #Password doesn't exists in database - response.media = sql.insert("INSERT INTO OPTIONS VALUES('Password','"+NewPassword+"')") - elif res == 0 and NewPassword is None: #No password supplied - response.media = {'RESULT':'ERROR','TEXT':'Error, you need to supply a password'} - elif res == 1 and OldPassword is not None: # Password exists in database (And you supplied OldPassword) - res = sql.select("SELECT COUNT(*) 'RESULT' FROM OPTIONS WHERE Option='Password' AND Value='"+OldPassword+"'")[0]['RESULT'] - if res == 0: # Old password incorrect - response.media = {'RESULT':'ERROR','TEXT':'Old password incorrect'} - elif res == 1 and NewPassword is not None: # All is supplied - response.media = sql.insert("UPDATE OPTIONS SET Value='"+NewPassword+"' WHERE Option='Password'") - else: - response.media = {'RESULT':'ERROR', 'TEXT':'No password supplied or bad args'} + res = sql.select("SELECT COUNT(*) 'RESULT' FROM OPTIONS WHERE Option='Password'")[0]['RESULT'] + if res == 0 and NewPassword is not None: #Password doesn't exists in database + return str(sql.insert("INSERT INTO OPTIONS VALUES('Password','"+NewPassword+"')")) + elif res == 0 and NewPassword is None: #No password supplied + return str({'RESULT':'ERROR','TEXT':'Error, you need to supply a password'}) + elif res == 1 and OldPassword is not None: # Password exists in database (And you supplied OldPassword) + res = sql.select("SELECT COUNT(*) 'RESULT' FROM OPTIONS WHERE Option='Password' AND Value='"+OldPassword+"'")[0]['RESULT'] + if res == 0: # Old password incorrect + return str({'RESULT':'ERROR','TEXT':'Old password incorrect'}) + elif res == 1 and NewPassword is not None: # All is supplied + return str(sql.insert("UPDATE OPTIONS SET Value='"+NewPassword+"' WHERE Option='Password'")) else: - response.media = {'RESULT':'ERROR', 'TEXT':'No password supplied or bad args'} + return str({'RESULT':'ERROR', 'TEXT':'No password supplied or bad args'}) + else: + return str({'RESULT':'ERROR', 'TEXT':'No password supplied or bad args'}) + +## +# getOptionValue: Get Option +# /get/optionvalue? +# @param Password -> SHA-256 of password +# @param Option -> Option ID +## +@app.route("/get/optionvalue",methods=['POST']) +def getOptionValue(): + logit(request.base_url) + Password,Option= None,None + for key, value in request.args.to_dict().items(): + if key == "Option": + Option = value + if key == "Password" and value == retPassword(): + Password=value + if Password is None: + return str({'TEXT': 'Invalid password','RESULT':'ERROR'}) + else: + return sql.select("SELECT VALUE FROM OPTIONS WHERE Option='"+str(Option)+"'")[0] + - -api = falcon.API() -api.add_route('/add/computer', addComputer()) #Add computer -api.add_route('/add/group', addGroup()) #Add group to the list of local groups -api.add_route('/add/cookgrp', addCookGrp()) #Assign cook to group -api.add_route('/add/grpcomputer', addGrpComputer()) #Add computer to a group -api.add_route('/del/computer', delComputer()) #Delete computer -api.add_route('/del/cookgrp', delCookGrp()) # Deassign cook from a group -api.add_route('/del/emptypcsgroup', delEmptyPcsGroup()) # Delete all computers from a group -api.add_route('/del/group', delGroup()) #Delete group -api.add_route('/del/grpcomputer', delGrpComputer()) #Delete computer from a group -api.add_route('/del/cook', delCook()) #Delete cook and all status about it -api.add_route('/del/groupscook', delGroupsCook()) #Delete all groups of a cook -api.add_route('/del/cleancook', delCleanCook()) #Delete status of a cook for all computers (Restart cook). No delete groups - -api.add_route('/get/computerexists', getComputerExists()) #Returns 0 or 1 (name status) -api.add_route('/get/computers', getComputers()) #Get list of computer and all data in array -api.add_route('/get/cookall', getCookAll()) #Get all cooks implemented in one group at least -api.add_route('/get/cookgrp', getCookGrp()) # See cooks that have a determinated group -api.add_route('/get/cookpend', getCookPend()) #Get cooks pending to implement to a computer -api.add_route('/get/groups', getGroups()) #Get groups of a computer (Or list if not args) -api.add_route('/get/computersgrp', getComputersGrp()) #Get computers in a group -api.add_route('/get/grpcook', getGrpCook()) # See groups of a determinated cook -api.add_route('/get/lastrevisioncook', getLastRevisionCook()) # Returns number of last revision of a cook -api.add_route('/get/statuscook', getStatusCook()) # See status of a cook -api.add_route('/load/cook', loadCook()) # Load a cook (Transfer in json way) -api.add_route('/upd/cookstatus', setCookStatus()) # Update status of a cook in a computer -api.add_route('/upd/computer', updComputer()) #Update data of computer -api.add_route('/upd/cookname', updCookName()) #Update file name of cook and SQL references to it. -api.add_route('/upd/group', updGroup()) #Update group name - - -api.add_route('/check/password', checkPassword()) #Check admin password -api.add_route('/upd/password', updPassword()) # Update password (Or create it not exists) -#api.add_route('/get/password', getPassword()) # Get password (Will be '' if password not exists) - -class getApiVer(object): - def on_get(self, request, response): - logit(request) - response.media = {'API':API_VER} -api.add_route('/get/apiver', getApiVer()) # Get API version +@app.route('/get/apiver',methods=['POST']) +def getApiVer(): + return str({'API':API_VER}) print("Build: "+str(BUILD)) print("API Version: "+str(API_VER)) + + +app.run(debug=False,port=3333,ssl_context='adhoc',host='0.0.0.0') \ No newline at end of file diff --git a/client/client.ps1 b/client/client.ps1 index e09feea..56d9076 100644 --- a/client/client.ps1 +++ b/client/client.ps1 @@ -1,4 +1,4 @@ -# Build 11 +# Build 13. Using API 2 param([Int32]$startup=0) #Write-Host $startup $srcdir = $PSCommandPath | Split-Path -Parent @@ -9,7 +9,27 @@ $64bit = [Environment]::Is64BitOperatingSystem $computerName = [System.Net.Dns]::GetHostName() $UUID=(Get-CimInstance Win32_ComputerSystemProduct).UUID -$exists = Invoke-RestMethod -Method Get -Uri "$server/get/computerexists?ComputerName=$computerName&UUID=$UUID" +if ((Get-Host | Select-Object Version).Version.Major -lt 6){#Powershell Windows (Not Core) + add-type -TypeDefinition @" + using System.Net; + using System.Security.Cryptography.X509Certificates; + public class TrustAllCertsPolicy : ICertificatePolicy { + public bool CheckValidationResult( + ServicePoint srvPoint, X509Certificate certificate, + WebRequest request, int certificateProblem) { + return true; + } + } +"@ + [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy +}else{ # Powershell Core + $PSDefaultParameterValues += + @{'Invoke-RestMethod:SkipCertificateCheck' = $true} +} + + + +$exists = Invoke-RestMethod -Method Post -Uri "$server/get/computerexists?ComputerName=$computerName&UUID=$UUID" if ($exists.Result -eq "ERROR"){ if ($exists.EXITCODE -eq '3'){ Write-Host "Computer outside database:" $computerName @@ -45,25 +65,25 @@ $diskResults = @() $ThisVolume.FreeSpace = $([Math]::Round($disk.FreeSpace / 1GB,2)) $DiskResults += $ThisVolume } -$DisksData = $DiskResults |ConvertTo-Json +$DisksData = ConvertTo-Json -Depth 4 $DiskResults $DisksData = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($DisksData)) #I can't enter to database all without encode $lastUser = (Get-CimInstance -ClassName Win32_ComputerSystem -Property UserName -ComputerName .).UserName # Send it $paramInvoke = -join("$server/upd/computer?ComputerName=$computerName&UUID=",$UUID,"&SOVersion=",$SOVersion,"&SOCaption=",$SOData.Caption,"&SOBit=",$SOData.OsArchitecture.Substring(0,2),"&LastConnection=",$Timestamp,"&RAM=",$RAMInstalled,"&RAMFree=",$RAMFree,"&CPUName=",$CPUName,"&LastUser=",$lastUser,"&HDD=",$DisksData) -Invoke-RestMethod -Method Get -Uri $paramInvoke | out-null +Invoke-RestMethod -Method Post -Uri $paramInvoke | out-null # More info (Only if has to be) # $paramInvoke = -join("$server/upd/computerhis?ComputerName=$computerName&UUID=",$UUID,"&RAMFree=",$RAMFree,"&RAMUsed=",$RAMUsed,"&Timestamp=",$Timestamp,"&DisksUse=",$disksUse) -# Invoke-RestMethod -Method Get -Uri $paramInvoke | out-null +# Invoke-RestMethod -Method Post -Uri $paramInvoke | out-null # Load Cooks of computer -$cooks = Invoke-RestMethod -Method Get -Uri "$server/get/cookpend?ComputerName=$computerName&UUID=$UUID" +$cooks = Invoke-RestMethod -Method Post -Uri "$server/get/cookpend?ComputerName=$computerName&UUID=$UUID" foreach ($CookName in $cooks){ Set-Location $env:temp # For downloading/copying items, use system temp location $CookName = $CookName.CookName - $cook = Invoke-RestMethod -Method Get -Uri "$server/load/cook?CookName=$CookName&ComputerName=$computerName&UUID=$UUID" + $cook = Invoke-RestMethod -Method Post -Uri "$server/load/cook?CookName=$CookName&ComputerName=$computerName&UUID=$UUID" Write-Host "Receta:" $cook.name $CookRevision = $cook.revision $atstartup = $cook.atstartup @@ -261,7 +281,7 @@ foreach ($CookName in $cooks){ if ($cook.runever -eq "1"){ $err = -1 # This is for run but not for error, is by cook saw. } - Invoke-RestMethod -Method Get -Uri "$server/upd/cookstatus?ComputerName=$computerName&UUID=$UUID&CookName=$CookName&Revision=$CookRevision&Error=$err&ErrorDesc=$errvar" | out-null + Invoke-RestMethod -Method Post -Uri "$server/set/cookstatus?ComputerName=$computerName&UUID=$UUID&CookName=$CookName&Revision=$CookRevision&Error=$err&ErrorDesc=$errvar" | out-null #Delete files copied to temp for saving space foreach ($element in $filesCopied) { diff --git a/client/configpcm_example.ini b/client/configpcm_example.ini index a3f633d..583caef 100644 --- a/client/configpcm_example.ini +++ b/client/configpcm_example.ini @@ -1,3 +1,3 @@ -server=http://miserver.dominio:3333 +server=https://miserver.dominio:3333 resources=\\\\MISERVER\\REPOFOLDER lang=en \ No newline at end of file diff --git a/client/control.pyw b/client/control.pyw index de51d92..fbe65f0 100644 --- a/client/control.pyw +++ b/client/control.pyw @@ -12,6 +12,13 @@ from translation import T passha256 = None # Password (Global) +config = configparser.ConfigParser() +config.read('configpcm.ini') + +c_server = config['General']['server'] +c_resources = config['General']['resources'].replace('\\\\','\\') + + def ping(host): """ Returns True if host (str) responds to a ping request. @@ -30,6 +37,10 @@ def sendmenudot(text,title,choices): return menu.split('.')[0] else: return menu + +def retOpt(option): + return returnvalueapi('/get/optionvalue?Option='+str(option),field="Value") + ## showchoicesapi, suburl has to have params (NOT inlcuding server part) def showchoicesapi(text,title,suburl,field=['Name']): global c_server @@ -43,7 +54,8 @@ def showchoicesapi(text,title,suburl,field=['Name']): else: twopart= '?Password='+str(passha256) try: - jsonobj = json.loads(requests.get(c_server+suburl+twopart).text) + r=(requests.post(c_server+suburl+twopart, verify=False).text).replace("\'", "\"").replace('\\"',"'").replace(': None',': "None"') + jsonobj = json.loads(r) listitems = [] for ite in jsonobj: # Run in array from json to = "" @@ -66,8 +78,8 @@ def sendsettoapi(suburl,goodtext): # Send a add/del/modify to API. Doesn't retur else: twopart= '?Password='+str(passha256) try: - jsonobj = json.loads(requests.get(c_server+suburl+twopart).text) - #jsonobj['RESULT'] has to exist for next if + r=(requests.post(c_server+suburl+twopart, verify=False).text).replace("\'", "\"").replace('\\"',"'").replace(': None',': "None"') + jsonobj = json.loads(r) try: jsonobj['RESULT'] except: @@ -95,22 +107,16 @@ def returnvalueapi(suburl,field="Name"): else: twopart= '?Password='+str(passha256) try: - jsonobj = json.loads(requests.get(c_server+suburl+twopart).text) + r=(requests.post(c_server+suburl+twopart, verify=False).text).replace("\'", "\"").replace('\\"',"'").replace(': None',': "None"') + jsonobj = json.loads(r) return jsonobj[field] except: easygui.msgbox(msg=T('Error talking with API'), title="Error", ok_button='OK') return None -config = configparser.ConfigParser() -config.read('configpcm.ini') - -c_server = config['General']['server'] -c_resources = config['General']['resources'].replace('\\\\','\\') - - def menuprinc(): - menu = sendmenudot(T('Main menu'),T('Select option'),['1.'+T('Computers'),'2.'+T('Groups'),'3.'+T('Cooks'),'4.Reportes/Listados']) + menu = sendmenudot(T('Main menu'),T('Select option'),['1.'+T('Computers'),'2.'+T('Groups'),'3.'+T('Cooks'),'4.Reportes/Listados','5.'+T('Options')]) if menu == '1': mcomputers() elif menu == '2': @@ -119,6 +125,8 @@ def menuprinc(): mcooks() elif menu == '4': mreports() + elif menu == '5': + moptions() def mcomputers(): menu = sendmenudot(T('Computers menu'),T('Select option'),['1.'+T('Add computer'),'2.'+T('Remove computer'),'3.'+T('Add computer to group'),'4.'+T('Computers list'),'5.'+T('Computer status')]) @@ -177,7 +185,8 @@ def mcooks(): cook = showchoicesapi("Lista de recetas implementadas en algĂșn grupo. Selecciona una para ver sus datos","Detalles de una receta","/get/cookall",'CookName') if cook is not None: showchoicesapi("Lista de grupos de la receta "+cook,"Listado de grupos de una receta","/get/grpcook?CookName="+cook) - jsonobj = json.loads(requests.get(c_server+'/get/statuscook?CookName='+cook).text) + r=(requests.post(c_server+'/get/statuscook?CookName='+cook, verify=False).text).replace("\'", "\"").replace('\\"',"'").replace(': None',': "None"') + jsonobj = json.loads(r) list = [] s_err = 0 s_com = 0 @@ -247,6 +256,20 @@ def mreports(): menuprinc() return mreports() + +def moptions(): + debugsql = retOpt('DebugSQL') + addcomputers = retOpt('AddComputers') + menu = sendmenudot(T('Options menu'),T('Select option'),['1.'+T('Debug SQL commands')+'-'+str(debugsql),'2.'+T('Allow auto add of new computers')+'-'+str(addcomputers)]) + + if menu == '1': + showchoicesapi(T('Computers list'),T('Computers list'),"/get/computers") + elif menu == '2': + showchoicesapi(T('Groups list'),T('Groups list'),"/get/groups") + elif menu is None: + menuprinc() + return + mreports() def m_addcomputergroup(): @@ -272,6 +295,7 @@ def m_delcomputergroup(): # Check password before starting all pa = returnvalueapi("/check/password?Password=None",field="EXITCODE") +print(pa) if pa == "3": # No password stored yet passw = easygui.passwordbox(T('There is no password yet in PCM. Please set one below'),T('Set password')) passw2 = easygui.passwordbox(T('Confirm it'),T('Set password')) @@ -292,6 +316,7 @@ else: # There is a password quit() passha256 = hashlib.sha256(passw.encode()).hexdigest() re = returnvalueapi("/check/password?Password="+passha256,field="EXITCODE") # Create password in database + print(re) if re == '0': # Password is right menuprinc() else: diff --git a/docs/changelog.md b/docs/changelog.md new file mode 100644 index 0000000..788511e --- /dev/null +++ b/docs/changelog.md @@ -0,0 +1,10 @@ +# Changelog + +## 2019/11/20 +- New API (2). All requests now works in POST and SSL (Self-Signed) +- Now using Flask and not falcon with waitress-serve (Lesser dependencies and ssl support) +- Some new options +- More stable (Besides this API is at beta stage because POST and different json returns) +- Better doc +- Preparing for better gui (Web one) +- Now SQL will have versions, for updating if neccesary (If you are using old version, please create in database new table "OPTIONS" with data that has "emptydatabase.db") \ No newline at end of file diff --git a/docs/index.md b/docs/index.md index 9a0e80a..4a97a0c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -14,7 +14,6 @@ It's not error proof, then, I don't have any responsability if something crashes # Roadmap - Complete translation English and Spanish -- Somewhat more security in API 1 - Stabilize all - I created a simple GUI in EasyGUI to be easy used, but if I have time, maybe will do a webUI more dynamic and visually better (Without needing to install php/apache/nginx, using python) - Support Linux clients @@ -22,12 +21,12 @@ It's not error proof, then, I don't have any responsability if something crashes # Requirements ## Server -For server you can use Linux or Windows, and in theory any environment that can run Python 3 can work as server +For server you can use Linux, Mac or Windows, and in theory any environment that can run Python 3 can work as server - Python3 with: - - Falcon - - Waitress-serve + - Flask + - pyopenssl - Yaml - Python3 deps can be installed it using pip install command (pip install waitress falcon pyyaml) + Python3 deps can be installed it using pip install command (pip install pyopenssl flask pyyaml) - For controlling the program, you have to start control.pyw using Python3. It doesn't need to be started in server, but it has to be in that folder (Or with configpcm.ini file). It uses easygui of python3 (pip install easygui) @@ -47,7 +46,6 @@ For server you can use Linux or Windows, and in theory any environment that can ## Server - Copy this folder to a folder in your server - Install dependencies -- Open sysopt.py file and change values if needed - Start the server: Start api.py using loadserver.bat (Windows) o loadserver.sh (Linux) file. You can do in systemd way, or a cron, or in a terminal of windows server,... ## Client. Example using GPO and Task Schedule @@ -66,4 +64,4 @@ For server you can use Linux or Windows, and in theory any environment that can - Args: -executionpolicy bypass -windowstyle hidden -noninteractive -nologo -file "\\SERVER\SysVol\DOMAINNAME\scripts\client.ps1" -startup 1 ## Control app -- Start control.pyw to setup password and start adding computers, groups and cooks. You can use docs/example_cooks for examples. If anyone wants, I will setup a git repo for cooks. \ No newline at end of file +- Start control.pyw to setup password and start adding computers, groups and cooks and configure options. You can use docs/example_cooks for examples. If anyone wants, I will setup a git repo for cooks. \ No newline at end of file diff --git a/loadserver.bat b/loadserver.bat index 17908f8..6ad7ce2 100644 --- a/loadserver.bat +++ b/loadserver.bat @@ -1,3 +1,3 @@ REM Starting Server. Will only work if python and dependencies are installed and in PATH cd /D "%~dp0" -waitress-serve --port=3333 api:api \ No newline at end of file +python3 api.py \ No newline at end of file diff --git a/loadserver.sh b/loadserver.sh index 0825fe9..66a7c0b 100644 --- a/loadserver.sh +++ b/loadserver.sh @@ -1,3 +1,3 @@ #!/bin/bash cd "$(dirname "$(realpath "$0")")"; -waitress-serve --port=3333 api:api \ No newline at end of file +python3 api.py \ No newline at end of file diff --git a/mkdocs.yml b/mkdocs.yml index 4f1b4bb..602e18d 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -4,4 +4,5 @@ nav: - Quick Start: quick_start.md - How to write a cook: howto_writecook.md - Hierarchy: file_hierarchy.md + - Changelog: changelog.md theme: readthedocs \ No newline at end of file diff --git a/sql.py b/sql.py index c508fab..94e2cc3 100644 --- a/sql.py +++ b/sql.py @@ -54,4 +54,9 @@ def retOption(option): except: return None -debugsql = retOption('DebugSQL') \ No newline at end of file +debugsql = retOption('DebugSQL') + +#Make updates if neccesary +sqlv=retOption('SQLVersion') +if sqlv == 1: + pass #Its latest version of SQL \ No newline at end of file