Skip to content

Commit

Permalink
Added Newznab provider and initialized api framework
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Dlesk committed Dec 29, 2011
1 parent 21512ef commit 4c49628
Show file tree
Hide file tree
Showing 15 changed files with 189 additions and 49 deletions.
Binary file modified Gamez.db
Binary file not shown.
10 changes: 9 additions & 1 deletion Gamez.ini
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,22 @@ server.socket_port = 8085
username = ""
api_key = ""

[Newznab]
api_key = ""
wii_category_id = "1030"
host = ""
port =

[Sabnzbd]
api_key = ""
host = "127.0.0.1"
port = 8081

[Scheduler]
download_interval = 60

[SystemGenerated]
is_to_ignore_update = 0
ignored_version = ""
ignored_version =
api_key = "ikzFRzA1Y8I1UajNJAOQ803TbTYk1vLB64A9SxrAxAw"

12 changes: 9 additions & 3 deletions Gamez.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ def RunWebServer(self,isToDaemonize):

def GenerateSabPostProcessScript():
config = ConfigParser.RawConfigParser()
print(os.path.join(app_path,'Gamez.ini'))
config.read(os.path.join(app_path,'Gamez.ini'))
gamezWebHost = config.get('global','server.socket_host').replace('"','')
gamezWebport = config.get('global','server.socket_port').replace('"','')
Expand Down Expand Up @@ -114,10 +113,17 @@ def RunGameTask():
sabnzbdHost = config.get('Sabnzbd','host').replace('"','')
sabnzbdPort = config.get('Sabnzbd','port').replace('"','')
sabnzbdApi = config.get('Sabnzbd','api_key').replace('"','')
newznabWiiCat = config.get('Newznab','wii_category_id').replace('"','')
newznabApi = config.get('Newznab','api_key').replace('"','')
newznabHost = config.get('Newznab','host').replace('"','')
newznabPort = config.get('Newznab','port').replace('"','')
LogEvent("Searching for games")
lib.GameTasks.GameTasks().FindGames(nzbMatrixUser,nzbMatrixApi,sabnzbdApi,sabnzbdHost,sabnzbdPort)
lib.GameTasks.GameTasks().FindGames(nzbMatrixUser,nzbMatrixApi,sabnzbdApi,sabnzbdHost,sabnzbdPort,newznabWiiCat,newznabApi,newznabHost,newznabPort)
except:
print(sys.exc_info()[0])
errorMessage = "Major error occured when running scheduled tasks"
for message in sys.exc_info():
errorMessage = errorMessage + " - " + str(message)
LogEvent(errorMessage)

if __name__ == '__main__':
app_path = sys.path[0]
Expand Down
28 changes: 28 additions & 0 deletions lib/ConfigFunctions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import ConfigParser
import os
import base64
import hashlib
import random

def CheckConfigForAllKeys(app_path):
changesMade = False
Expand All @@ -26,6 +29,10 @@ def CheckConfigForAllKeys(app_path):
if(config.has_section('SystemGenerated') == False):
config.add_section('SystemGenerated')
changesMade = True

if(config.has_section('Newznab') == False):
config.add_section('Newznab')
changesMade = True

if(config.has_option('global','server.socket_host') == False):
config.set('global','server.socket_host','"127.0.0.1"')
Expand Down Expand Up @@ -67,6 +74,27 @@ def CheckConfigForAllKeys(app_path):
config.set('SystemGenerated','ignored_version','""')
changesMade = True

if(config.has_option('SystemGenerated','api_key') == False):
apiKey = base64.b64encode(hashlib.sha256( str(random.getrandbits(256)) ).digest(), random.choice(['rA','aZ','gQ','hH','hG','aR','DD'])).rstrip('==')
config.set('SystemGenerated','api_key','"' + apiKey + '"')
changesMade = True

if(config.has_option('Newznab','api_key') == False):
config.set('Newznab','api_key','""')
changesMade = True

if(config.has_option('Newznab','wii_category_id') == False):
config.set('Newznab','wii_category_id','"1030"')
changesMade = True

if(config.has_option('Newznab','host') == False):
config.set('Newznab','host','""')
changesMade = True

if(config.has_option('Newznab','port') == False):
config.set('Newznab','port','')
changesMade = True

if(changesMade):
with open(configFilePath,'wb') as configFile:
config.write(configFile)
Binary file modified lib/ConfigFunctions.pyc
Binary file not shown.
Binary file modified lib/Constants.pyc
Binary file not shown.
2 changes: 1 addition & 1 deletion lib/DBFunctions.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ def ValidateDB():
def AddEventToDB(message):
db_path = os.path.join(os.path.abspath(""),"Gamez.db")
createdDate = datetime.datetime.now()
sql = "INSERT INTO gamez_log (message,created_date) values('" + message + "',datetime())"
sql = "INSERT INTO gamez_log (message,created_date) values('" + message.replace("'","''") + "',datetime())"
connection = sqlite3.connect(db_path)
cursor = connection.cursor()
cursor.execute(sql)
Expand Down
Binary file modified lib/DBFunctions.pyc
Binary file not shown.
133 changes: 93 additions & 40 deletions lib/GameTasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,69 +10,122 @@

class GameTasks():

def FindGames(self, nzbmatrixusername, nzbmatrixapi,sabnzbdApi,sabnzbdHost,sabnzbdPort):
def FindGames(self, nzbmatrixusername, nzbmatrixapi,sabnzbdApi,sabnzbdHost,sabnzbdPort,newznabWiiCat,newznabApi,newznabHost,newznabPort):
GameTasks().CheckIfPostProcessExistsInSab(sabnzbdApi,sabnzbdHost,sabnzbdPort)
nzbmatrixusername = nzbmatrixusername.replace('"','')
nzbmatrixapi = nzbmatrixapi.replace('"','')
newznabApi = newznabApi.replace('"','')
newznabWiiCat = newznabWiiCat.replace('"','')
games = GetRequestedGamesAsArray()
for game in games:
try:
game_name = str(game[0])
game_id = str(game[1])
LogEvent("Searching for game: " + game_name)
nzbmatrixResult = GameTasks().FindGameOnNZBMatrix(game_name,game_id,nzbmatrixusername,nzbmatrixapi,sabnzbdApi,sabnzbdHost,sabnzbdPort)
isDownloaded = False

if(nzbmatrixusername <> '' and nzbmatrixapi <> ''):
LogEvent("Checking for game [" + game_name + "] on NZB Matrix")
isDownloaded = GameTasks().FindGameOnNZBMatrix(game_name,game_id,nzbmatrixusername,nzbmatrixapi,sabnzbdApi,sabnzbdHost,sabnzbdPort)

if(newznabWiiCat <> '' and newznabWiiApi <> '' and newznabHost <> '' and newznabPort <> ''):
if(isDownloaded == False):
LogEvent("Checking for game [" + game_name + "] on Newznab")
isDownloaded = FindGameOnNewznabServer(game_name,game_id,sabnzbdApi,sabnzbdHost,sabnzbdPort,newznabWiiCat,newznabApi,newznabHost,newznabPort)
except:
error = sys.exc_info()[0]
print error
continue
return

def FindGameOnNZBMatrix(self,game_name,game_id,username,api,sabnzbdApi,sabnzbdHost,sabnzbdPort):
url = "http://api.nzbmatrix.com/v1.1/search.php?search=" + game_name + "&num=1&cat=44&username=" + username + "&apikey=" + api
opener = urllib.FancyURLopener({})
responseObject = opener.open(url)
response = responseObject.read()
responseObject.close()
responseData = response.split("\n")
fieldData = responseData[0].split(":")
nzbID = fieldData[1]
nzbID = nzbID.replace(";","")
try:
opener = urllib.FancyURLopener({})
responseObject = opener.open(url)
response = responseObject.read()
responseObject.close()
except:
LogEvent("Unable to connect to NZBMatrix Server: " + url)
return False
try:
responseData = response.split("\n")
fieldData = responseData[0].split(":")
nzbID = fieldData[1]
nzbID = nzbID.replace(";","")

if(nzbID <> "nothing_found"):
LogEvent("Game found on NZB Matrix")
GameTasks().AddNZBToSab(nzbID,game_name,sabnzbdApi,sabnzbdHost,sabnzbdPort,game_id)
UpdateStatus(game_id,"Snatched")
return
if(nzbID <> "nothing_found"):
LogEvent("Game found on NZB Matrix")
nzbUrl = "http://api.nzbmatrix.com/v1.1/download.php?id=" + nzbID
result = GameTasks().AddNZBToSab(nzbUrl,game_name,sabnzbdApi,sabnzbdHost,sabnzbdPort,game_id)
if(result):
UpdateStatus(game_id,"Snatched")
return True
return False
except:
LogEvent("Error getting game [" + game_name + "] from NZB Matrix")
return False

def FindGameOnNewznabServer(self,game_name,game_id,sabnzbdApi,sabnzbdHost,sabnzbdPort,newznabWiiCat,newznabApi,newznabHost,newznabPort):
url = "http://" + newznabHost + ":" + newznabPort + "/api?apikey=" + newznabApi + "&t=search&cat=" + newznabWiiCat + "&q=" + game_name + "&o=json"
try:
opener = urllib.FancyURLopener({})
responseObject = opener.open(url)
response = responseObject.read()
responseObject.close()
except:
LogEvent("Unable to connect to Newznab Server: " + url)
return False
try:
jsonObject = json.loads(response)
for item in jsonObject:
nzbID = item["guid"]
nzbUrl = "http://" + newznabHost + ":" + newznabPort + "/api?apikey=" + newznabApi + "&t=get&id=" + nzbID
result = GameTasks().AddNZBToSab(nzbUrl,game_name,sabnzbdApi,sabnzbdHost,sabnzbdPort,game_id)
if(result):
UpdateStatus(game_id,"Snatched")
return True
return False
except:
LogEvent("Error getting game [" + game_name + "] from Newznab")
return False

def AddNZBToSab(self,nzbID,game_name,sabnzbdApi,sabnzbdHost,sabnzbdPort,game_id):
nzbUrl = "http://api.nzbmatrix.com/v1.1/download.php?id=" + nzbID
def AddNZBToSab(self,nzbUrl,game_name,sabnzbdApi,sabnzbdHost,sabnzbdPort,game_id):
url = "http://" + sabnzbdHost + ":" + sabnzbdPort + "/sabnzbd/api?mode=addurl&pp=3&apikey=" + sabnzbdApi + "&script=gamezPostProcess.py&name=" + nzbUrl + "&nzbname=[" + game_id + "] - "+ game_name
responseObject = urllib.FancyURLopener({}).open(url)
responseObject.read()
responseObject.close()
try:
responseObject = urllib.FancyURLopener({}).open(url)
responseObject.read()
responseObject.close()
except:
LogEvent("Unable to connect to Sanzbd: " + url)
return False
LogEvent("NZB added to Sabnzbd")
return
return True

def CheckIfPostProcessExistsInSab(self,sabnzbdApi,sabnzbdHost,sabnzbdPort):

path = os.path.abspath("postprocess")
srcPath = os.path.join(path,"gamezPostProcess.py")
url = "http://" + sabnzbdHost + ":" + sabnzbdPort + "/sabnzbd/api?mode=get_config&apikey=" + sabnzbdApi + "&section=misc&keyword=script_dir"
opener = urllib.FancyURLopener({})
responseObject = opener.open(url)
response = responseObject.read()
responseObject.close()
scriptDir = response.split(":")[2].replace("'","").replace(" ","").replace("{","").replace("}","").replace("\n","")
destPath = os.path.join(scriptDir,"gamezPostProcess.py")

try:
LogEvent("Copying post process script to Sabnzbd scripts folder")
shutil.copyfile(srcPath,destPath)
except:
print 'Error Copying File'
try:
LogEvent("Setting permissions on post process script")
cmd = "chmod +x '" + destPath + "'"
os.system(cmd)
opener = urllib.FancyURLopener({})
responseObject = opener.open(url)
response = responseObject.read()
responseObject.close()
scriptDir = response.split(":")[2].replace("'","").replace(" ","").replace("{","").replace("}","").replace("\n","")
destPath = os.path.join(scriptDir,"gamezPostProcess.py")
try:
LogEvent("Copying post process script to Sabnzbd scripts folder")
shutil.copyfile(srcPath,destPath)
except:
LogEvent("Unable to copy post process script to Sab folder")
return
try:
LogEvent("Setting permissions on post process script")
cmd = "chmod +x '" + destPath + "'"
os.system(cmd)
except:
LogEvent("Unable to set permissions on post process script")
return
except:
print 'Error Setting Permissions'
return
LogEvent("Unable to connect to Sanzbd: " + url)
return
return
Binary file modified lib/GameTasks.pyc
Binary file not shown.
Binary file modified lib/Logger.pyc
Binary file not shown.
Binary file modified lib/UpgradeFunctions.pyc
Binary file not shown.
53 changes: 49 additions & 4 deletions lib/WebRoot.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
import ConfigParser
from time import sleep
import urllib
from xml.dom import minidom
import base64
import hashlib
import random

class WebRoot:
appPath = ''
Expand Down Expand Up @@ -268,7 +272,6 @@ def settings(self):
);
$("button").button().click(function(){
var searchText = document.getElementById("search").value;
//alert(searchText);
document.location.href = "search?term=" + searchText;
});
</script>
Expand All @@ -289,6 +292,9 @@ def settings(self):
<label>Download Interval (In Seconds)</label>
<input type="text" name="downloadInterval" id="downloadInterval" value='""" + config.get('Scheduler','download_interval').replace('"','') + """' />
<label>Gamez API Key</label>
<input type="text" name="gamezApiKey" id="gamezApiKey" value='""" + config.get('SystemGenerated','api_key').replace('"','') + """' />
<h1>SABnzbd+</h1>
<label>SABnzbd+ Host</label>
Expand All @@ -299,6 +305,7 @@ def settings(self):
<label>SABnzbd+ API Key</label>
<input type="text" name="sabApi" id="sabApi" value='""" + config.get('Sabnzbd','api_key').replace('"','') + """' />
<h1>NZB Matrix</h1>
Expand All @@ -308,6 +315,21 @@ def settings(self):
<label>NZB Matrix Username</label>
<input type="text" name="nzbMatrixUsername" id="nzbMatrixUsername" value='""" + config.get('NZBMatrix','username').replace('"','') + """' />
<h1>Newznab</h1>
<label>Newznab Host</label>
<input type="text" name="newznabHost" id="newznabHost" value='""" + config.get('Newznab','host').replace('"','') + """' />
<label>Newznab Port</label>
<input type="text" name="newznabPort" id="newznabPort" value='""" + config.get('Newznab','port').replace('"','') + """' />
<label>Newznab API Key</label>
<input type="text" name="newznabApi" id="newznabApi" value='""" + config.get('Newznab','api_key').replace('"','') + """' />
<label>Newznab Wii Category ID</label>
<input type="text" name="newznabWiiCat" id="newznabWiiCat" value='""" + config.get('Newznab','wii_category_id').replace('"','') + """' />
<button type="submit">Save Settings</button>
<div class="spacer"></div>
Expand Down Expand Up @@ -378,7 +400,6 @@ def log(self,status_message='',version=''):
);
$("button").button().click(function(){
var searchText = document.getElementById("search").value;
//alert(searchText);
document.location.href = "search?term=" + searchText;
});
</script>
Expand Down Expand Up @@ -459,12 +480,16 @@ def upgradetolatestversion(self,verification):
raise cherrypy.InternalRedirect("/?status_message=" + status)

@cherrypy.expose
def savesettings(self,cherrypyHost='', nzbMatrixUsername='', downloadInterval=3600, sabPort='', nzbMatrixApi='', sabApi='', cherrypyPort='', sabHost=''):
def savesettings(self,cherrypyHost='', nzbMatrixUsername='', downloadInterval=3600, sabPort='', nzbMatrixApi='', sabApi='', cherrypyPort='', sabHost='',gamezApiKey='',newznabHost='',newznabPort='',newznabApi='',newznabWiiCat=''):
cherrypyHost = '"' + cherrypyHost + '"'
nzbMatrixUsername = '"' + nzbMatrixUsername + '"'
nzbMatrixApi = '"' + nzbMatrixApi + '"'
sabApi = '"' + sabApi + '"'
sabHost = '"' + sabHost + '"'
gamezApiKey = '"' + gamezApiKey + '"'
newznabHost = '"' + newznabHost + '"'
newznabApi = '"' + newznabApi + '"'
newznabWiiCat = '"' + newznabWiiCat + '"'
config = ConfigParser.RawConfigParser()
configFilePath = os.path.join(WebRoot.appPath,'Gamez.ini')
config.read(configFilePath)
Expand All @@ -476,6 +501,11 @@ def savesettings(self,cherrypyHost='', nzbMatrixUsername='', downloadInterval=36
config.set('Sabnzbd','port',sabPort)
config.set('Sabnzbd','api_key',sabApi)
config.set('Scheduler','download_interval',downloadInterval)
config.set('SystemGenerated','api_key',gamezApiKey)
config.set('Newznab','host',newznabHost)
config.set('Newznab','port',newznabPort)
config.set('Newznab','wii_category_id',newznabWiiCat)
config.set('Newznab','api_key',newznabApi)
with open(configFilePath,'wb') as configFile:
config.write(configFile)
status = "Application Settings Updated Successfully. Gamez is restarting. If after 5 seconds, Gamez isn't working, update the Gamez.ini file and re-launch Gamez"
Expand All @@ -484,4 +514,19 @@ def savesettings(self,cherrypyHost='', nzbMatrixUsername='', downloadInterval=36
@cherrypy.expose
def clearlog(self):
ClearDBLog()
raise cherrypy.InternalRedirect('/')
raise cherrypy.InternalRedirect('/')

@cherrypy.expose
def api(self,api_key=''):
config = ConfigParser.RawConfigParser()
configFilePath = os.path.join(WebRoot.appPath,'Gamez.ini')
config.read(configFilePath)
systemApiKey = config.get('SystemGenerated','api_key').replace('"','')
if(api_key == ''):
return json.dumps({"Error" : "API Key Required"})
elif(api_key <> systemApiKey):
return json.dumps({"Error" : "Invalid API Key"})
else:
response = {"Error" : "API Not Yet Implemented"}
return json.dumps(response)
return json.dumps({"Error" : "Unkown Error"})
Binary file modified lib/WebRoot.pyc
Binary file not shown.
Binary file modified lib/__init__.pyc
Binary file not shown.

0 comments on commit 4c49628

Please sign in to comment.