Files
powerfulcomputermanager/client/control.pyw
2019-06-27 17:51:59 +02:00

282 lines
13 KiB
Python

#!/usr/bin/python3
# Version 0.7
import easygui
import configparser
import json
import requests
import subprocess, platform
import hashlib #SHA256
from translation import T
passha256 = None # Password (Global)
def ping(host):
"""
Returns True if host (str) responds to a ping request.
Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
"""
# Option for the number of packets as a function of
param = '-n' if platform.system().lower()=='windows' else '-c'
# Building the command. Ex: "ping -c 1 google.com"
command = ['ping', param, '1', host]
return subprocess.call(command) == 0
## sendmenudot, returns of choice of a series of choices that has "." as delimiter inside it (For returning index)
def sendmenudot(text,title,choices):
menu = easygui.choicebox(text,title,choices)
if menu is not None:
return menu.split('.')[0]
else:
return menu
## showchoicesapi, suburl has to have params (NOT inlcuding server part)
def showchoicesapi(text,title,suburl,field='Name'):
global c_server
global passha256
if 'Password=' in suburl:
twopart = ""
elif '?' in suburl:
twopart = '&Password='+str(passha256)
else:
twopart= '?Password='+str(passha256)
try:
jsonobj = json.loads(requests.get(c_server+suburl+twopart).text)
listitems = []
for ite in jsonobj:
listitems.append(ite[field])
return easygui.choicebox(text,title,listitems)
except:
easygui.msgbox(msg='Error en la aplicación al consultar', title=title, ok_button='OK')
return None
def sendsettoapi(suburl,goodtext): # Send a add/del/modify to API. Doesn't return more than "Valid" and "Not valid"
global c_server
global passha256
if 'Password=' in suburl:
twopart = ""
elif '?' in suburl:
twopart = '&Password='+str(passha256)
else:
twopart= '?Password='+str(passha256)
try:
jsonobj = json.loads(requests.get(c_server+suburl+twopart).text)
#jsonobj['RESULT'] has to exist for next if
try:
jsonobj['RESULT']
except:
jsonobj['RESULT'] = ""
if jsonobj is not None and jsonobj['RESULT'] is not None and jsonobj['RESULT'] == 'ERROR':
try:
easygui.msgbox(jsonobj['TEXT'],"Error","Ok")
except:
easygui.msgbox("Error no especificado","Error","Ok")
return 1
else:
easygui.msgbox(goodtext,"Exito","Ok")
return 0
except:
easygui.msgbox("Error inesperado","Error","Ok")
return 1
def returnvalueapi(suburl,field="Name"):
global c_server
global passha256
if 'Password=' in suburl:
twopart = ""
elif '?' in suburl:
twopart = '&Password='+str(passha256)
else:
twopart= '?Password='+str(passha256)
try:
jsonobj = json.loads(requests.get(c_server+suburl+twopart).text)
return jsonobj[field]
except:
easygui.msgbox(msg='Error en la aplicación al consultar', 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'])
if menu == '1':
mcomputers()
elif menu == '2':
mgroups()
elif menu == '3':
mcooks()
elif menu == '4':
mreports()
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')])
if menu == '1':
newcomputer = easygui.enterbox("Nombre del nuevo equipo",T('Add computer'))
if easygui.ynbox("Nombre del equipo: '"+newcomputer+"'. ¿Seguro?",T('Add computer')):
sendsettoapi("/add/computer?ComputerName="+newcomputer,"Equipo añadido a la base de datos")
elif menu == '2':
whatc = showchoicesapi("Seleccione equipo a borrar",T('Remove computer'),"/get/computers")
if whatc is not None and easygui.ynbox("Se va a borrar el equipo '"+whatc+"'. ¿Seguro?",T('Remove computer')):
sendsettoapi("/del/computer?ComputerName="+whatc,T('Computer deleted'))
elif menu == '3':
m_addcomputergroup()
elif menu == '4':
showchoicesapi(T('Computers list'),T('Computers list'),"/get/computers")
elif menu == '5':
computer = showchoicesapi(T('Select a computer'),T('Computer status'),"/get/computers")
showchoicesapi(T('Cooks of computer')+' '+computer,T('Computer status'),"/get/cookpend?ComputerName="+computer+"&SeeAll=1",'CookName')
showchoicesapi(T('Cooks pending of computer')+' '+computer,T('Computer status'),"/get/cookpend?ComputerName="+computer,'CookName')
showchoicesapi(T('Groups of computer')+' '+computer,T('Computer status'),"/get/groups?ComputerName="+computer,'Name')
elif menu is None:
menuprinc()
return
mcomputers()
def mgroups():
menu = sendmenudot(T('Groups menu'),T('Select option'),['1.'+T('Add group'),'2.'+T('Remove group'),'3.'+T('Add computer to group'),'4.'+T('Remove computer of a group'),'5.Listado de grupos','6.Listado de equipos de un grupo'])
if menu == '1':
newgroup = easygui.enterbox(T('New group name'),T('Add group'))
if easygui.ynbox("Nombre del grupo: '"+newgroup+"'. ¿Seguro?",T('Add group')):
sendsettoapi("/add/group?GroupName="+newgroup,"Grupo añadido a la base de datos")
elif menu == '2':
group = showchoicesapi("Lista de grupos. Selecciona uno para borrarlo",T('Remove group'),"/get/groups",'Name')
if group is not None and easygui.ynbox("Borrar grupo '"+group+"'. ¿Seguro?",T('Remove group')):
sendsettoapi("/del/group?GroupName="+group,T('Group deleted'))
elif menu == '3':
m_addcomputergroup()
elif menu == '4':
m_delcomputergroup()
elif menu == '5':
showchoicesapi("Listado de grupos","Listado de grupos","/get/groups",field='Name')
elif menu == '6':
group = showchoicesapi("Lista de grupos","Listado de equipos de un grupo","/get/groups")
showchoicesapi("Lista de equipos del grupo "+group,"Listado de equipos de un grupo","/get/computersgrp?GroupName="+group)
elif menu is None:
menuprinc()
return
mgroups()
def mcooks():
global c_server
global c_resources
menu = sendmenudot(T('Cooks menu'),T('Select option'),['1.Detalles de una receta','2.'+T('Rename cook'),'3.Añadir receta a un grupo','4.Eliminar receta de un grupo','5.Grupos de una receta'])
if menu == '1':
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)
list = []
s_err = 0
s_com = 0
s_lastrev = returnvalueapi('/get/lastrevisioncook?CookName='+cook,"Revision")
for ite in jsonobj:
s_com = s_com + 1
if ite['Error'] == 0:
err = " implementado correctamente"
else:
err = " con errores"
s_err = s_err + 1
list.append(ite['Name']+" -> Revision "+str(ite['Revision'])+err)
easygui.choicebox("Detalles de equipos de la receta "+cook+"\nEquipos: "+str(s_com)+" Con errores: "+str(s_err)+'\nUltima revision: '+str(s_lastrev),"Detalles de una receta",list)
elif menu == '2':
cook = showchoicesapi("Lista de recetas implementadas en algún grupo. Selecciona una para renombrarla. Si la receta no está en ningún grupo, se puede renombrar desde fuera.",T('Rename cook'),c_server+"/get/cookall",'CookName')
if cook is not None:
newname = easygui.enterbox("Nombre de la nueva receta","Renombrar receta")
if newname is not None and easygui.ynbox("Cambiar nombre de la receta '"+cook+"' por '"+newname+"'. ¿Seguro?",T('Rename cook')):
sendsettoapi("/upd/cookname?CookName="+cook+"&CookNewName="+newname,"Receta cambiada de nombre")
elif menu == '3':
cook = easygui.enterbox(T('Name of the cook'),"Añadir receta a un grupo")
group = showchoicesapi("Lista de grupos existentes","Listado de grupos",c_server+"/get/groups")
if easygui.ynbox("Añadir la receta "+cook+" al grupo '"+group+"'. ¿Seguro?","Añadir receta a un grupo"):
sendsettoapi("/add/cookgrp?CookName="+cook+"&GroupName="+group,"Receta añadida al grupo")
elif menu == '4':
cook = showchoicesapi("Lista de recetas implementadas en algún grupo. Selecciona una para elegir un grupo de esa receta para borrar. Si la receta no está en ningún grupo, no saldrá.","Eliminar receta de un grupo","/get/cookall",'CookName')
if cook is not None:
group = showchoicesapi("Lista de grupos que tienen esa receta. Selecciona el grupo a quitar","Eliminar receta de un grupo","/get/grpcook?CookName="+cook,'Name')
if group is not None and easygui.ynbox("Se va a quitar la receta "+cook+" del grupo "+group+". ¿Seguro?","Eliminar receta de un grupo"):
sendsettoapi("/del/cookgrp?CookName="+cook+"&GroupName="+group,"Receta quitada del grupo")
elif menu == '5':
cook = showchoicesapi("Lista de recetas implementadas en algún grupo. Selecciona una para elegir un grupo de esa receta para borrar. Si la receta no está en ningún grupo, no saldrá.","Eliminar receta de un grupo","/get/cookall",'CookName')
if cook is not None:
showchoicesapi("Lista de grupos que tienen esa receta. Selecciona el grupo a quitar","Eliminar receta de un grupo","/get/grpcook?CookName="+cook,'Name')
elif menu is None:
menuprinc()
return
mcooks()
def mreports():
menu = sendmenudot(T('Reports menu'),T('Select option'),['1.'+T('Computers list'),'2.'+T('Groups list'),'3.Equipos y recetas de un grupo','4.Grupos de una receta'])
if menu == '1': #Listado de equipos
showchoicesapi(T('Computers list'),T('Computers list'),"/get/computers")
elif menu == '2': #Listado de grupos
showchoicesapi(T('Groups list'),T('Groups list'),"/get/groups")
elif menu == '3':
group = showchoicesapi(T('Groups list')+'. '+T('Select a group'),T('Groups list'),"/get/groups")
showchoicesapi("Lista de equipos del grupo "+group,T('List of computers and cooks of a group'),"/get/computersgrp?GroupName="+group)
showchoicesapi("Lista de recetas del grupo "+group,T('List of computers and cooks of a group'),"/get/cookgrp?GroupName="+group,'CookName')
elif menu == '4':
cook = showchoicesapi("Lista de recetas con grupo. Selecciona una para ver sus grupos",T('List of groups of a cook'),"/get/cookall",'CookName')
if cook is not None:
showchoicesapi("Lista de grupos de la receta "+cook,T('List of groups of a cook'),"/get/grpcook?CookName="+cook)
elif menu is None:
menuprinc()
return
mreports()
def m_addcomputergroup():
whatc = showchoicesapi(T('Select computer to add to a group'),T('Add computer to group'),"/get/computers")
if whatc is None:
return
whatg = showchoicesapi(T('Select group to be added'),T('Add computer to group'),"/get/groups")
if whatg is None:
return
sendsettoapi("/add/grpcomputer?ComputerName="+whatc+"&GroupName="+whatg,"Equipo añadido al grupo")
def m_delcomputergroup():
computer = showchoicesapi("Seleccione equipo para buscar un grupo que borrar",T('Remove computer of a group'),"/get/computers")
if computer is None:
return
group = showchoicesapi(T('Select group to delete'),T('Remove computer of a group'),"/get/groups?ComputerName="+computer)
if group is None:
return
if easygui.ynbox("Quitar el equipo "+computer+" del grupo '"+group+"'. ¿Seguro?",T('Remove computer of a group')):
sendsettoapi("/del/grpcomputer?ComputerName="+computer+"&GroupName="+group,"Equipo quitado del grupo")
# Check password before starting all
pa = returnvalueapi("/check/password?Password=None",field="EXITCODE")
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'))
if passw==passw2 and passw is not None: # Password match
passha256 = hashlib.sha256(passw.encode()).hexdigest()
re = returnvalueapi("/upd/password?NewPassword="+passha256,field="RESULT") # Create password in database
if re=='OK': # All right. Start app
menuprinc()
else: # Fail. Not controlled
easygui.msgbox(T('Error unespecified. App will exit'),T('Set password'))
else: # Password not match
easygui.msgbox(T('Password not match. App will exit'),T('Set password'))
#Exit
else: # There is a password
passw = easygui.passwordbox(T('Enter password to start'),T('Enter password'))
if passw is None:
quit()
passha256 = hashlib.sha256(passw.encode()).hexdigest()
re = returnvalueapi("/check/password?Password="+passha256,field="EXITCODE") # Create password in database
if re == '0': # Password is right
menuprinc()
else:
easygui.msgbox(T('Password not match. App will exit'),T('Enter password'))