Config support added; Added utilities.py; Clean up of code

Added:
- .ini config support
- lancher.bat to launch program
- added utilities.py for help function

Removed:
- old ununsed input handlers functions
- old ununsed download handler functions
- removed many print()s
This commit is contained in:
Neocky 2021-03-08 22:13:57 +01:00
parent 37d71e6b4b
commit 53ae3b5a64
6 changed files with 100 additions and 122 deletions

2
launcher.bat Normal file
View File

@ -0,0 +1,2 @@
@ECHO OFF
py "%~dp0\src\handle_input.py"

37
src/handle_config.py Normal file
View File

@ -0,0 +1,37 @@
# handles the config and everything around it
import sys
import configparser
import os.path
from consoleoutput import oColors
def checkConfig():
configAvailable = os.path.isfile("./config.ini")
if not configAvailable:
createConfig()
print(oColors.brightRed + "Config created. Edit config before executing again!" + oColors.standardWhite)
input("Press any key + enter to exit...")
sys.exit()
class configValues:
config = configparser.ConfigParser()
config.sections()
config.read("config.ini")
pathToPluginFolder = config['General']['PathToPluginFolder']
return configValues
def createConfig():
config = configparser.ConfigParser(allow_no_value=True)
config['General'] = {}
config['General'][';'] = 'If a local plugin folder exists (True/False): (If false use sftp)'
config['General']['LocalPluginFolder'] = 'True'
config['General']['PathToPluginFolder'] = 'C:\\Users\\USER\\Desktop\\plugins'
config['Remote Server'] = {}
config['Remote Server']['Server'] = '0.0.0.0'
config['Remote Server']['Username'] = 'user'
config['Remote Server']['Password'] = 'longpassword'
with open('./config.ini', 'w') as configfile:
config.write(configfile)

View File

@ -1,9 +1,10 @@
import time
import sys
from consoleoutput import consoleTitle, clearConsole, printMainMenu, oColors
from plugin_downloader import downloadPackageManual, apiCallTest, searchPackage, getPackageVersion
from plugin_downloader import searchPackage, getSpecificPackage
from plugin_updatechecker import updateInstalledPackage, checkInstalledPackage
from handle_config import checkConfig
from utilities import getHelp
def createInputLists():
global COMMANDLIST
@ -11,7 +12,8 @@ def createInputLists():
'get',
'update',
'check',
'exit'
'exit',
'help'
]
global INPUTSELECTEDOBJECT
INPUTSELECTEDOBJECT = [
@ -23,17 +25,23 @@ def createInputLists():
def handleInput(inputCommand, inputSelectedObject, inputParams):
while True:
if inputCommand == 'get':
getPackageVersion(r"C:\\Users\USER\Desktop\\", inputSelectedObject, inputParams)
if inputSelectedObject.isdigit():
getSpecificPackage(inputSelectedObject, checkConfig().pathToPluginFolder, inputParams)
break
else:
searchPackage(inputSelectedObject)
break
if inputCommand == 'update':
#if inputSelectedObject in INPUTSELECTEDOBJECT:
updateInstalledPackage(r'C:\\Users\\USER\\Desktop\\plugins', inputSelectedObject)
updateInstalledPackage(checkConfig().pathToPluginFolder, inputSelectedObject)
break
if inputCommand == 'check':
checkInstalledPackage(r'C:\\Users\\USER\\Desktop\\plugins', inputSelectedObject)
checkInstalledPackage(checkConfig().pathToPluginFolder, inputSelectedObject)
break
if inputCommand == 'exit':
sys.exit()
if inputCommand == 'help':
getHelp()
break
else:
print(oColors.brightRed + "Command not found. Please try again." + oColors.standardWhite)
getInput()
@ -55,43 +63,12 @@ def getInput():
handleInput(inputCommand, inputSelectedObject, inputParams)
def inputOption(inputOptionString):
inputString = None
print(inputOptionString)
if inputOptionString == 1:
inputString = input("SpigotMC Ressource ID: ")
if inputOptionString == 2:
inputString = input("SpigotMC Ressource ID: ")
if inputOptionString == 3:
inputString = input(" SpigotMC Ressource Name: ")
print("ich bin ein test")
return inputString
def handleInputOLD(inputString):
if inputString == "1":
downloadPackageManual()
if inputString == "2":
ressourceId = inputOption(2)
apiCallTest(ressourceId)
if inputString == "3":
ressourceName = inputOption(3)
searchPackage(ressourceName)
if inputString == "4":
#getLatestPackageVersionInteractive(r"C:\\Users\USER\Desktop\\")
print("4")
if inputString == "5":
#updateAllInstalledPackages(r'C:\\Users\\USER\\Desktop\\plugins')
print("5")
def inputMainMenu():
createInputLists()
clearConsole()
checkConfig()
createInputLists()
printMainMenu()
getInput()
#inputSt = input(" pluGET >> ")
#handleInputOLD(inputSt)
def outputTest():
@ -110,7 +87,6 @@ def outputTest():
input("Press key to end program...")
#createCloudScraperInstance()
consoleTitle()
inputMainMenu()
outputTest()

View File

@ -1,7 +1,9 @@
import urllib.request
import cgi
from urllib.error import HTTPError
import re
from web_request import doAPIRequest
from consoleoutput import oColors
from handle_config import checkConfig
def calculateFileSize(downloadFileSize):
@ -11,36 +13,6 @@ def calculateFileSize(downloadFileSize):
return roundedFileSize
# 28140 for Luckperms (Testing only)
def downloadPackageManual():
ressourceId = input("SpigotMC Ressource ID: ")
url = "https://api.spiget.org/v2/resources/" + ressourceId + "/download"
#url2 = "https://api.spiget.org/v2/resources/" + ressourceId + "/versions/latest/download"
#print(url2)
#user_agent = 'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11'
#header = { 'User-agent': 'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11', 'Accept-Encoding': 'gzip, deflate, br' }
#req = urllib.request.Request(url2, headers=header)
#remotefile = urlopen(req)
remotefile = urllib.request.urlopen(url)
filecontent = remotefile.info()['Content-Disposition']
filesize = remotefile.info()['Content-Length']
# getting original filename
value, params = cgi.parse_header(filecontent)
filename = params["filename"]
# creating file path
path = r"C:\\Users\Jan-Luca\Desktop\\"
ppath = path + filename
# download file
urllib.request.urlretrieve(url, ppath)
filesizeData = calculateFileSize(filesize)
print(f"Downloadsize: {filesizeData} MB")
# 89273
def handleRegexPackageName(packageNameFull):
packageNameFull2 = packageNameFull
# trims the part of the package that has for example "[1.1 Off]" in it
@ -49,17 +21,14 @@ def handleRegexPackageName(packageNameFull):
if unwantedpackageNamematch:
unwantedpackageNameString = unwantedpackageName.group()
packageNameFull2 = packageNameFull.replace(unwantedpackageNameString, '')
print(packageNameFull2)
print("packageNameFull2")
# gets the real packagename "word1 & word2" is not supported only gets word 1
packageName = re.search(r'([a-zA-Z]\d*)+(\s?\-*\_*[a-zA-Z]\d*\+*\-*\'*)+', packageNameFull2)
packageNameFullString = packageName.group()
packageNameOnly = packageNameFullString.replace(' ', '')
#print(packageNameOnly)
#print("packageNameOnly")
return packageNameOnly
# TODO ununsed function
def getlatestVersion(packageId):
url = f"https://api.spiget.org/v2/resources/{packageId}/versions/latest"
response = doAPIRequest(url)
@ -67,20 +36,7 @@ def getlatestVersion(packageId):
return packageVersion
def apiCallTest(ressourceId):
url = f"https://api.spiget.org/v2/resources/{ressourceId}"
response = doAPIRequest(url)
print(response)
packageName = response["name"]
packageTag = response["tag"]
print(packageName)
print(packageTag)
packageNameNew = handleRegexPackageName(packageName)
print(packageNameNew)
def getVersionID(packageId, packageVersion):
print(packageVersion)
if packageVersion == None or packageVersion == 'latest':
url = f"https://api.spiget.org/v2/resources/{packageId}/versions/latest"
response = doAPIRequest(url)
@ -108,7 +64,6 @@ def getVersionName(packageId, versionId):
def searchPackage(ressourceName):
url = f"https://api.spiget.org/v2/search/resources/{ressourceName}?field=name"
packageName = doAPIRequest(url)
print(url)
i = 1
print("Index / Name / Description / Downloads")
for ressource in packageName:
@ -120,18 +75,17 @@ def searchPackage(ressourceName):
ressourceSelected = int(input("Select your wanted Ressource: "))
ressourceSelected = ressourceSelected - 1
fileInfo = packageName[ressourceSelected]["file"]
packageUrl = fileInfo["url"]
#fileInfo = packageName[ressourceSelected]["file"]
#packageUrl = fileInfo["url"]
ressourceId = packageName[ressourceSelected]["id"]
print(packageUrl)
print(ressourceId)
getSpecificPackage(ressourceId, checkConfig().pathToPluginFolder)
def downloadSpecificVersion(ressourceId, downloadPath, versionID='latest'):
print(versionID)
if versionID != 'latest':
#url = f"https://spigotmc.org/resources/{ressourceId}/download?version={versionID}"
print("Sorry but specific version downloads aren't supported because of cloudflare protection. :(")
print(oColors.brightRed + "Sorry but specific version downloads aren't supported because of cloudflare protection. :(" + oColors.standardWhite)
print(oColors.brightRed + "Reverting to latest version." + oColors.standardWhite)
url = f"https://api.spiget.org/v2/resources/{ressourceId}/download"
#url = f"https://api.spiget.org/v2/resources/{ressourceId}/versions/latest/download" #throws 403 forbidden error
@ -140,26 +94,31 @@ def downloadSpecificVersion(ressourceId, downloadPath, versionID='latest'):
filesize = remotefile.info()['Content-Length']
urllib.request.urlretrieve(url, downloadPath)
filesizeData = calculateFileSize(filesize)
print(f"File downloaded here: {downloadPath}")
print(f"Downloadsize: {filesizeData} KB")
print(f"File downloaded here: {downloadPath}")
def getPackageVersion(ressourceId, downloadPath, inputPackageVersion='latest'):
def getSpecificPackage(ressourceId, downloadPath, inputPackageVersion='latest'):
url = f"https://api.spiget.org/v2/resources/{ressourceId}"
packageDetails = doAPIRequest(url)
packageName = packageDetails["name"]
#packageTag = packageDetails["tag"]
packageNameNew = handleRegexPackageName(packageName)
versionId = getVersionID(ressourceId, inputPackageVersion)
packageVersion = getVersionName(ressourceId, versionId)
#packageVersion = getlatestVersion(ressourceId)
packageDownloadName = f"{packageNameNew}-{packageVersion}.jar"
downloadPackagePath = downloadPath + packageDownloadName
downloadPackagePath = f"{downloadPath}\\{packageDownloadName}"
if inputPackageVersion is None or inputPackageVersion == 'latest':
try:
downloadSpecificVersion(ressourceId=ressourceId, downloadPath=downloadPackagePath)
except HTTPError as err:
print(oColors.brightRed + f"Error: {err.code} - {err.reason}" + oColors.standardWhite)
else:
try:
downloadSpecificVersion(ressourceId, downloadPackagePath, versionId)
except HTTPError as err:
print(oColors.brightRed + f"Error: {err.code} - {err.reason}" + oColors.standardWhite)
# get latest update > https://api.spiget.org/v2/resources/28140/updates/latest
# this also > https://api.spiget.org/v2/resources/28140/versions/latest

View File

@ -1,9 +1,10 @@
import os
import re
from consoleoutput import oColors #consoleTitle, clearConsole
from plugin_downloader import getPackageVersion #handleInput
from consoleoutput import oColors
from plugin_downloader import getSpecificPackage #handleInput
from web_request import doAPIRequest
from handle_config import checkConfig
def createPluginList():
@ -46,9 +47,6 @@ def compareVersions(pluginId, pluginVersion):
def checkInstalledPackage(pluginFolderPath, inputSelectedObject="all"):
#if inputSelectedObject is not ('all', '*'):
# print(oColors.brightRed + "Only *all* as selected object is supported!" + oColors.standardWhite)
# inputSelectedObject = 'all'
createPluginList()
pluginList = os.listdir(pluginFolderPath)
i = 0
@ -78,7 +76,7 @@ def checkInstalledPackage(pluginFolderPath, inputSelectedObject="all"):
print(f"[{1}] {fileName} - {fileVersion} - {pluginIsOutdated}")
break
else:
print(f"[{i+1}] {fileName} - {fileVersion} - {pluginIsOutdated}") # TODO find better way
print(f"[{i+1}] {fileName} - {fileVersion} - {pluginIsOutdated}") # TODO find better way for the 2 else
else:
print(f"[{i+1}] {fileName} - {fileVersion} - {pluginIsOutdated}")
@ -97,12 +95,6 @@ def updateInstalledPackage(pluginFolderPath, inputSelectedObject='all'):
fileVersion = getFileVersion(plugin)
pluginId = getInstalledPlugin(fileName, fileVersion)
pluginIdStr = str(pluginId)
print(f"name: {fileName}")
print(f"version: {fileVersion}")
# debug purpose
print(inputSelectedObject)
print(INSTALLEDPLUGINLIST)
print(f"pluginId: {pluginId}")
if pluginId == None:
print(oColors.brightRed + "Couldn't find plugin id. Sorry :(" + oColors.standardWhite)
@ -110,16 +102,20 @@ def updateInstalledPackage(pluginFolderPath, inputSelectedObject='all'):
if inputSelectedObject == pluginIdStr or re.search(inputSelectedObject, fileName, re.IGNORECASE):
print(f"Updating: {fileName}")
os.remove(f"C:\\Users\\USER\\Desktop\\plugins\\{plugin}")
getPackageVersion(pluginId, r"C:\\Users\\USER\\Desktop\\plugins\\")
pluginPath = checkConfig().pathToPluginFolder
pluginPath = f"{pluginPath}\\{plugin}"
os.remove(pluginPath)
getSpecificPackage(pluginId, checkConfig().pathToPluginFolder)
break
if inputSelectedObject == 'all':
if INSTALLEDPLUGINLIST[i][2] == True:
print("Deleting old plugin...")
os.remove(f"C:\\Users\\USER\\Desktop\\plugins\\{plugin}")
pluginPath = checkConfig().pathToPluginFolder
pluginPath = f"{pluginPath}\\{plugin}"
os.remove(pluginPath)
print("Downloading new plugin...")
getPackageVersion(pluginId, r"C:\\Users\\USER\\Desktop\\plugins\\")
getSpecificPackage(pluginId, checkConfig().pathToPluginFolder)
i = i + 1
#print(INSTALLEDPLUGINLIST[1][0])
#getLatestPackageVersion(pluginID, r"C:\\Users\USER\Desktop\\plugins\\")
@ -135,9 +131,8 @@ def getInstalledPlugin(localFileName, localFileVersion):
for ressource in packageName:
if plugin_match_found == True:
break
pName = ressource["name"]
#pName = ressource["name"]
pID = ressource["id"]
#print(f" [{i}] {pName} - {pID}")
url2 = f"https://api.spiget.org/v2/resources/{pID}/versions?size=100&sort=-name"
packageVersions = doAPIRequest(url2)
for updates in packageVersions:

9
src/utilities.py Normal file
View File

@ -0,0 +1,9 @@
# misc functions
from consoleoutput import oColors
def getHelp():
print(oColors.brightYellow+ "Need help?" + oColors.standardWhite)
print("Check the docs here:")
print("https://github.com/Neocky/pluGET")
print("Or go to the official discord.")
print("The link for discord can also be found on Github!")