Files
CyberPanel/baseTemplate/views.py

353 lines
12 KiB
Python
Raw Normal View History

2017-10-24 19:16:36 +05:00
# -*- coding: utf-8 -*-
2022-03-02 13:18:22 +05:00
from django.shortcuts import render, redirect
from django.http import HttpResponse
from plogical.getSystemInformation import SystemInformation
import json
from loginSystem.views import loadLoginPage
2017-10-24 19:16:36 +05:00
from .models import version
import requests
import subprocess
import shlex
import os
import plogical.CyberCPLogFileWriter as logging
2023-10-17 17:52:49 +05:00
from plogical.acl import ACLManager
2019-06-26 03:57:16 +05:00
from manageServices.models import PDNSStatus
from django.views.decorators.csrf import ensure_csrf_cookie
2023-10-17 17:52:49 +05:00
from plogical.processUtilities import ProcessUtilities
from plogical.httpProc import httpProc
2017-10-24 19:16:36 +05:00
# Create your views here.
2022-04-24 22:41:34 +05:00
VERSION = '2.3'
BUILD = 4
2017-10-24 19:16:36 +05:00
@ensure_csrf_cookie
2017-10-24 19:16:36 +05:00
def renderBase(request):
template = 'baseTemplate/homePage.html'
cpuRamDisk = SystemInformation.cpuRamDisk()
finaData = {'ramUsage': cpuRamDisk['ramUsage'], 'cpuUsage': cpuRamDisk['cpuUsage'],
'diskUsage': cpuRamDisk['diskUsage']}
proc = httpProc(request, template, finaData)
return proc.render()
2017-10-24 19:16:36 +05:00
@ensure_csrf_cookie
def versionManagement(request):
getVersion = requests.get('https://cyberpanel.net/version.txt')
latest = getVersion.json()
latestVersion = latest['version']
latestBuild = latest['build']
currentVersion = VERSION
currentBuild = str(BUILD)
2022-03-02 13:18:22 +05:00
u = "https://api.github.com/repos/usmannasir/cyberpanel/commits?sha=v%s.%s" % (latestVersion, latestBuild)
2023-10-29 12:15:46 +05:00
logging.writeToFile(u)
r = requests.get(u)
latestcomit = r.json()[0]['sha']
command = "git -C /usr/local/CyberCP/ rev-parse HEAD"
output = ProcessUtilities.outputExecutioner(command)
Currentcomt = output.rstrip("\n")
notechk = True
if Currentcomt == latestcomit:
notechk = False
2023-10-29 12:15:46 +05:00
template = 'baseTemplate/versionManagment.html'
finalData = {'build': currentBuild, 'currentVersion': currentVersion, 'latestVersion': latestVersion,
'latestBuild': latestBuild, 'latestcomit': latestcomit, "Currentcomt": Currentcomt, "Notecheck": notechk}
proc = httpProc(request, template, finalData, 'versionManagement')
return proc.render()
@ensure_csrf_cookie
def upgrade_cyberpanel(request):
if request.method == 'POST':
try:
upgrade_command = 'sh <(curl https://raw.githubusercontent.com/usmannasir/cyberpanel/stable/preUpgrade.sh || wget -O - https://raw.githubusercontent.com/usmannasir/cyberpanel/stable/preUpgrade.sh)'
result = subprocess.run(upgrade_command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.returncode == 0:
response_data = {'success': True, 'message': 'CyberPanel upgrade completed successfully.'}
else:
response_data = {'success': False, 'message': 'CyberPanel upgrade failed. Error output: ' + result.stderr}
except Exception as e:
response_data = {'success': False, 'message': 'An error occurred during the upgrade: ' + str(e)}
2017-10-24 19:16:36 +05:00
def getAdminStatus(request):
try:
2018-08-18 00:39:10 +05:00
val = request.session['userID']
currentACL = ACLManager.loadedACL(val)
2017-10-24 19:16:36 +05:00
2019-06-26 03:57:16 +05:00
if os.path.exists('/home/cyberpanel/postfix'):
currentACL['emailAsWhole'] = 1
else:
currentACL['emailAsWhole'] = 0
if os.path.exists('/home/cyberpanel/pureftpd'):
currentACL['ftpAsWhole'] = 1
else:
currentACL['ftpAsWhole'] = 0
try:
pdns = PDNSStatus.objects.get(pk=1)
currentACL['dnsAsWhole'] = pdns.serverStatus
except:
2020-05-15 01:07:04 +05:00
if ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu or ProcessUtilities.decideDistro() == ProcessUtilities.ubuntu20:
2019-07-25 14:12:54 +05:00
pdnsPath = '/etc/powerdns'
else:
pdnsPath = '/etc/pdns'
if os.path.exists(pdnsPath):
2019-06-26 03:57:16 +05:00
PDNSStatus(serverStatus=1).save()
currentACL['dnsAsWhole'] = 1
else:
currentACL['dnsAsWhole'] = 0
2018-08-18 00:39:10 +05:00
json_data = json.dumps(currentACL)
2017-10-24 19:16:36 +05:00
return HttpResponse(json_data)
except KeyError:
return HttpResponse("Can not get admin Status")
2017-10-24 19:16:36 +05:00
def getSystemStatus(request):
try:
val = request.session['userID']
currentACL = ACLManager.loadedACL(val)
2017-10-24 19:16:36 +05:00
HTTPData = SystemInformation.getSystemInformation()
json_data = json.dumps(HTTPData)
return HttpResponse(json_data)
except KeyError:
return HttpResponse("Can not get admin Status")
2017-10-24 19:16:36 +05:00
def getLoadAverage(request):
try:
val = request.session['userID']
currentACL = ACLManager.loadedACL(val)
loadAverage = SystemInformation.cpuLoad()
loadAverage = list(loadAverage)
one = loadAverage[0]
two = loadAverage[1]
three = loadAverage[2]
2022-03-02 13:18:22 +05:00
loadAvg = {"one": one, "two": two, "three": three}
json_data = json.dumps(loadAvg)
return HttpResponse(json_data)
except KeyError:
return HttpResponse("Not allowed.")
2017-10-24 19:16:36 +05:00
@ensure_csrf_cookie
def versionManagment(request):
## Get latest version
getVersion = requests.get('https://cyberpanel.net/version.txt')
latest = getVersion.json()
latestVersion = latest['version']
latestBuild = latest['build']
## Get local version
currentVersion = VERSION
currentBuild = str(BUILD)
u = "https://api.github.com/repos/usmannasir/cyberpanel/commits?sha=v%s.%s" % (latestVersion, latestBuild)
logging.CyberCPLogFileWriter.writeToFile(u)
r = requests.get(u)
latestcomit = r.json()[0]['sha']
command ="git -C /usr/local/CyberCP/ rev-parse HEAD"
output = ProcessUtilities.outputExecutioner(command)
Currentcomt = output.rstrip("\n")
notechk = True
# command ="git fetch -C /usr/local/CyberCP/"
# output = ProcessUtilities.outputExecutioner(command)
#
# command ="git -C /usr/local/CyberCP/ log %s..%s --pretty=oneline | wc -l" % ( Currentcomt, latestcomit)
# output = ProcessUtilities.outputExecutioner(command)
#
# numCommits = output.rstrip("\n")
if(Currentcomt == latestcomit):
notechk = False
template = 'baseTemplate/versionManagment.html'
finalData = {'build': currentBuild, 'currentVersion': currentVersion, 'latestVersion': latestVersion,
'latestBuild': latestBuild, 'latestcomit': latestcomit, "Currentcomt": Currentcomt, "Notecheck" : notechk }
proc = httpProc(request, template, finalData, 'versionManagement')
return proc.render()
2017-10-24 19:16:36 +05:00
def upgrade(request):
try:
admin = request.session['userID']
currentACL = ACLManager.loadedACL(admin)
2017-10-24 19:16:36 +05:00
data = json.loads(request.body)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson('fetchStatus', 0)
2024-01-10 09:50:52 +05:00
from plogical.applicationInstaller import ApplicationInstaller
extraArgs = {}
extraArgs['branchSelect'] = data["branchSelect"]
background = ApplicationInstaller('UpgradeCP', extraArgs)
background.start()
2022-03-02 13:18:22 +05:00
adminData = {"upgrade": 1}
2017-10-24 19:16:36 +05:00
json_data = json.dumps(adminData)
return HttpResponse(json_data)
except KeyError:
2022-03-02 13:18:22 +05:00
adminData = {"upgrade": 1, "error_message": "Please login or refresh this page."}
2017-10-24 19:16:36 +05:00
json_data = json.dumps(adminData)
return HttpResponse(json_data)
2017-10-24 19:16:36 +05:00
def upgradeStatus(request):
try:
val = request.session['userID']
try:
if request.method == 'POST':
from plogical.upgrade import Upgrade
path = Upgrade.LogPathNew
2017-10-24 19:16:36 +05:00
try:
upgradeLog = ProcessUtilities.outputExecutioner(f'cat {path}')
2017-10-24 19:16:36 +05:00
except:
final_json = json.dumps({'finished': 0, 'upgradeStatus': 1,
'error_message': "None",
'upgradeLog': "Upgrade Just started.."})
return HttpResponse(final_json)
2022-03-02 13:18:22 +05:00
if upgradeLog.find("Upgrade Completed") > -1:
2024-01-09 19:51:53 +05:00
command = f'rm -rf {path}'
ProcessUtilities.executioner(command)
2017-10-24 19:16:36 +05:00
final_json = json.dumps({'finished': 1, 'upgradeStatus': 1,
'error_message': "None",
'upgradeLog': upgradeLog})
return HttpResponse(final_json)
else:
final_json = json.dumps({'finished': 0, 'upgradeStatus': 1,
'error_message': "None",
'upgradeLog': upgradeLog})
return HttpResponse(final_json)
2019-12-10 15:09:10 +05:00
except BaseException as msg:
2017-10-24 19:16:36 +05:00
final_dic = {'upgradeStatus': 0, 'error_message': str(msg)}
final_json = json.dumps(final_dic)
return HttpResponse(final_json)
except KeyError:
final_dic = {'upgradeStatus': 0, 'error_message': "Not Logged In, please refresh the page or login again."}
final_json = json.dumps(final_dic)
return HttpResponse(final_json)
2017-10-24 19:16:36 +05:00
def upgradeVersion(request):
try:
vers = version.objects.get(pk=1)
getVersion = requests.get('https://cyberpanel.net/version.txt')
latest = getVersion.json()
vers.currentVersion = latest['version']
vers.build = latest['build']
vers.save()
return HttpResponse("Version upgrade OK.")
2019-12-10 15:09:10 +05:00
except BaseException as msg:
2017-10-24 19:16:36 +05:00
logging.CyberCPLogFileWriter.writeToFile(str(msg))
return HttpResponse(str(msg))
2021-07-16 15:00:35 +05:00
2021-07-16 15:00:35 +05:00
@ensure_csrf_cookie
def design(request):
### Load Custom CSS
2021-07-16 15:00:35 +05:00
try:
from baseTemplate.models import CyberPanelCosmetic
cosmetic = CyberPanelCosmetic.objects.get(pk=1)
except:
from baseTemplate.models import CyberPanelCosmetic
cosmetic = CyberPanelCosmetic()
cosmetic.save()
2022-05-11 12:45:24 +05:00
val = request.session['userID']
currentACL = ACLManager.loadedACL(val)
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson('reboot', 0)
2021-07-16 15:00:35 +05:00
finalData = {}
if request.method == 'POST':
MainDashboardCSS = request.POST.get('MainDashboardCSS', '')
cosmetic.MainDashboardCSS = MainDashboardCSS
cosmetic.save()
finalData['saved'] = 1
####### Fetch sha...
2022-03-02 13:18:22 +05:00
sha_url = "https://api.github.com/repos/usmannasir/CyberPanel-Themes/commits"
2022-03-02 13:18:22 +05:00
sha_res = requests.get(sha_url)
2022-03-02 13:18:22 +05:00
sha = sha_res.json()[0]['sha']
l = "https://api.github.com/repos/usmannasir/CyberPanel-Themes/git/trees/%s" % sha
fres = requests.get(l)
tott = len(fres.json()['tree'])
finalData['tree'] = []
for i in range(tott):
if (fres.json()['tree'][i]['type'] == "tree"):
finalData['tree'].append(fres.json()['tree'][i]['path'])
2021-07-16 15:00:35 +05:00
template = 'baseTemplate/design.html'
finalData['cosmetic'] = cosmetic
proc = httpProc(request, template, finalData, 'versionManagement')
return proc.render()
2022-03-02 13:18:22 +05:00
2022-03-02 13:18:22 +05:00
def getthemedata(request):
try:
val = request.session['userID']
currentACL = ACLManager.loadedACL(val)
data = json.loads(request.body)
2022-03-08 20:10:53 +05:00
if currentACL['admin'] == 1:
pass
else:
return ACLManager.loadErrorJson('reboot', 0)
#logging.CyberCPLogFileWriter.writeToFile(str(data) + " [themedata]")
2022-03-02 13:18:22 +05:00
url = "https://raw.githubusercontent.com/usmannasir/CyberPanel-Themes/main/%s/design.css" % data['Themename']
res = requests.get(url)
2022-03-02 13:18:22 +05:00
rsult = res.text
final_dic = {'status': 1, 'csscontent': rsult}
final_json = json.dumps(final_dic)
return HttpResponse(final_json)
except BaseException as msg:
final_dic = {'status': 0, 'error_message': str(msg)}
final_json = json.dumps(final_dic)
return HttpResponse(final_json)