Changes to web gui and fixes

This commit is contained in:
2020-07-03 18:37:34 +02:00
parent 609d821501
commit 3deb367e89
9 changed files with 94 additions and 25 deletions

View File

@@ -38,12 +38,15 @@ def returnvalueapi(suburl,field="Name"):
r=(requests.post(c_server+suburl+twopart, verify=False).text).replace("\'", "\"").replace('\\"',"'").replace(': None',': "None"')
try:
#print(suburl+twopart+"->"+r)
#print(suburl+twopart+"->"+r)
jsonobj = json.loads(r)
if isinstance(jsonobj, list):
print("LIST")
jsonobj = jsonobj[0]
return jsonobj[field]
except:
print('Error: '+str(r))
return str({'TEXT':r,'RESULT':'ERROR'})
print('Error: '+str(r))
return str({'TEXT':r,'RESULT':'ERROR'})
def returnTable(suburl,field=["Name"]):
global c_server
@@ -82,7 +85,7 @@ def pAdminIndex(): #Admin Index page
table = returnTable("/get/computers",['ID_C','Name','RAM','CPUName','SOVersion','SOCaption','HDD','LastConnection','RAMFree'])
for lista in table:
lista.append(returnTable("/get/groups?ComputerID="+lista[0],["Name"])) #lista[9]¿
lista.append(returnTable("/get/groups?ComputerID="+lista[0],["ID_G","Name"])) #lista[9]¿
if lista[6] is not None:
try:
lista[6]=json.loads(base64.b64decode(lista[6]).decode('UTF-8'))
@@ -126,13 +129,18 @@ def pAdminComputer(): #Admin see one group
computerid=request.args.get('ID_C')
if computerid is not None and computerid.isnumeric():
computername = returnvalueapi('/get/computers?ComputerID='+str(computerid),"Name")
groups = returnTable("/get/groups?ComputerName="+str(computername),['ID_G','Name'])
#####IT DOESNT HAVE TEMPLATE CREATED
groups = returnTable("/get/groups?ComputerID="+str(computerid),['ID_G','Name'])
for key in range(len(groups)): #Cookgs of every group
print(groups[key])
groups[key].append(returnTable("/get/cookgrp?GroupID="+groups[key][0],['CookName']))
return render_template('/admincomputer.tmpl', title="Computer "+computername,computerid=computerid,computername=computername,groups=groups)
return redirect('/admin')
@app.route("/admin/groups",methods=['GET'])
@app.route("/admin/groups/",methods=['GET'])
def pAdminGroups(): #Admin Index groups
if returnvalueapi('/check/password?Password='+str(request.cookies.get('admin_logued')),'EXITCODE') != '0':
return render_template('/login.tmpl', title="Login")
@@ -159,8 +167,14 @@ def pAdminGroup(): #Admin see one group
for cook in tem:
to = []
to.append(cook[0])
to.append(returnvalueapi('/get/lastrevisioncook?CookName='+cook[0],"Revision"))
to.append(returnTable("/get/statuscook?CookName="+cook[0],'ASIS'))
to.append(int(returnvalueapi('/get/lastrevisioncook?CookName='+cook[0],"Revision"))) # Has to be a number
tabletemp = returnTable("/get/statuscook?CookName="+cook[0],'ASIS')
print (tabletemp)
for x in range(len(tabletemp)):
print(type(tabletemp[x]['Revision']))
if type(tabletemp[x]['Revision']) != int: # Si no es un número, cambiar.
tabletemp[x]['Revision'] = 0
to.append(tabletemp)
cooksdata.append(to)
tem = (returnTable("/get/cookall",'ASIS')) #Lista de todas las recetas
@@ -243,29 +257,44 @@ def pAdminCookDelgroup(): # Add cook to group
else:
return "Error of arguments"
#First time password set
@app.route("/firsttime",methods=['POST'])
def pFirstTime(): #Add computer form enter
passwd = request.args.get('password')
passwd = hashlib.sha256(passwd.encode()).hexdigest()
if passwd != None:
r = returnvalueapi("/upd/password?NewPassword="+passwd,field="RESULT")
if r == "OK":
res = make_response(redirect(url_for('pAdminIndex')))
res.set_cookie("admin_logued",value=passwd)
else: #Hmm..Unespecified error
render_template('/firsttime.tmpl')
else:
return render_template('/firsttime.tmpl')
@app.route("/",methods=['GET'])
def pIndex(): #Index page
howispasswd=returnvalueapi('/check/password?Password='+str(request.cookies.get('admin_logued')),'EXITCODE')
if howispasswd == '0': # Logued
return redirect(url_for('pAdminIndex'))
if howispasswd == '1' or howispasswd == '2': # Has to login
elif howispasswd == '1' or howispasswd == '2': # Has to login
return render_template('/login.tmpl')
if howispasswd == '3': # No password yet
return 'Yet to do it..'
elif howispasswd == '3': # No password yet
return render_template('/firsttime.tmpl')
@app.route("/login",methods=['GET','POST'])
def pLogin(): #Login
if request.values.get('password'):
trpass = hashlib.sha256(request.values.get('password').encode()).hexdigest()
#print(returnvalueapi('/check/password?Password='+trpass,'EXITCODE'))
if returnvalueapi('/check/password?Password='+trpass,'EXITCODE') == '0':
howispasswd = returnvalueapi('/check/password?Password='+trpass,'EXITCODE')
if howispasswd == '0':
res = make_response(redirect(url_for('pAdminIndex')))
res.set_cookie("admin_logued",value=trpass)
return res
else:
elif howispasswd in (1,2):
return render_template('/login.tmpl')
elif howispasswd == '3': # No password yet
return render_template('/firsttime.tmpl')
else:
return render_template('/login.tmpl')

View File

@@ -15,8 +15,9 @@
</tr>
</thead>
<tbody>
{% for item in tablegroups %} {#['ID_G','Name','Cooks[CookName]']#}
{% for item in groups %} {#['ID_G','Name','Cooks[CookName]']#}
<tr>
<td><a href="/admin/group?ID_G={{item.0}}">{{item.0}}</a></td>
<td><a href="/admin/group?ID_G={{item.0}}">{{item.1}}</a></td>
<td style='width:50%;'>
{% for x in item.2 %}

View File

@@ -130,7 +130,7 @@
<td>{{item.1}}</td>
<td>
{% for subitem in item.2|sort(attribute='Revision')|sort(attribute='Name') %} {# item.2 = AppliedTo #}
{{subitem.Name}}{% if subitem.Revision|int < item.1|int %}<span style="color:red">({{subitem.Revision}})</span>{% elif subitem.Error != 0 %}<span style="color:orange;font-weigth:bold;font-style:italic" title="{{subitem.ErrorDesc}}">(Error r.{{subitem.Revision}})</span>{% endif %},
{{subitem.Name}}{% if subitem.Revision|int < item.1|int %}<span style="color:red">({{subitem.Revision}})</span>{% elif subitem.Error > 0 %}<span style="color:orange;font-weigth:bold;font-style:italic" title="{{subitem.ErrorDesc}}">(Error r.{{subitem.Revision}})</span>{% endif %},
{% endfor %}
</tr>
{% endfor %}

View File

@@ -26,13 +26,13 @@
</div>
</div>
<!-- Modal Delete Computer To Database -->
<!-- Modal Delete Computer From Database -->
<div class="modal fade" id="modalDel" tabindex="-1" role="dialog" aria-labelledby="modalDelLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<form method="get" action="/admin/delcomputer">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalDelLabel">Delete computer to Database. NOT REVERSIBLE</h5>
<h5 class="modal-title" id="modalDelLabel">Delete computer from Database. NOT REVERSIBLE</h5>
</div>
<div class="modal-body">
<div class="form-group">
@@ -76,11 +76,11 @@
{% for item in tablecomputers %} {#['ID_C','Name','RAM','CPUName','SOVersion','SOCaption','HDD','LastConnection','RamFree','GroupsNames']#}
<tr>
<td>{{item.0}}</td>
<td>{{item.1}}</td>
<td><a href="/admin/computer?ID_C={{item.0}}">{{item.1}}</a></td>
<td>{{item.5}} {{item.4}}</td>
<td width='200px'>
{% for x in item.9 %}
{{x.0}},
<a href="/admin/group?ID_G={{x.0}}">{{x.1}}</a>,
{% endfor %}
</td>
<td>{{item.3}}</td>

View File

@@ -0,0 +1,17 @@
{# -*- coding: utf-8 -*- #}
{% extends 'baseadmin.tmpl' %}
{% block content %}
<h2>Login</h2>
<form action="/firsttime" method="POST">
<div class="table-responsive">
<table class="table table-striped table-sm">
<tr>
<td>Please put password for program. Do not forget it!<input type="password" name="password" id="password" /></td>
</tr>
<tr>
<td><button type="submit">Set password</button></td>
</tr>
</table>
</div>
</form>
{% endblock %}

2
api.py
View File

@@ -113,7 +113,7 @@ def getComputers():
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")
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")

View File

@@ -1,4 +1,4 @@
# Build 14. Using API 2
# Build 15. Using API 2
param([Int32]$startup=0)
#Write-Host $startup
$srcdir = $PSCommandPath | Split-Path -Parent
@@ -48,7 +48,7 @@ if ($SOVersion -match "^10.0."){ #If its Windows 10, add revision number for kno
}
# Update Computer Data
$CPUInfo = (Get-CimInstance Win32_Processor) | Select Name,MaxClockSpeed,ThreadCount
$CPUInfo = (Get-CimInstance Win32_Processor) | Select-Object Name,MaxClockSpeed,ThreadCount
$CPUName = -join($CPUInfo.ThreadCount, " x ",$CPUInfo.Name.Trim()," (",$CPUInfo.MaxClockSpeed," MHz)")
$RAMInstalled = Get-CimInstance CIM_PhysicalMemory | Measure-Object -Property capacity -Sum | ForEach-Object {[math]::round(($_.sum / 1MB),2)}
$RAMFree = [Math]::Round((Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory/1024,0)
@@ -58,7 +58,7 @@ $objDisks = Get-CimInstance -Class win32_LogicalDisk -Filter "DriveType = '3'"
$diskResults = @()
ForEach( $disk in $objDisks )
{
$ThisVolume = "" | select Volume,Capacity,FreeSpace
$ThisVolume = "" | Select-Object Volume,Capacity,FreeSpace
$ThisVolume.Volume = $disk.DeviceID
$ThisVolume.Capacity = $([Math]::Round($disk.Size / 1GB,2))
$ThisVolume.FreeSpace = $([Math]::Round($disk.FreeSpace / 1GB,2))
@@ -104,6 +104,7 @@ foreach ($CookName in $cooks){
if ($err -eq 1 -or $exit -eq 1){break} # Halt if err ocurred (And noerror directive is not active)
$step = $step.Split("|")
$param = $step[1]
$param2 = $step[2]
Write-Host $step[0] "-" $step[1]
if($inif -eq $true -and $if -eq $false){ # Only can see "ENDIF" if is in IF and is not true
if ($step[0] -ne "ENDIF" -and $step[0] -ne "ELSE"){
@@ -168,6 +169,22 @@ foreach ($CookName in $cooks){
$err = 1
}
$filesCopied.Add($param) > $null #Add to list
}
"COPY" { # Copy file from repo location to some folder
$parts = $param.Split(";")
if ($parts[1] -ne ""){ #Exists orig and dest
$orig=$parts[0]
$dest=$parts[1]
Copy-Item "$orig" "$dest" -ErrorVariable errvar -Recurse -Force
if ($? -eq $false){ # Error in Copy
$err = 1
}
}else{ #Doesn't sent right
$err = 1
$errvar = "Param not set right. Exiting..."
}
}
"REMOVE" { # Remove files / folders
Remove-Item "$param" -Recurse -Force -ErrorAction Continue # They not see errors (Because error will be file not found)

View File

@@ -1,5 +1,9 @@
# Changelog
## 2020/03/17
- New function copy
- Some fixes
## 2020/02/20
- Fixing more bugs
- First public beta of web gui, it doesn't have some parts but it's working

View File

@@ -34,6 +34,7 @@ Note: Cooks start in directory $env:temp (%TEMP%) from SYSTEM user.
| W | CMD | Cmd command. Beware of quotes, because internally is run as cmd /c "" |
| W/L | PWCMD | Powershell command, runs using Invoke-Command |
| W/L | REPOTOLOCAL | Copy a file from REPO folder configured to local in temp folder. You can copy a file or a folder |
| W/L | COPY | Copy a file from copied to local (REPOTOLOCAL) to any destiantion. Ex: COPY|filec.cfg;C:\Program\filec.cfg|
| W | INSTALLMSI | Installs an MSI file silently (Params /quiet /norestart are put, do not repeat). You can add parameters (Like INSTALLMSI|superapp.msi ADDLOCAL=extension SETASDEFAULT=1) |
| W/L | NOERROR | Creates a block of instructions that not captures errors and continues event if fails<br>Example:<br>NOERROR|Try to delete a file that maybe can not exist<br>PWCMD|Remove-Item C:\Windows\loginstall.txt<br>ENDNOERROR|Finish |
| W/L | ENDNOERROR | Finishes NOERROR Block |