def AddXbox360GamesIfMissing(): url = "http://www.gamezapp.org/webservice/xbox360" response = '' try: responseObject = urllib.FancyURLopener({}).open(url) response = responseObject.read() responseObject.close() except: LogEvent("Unable to connect to web service: " + url) return json_data = json.loads(response) ClearGames("Xbox360") for data in json_data: game_name = data['GameTitle'] game_type = data['GameType'] game_cover = data['GameCover'] db_path = os.path.join(os.path.abspath(""),"Gamez.db") sql = "SELECT count(ID) from games where game_name = '" + game_name.replace("'","''") + "' AND system='Xbox360'" connection = sqlite3.connect(db_path) cursor = connection.cursor() cursor.execute(sql) result = cursor.fetchall() recordCount = result[0][0] cursor.close() if(str(recordCount) == "0"): LogEvent("Adding XBOX 360 Game [" + game_name.replace("'","''") + "] to Game List") sql = "INSERT INTO games (game_name,game_type,system,cover) values('" + game_name.replace("'","''") + "','" + game_type + "','Xbox360','" + game_cover + "')" cursor = connection.cursor() cursor.execute(sql) connection.commit() cursor.close() return
def SendNotificationToProwl(status,message,prowlApi): prowl = prowlpy.Prowl(prowlApi) try: prowl.add('Gamez',status,message,1,None,"http://www.prowlapp.com/") LogEvent("Prowl Notification Sent") except Exception,msg: LogEvent("Prowl Notification Error: " + msg)
def SendNotificationToNotifo(status,message,notifoUsername,notifoApiKey): notifoDict = {"to":notifoUsername,"msg":message,"label":"Gamez","title":"Gamez Download Alert"} try: notifo = Notifo(notifoUsername,notifoApiKey) LogEvent("Notifo Response: " + notifo.sendNotification(notifoDict)) except Exception,msg: LogEvent("Growl Notification Error: " + msg)
def CheckIfPostProcessExistsInSab(self, sabnzbdApi, sabnzbdHost, sabnzbdPort): path = os.path.abspath("postprocess") srcPath = os.path.join(path, "gamezPostProcess.py") url = urllib.quote("http://" + sabnzbdHost + ":" + sabnzbdPort + "/sabnzbd/api?mode=get_config&apikey=" + sabnzbdApi + "§ion=misc&keyword=script_dir") try: 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: LogEvent("Unable to connect to Sanzbd: " + url) return return
def AddComingSoonGames(): comingSoonWebServiceUrl = "http://www.gamezapp.org/webservice/comingsoon" response = '' try: responseObject = urllib.FancyURLopener({}).open(comingSoonWebServiceUrl) response = responseObject.read() responseObject.close() except: LogEvent("Unable to connect to web service: " + comingSoonWebServiceUrl) return json_data = json.loads(response) ClearComingSoonGames() for data in json_data: game_name = data['GameTitle'] release_date = data['ReleaseDate'] system = data['System'] db_path = os.path.join(os.path.abspath(""),"Gamez.db") sql = "SELECT count(ID) from comingsoon where gametitle = '" + game_name.replace("'","''") + "' AND system='" + system + "'" connection = sqlite3.connect(db_path) cursor = connection.cursor() cursor.execute(sql) result = cursor.fetchall() recordCount = result[0][0] cursor.close() if(str(recordCount) == "0"): LogEvent("Adding " + system + " Game [" + game_name.replace("'","''") + "] to Coming Soon Game List") sql = "INSERT INTO comingsoon (gametitle,releasedate,system) values('" + game_name.replace("'","''") + "','" + release_date + "','" + system + "')" cursor = connection.cursor() cursor.execute(sql) connection.commit() cursor.close() return
def HandleNotifications(status,message,appPath): config = ConfigParser.RawConfigParser() configFilePath = os.path.join(appPath,'Gamez.ini') config.read(configFilePath) prowlApi = config.get('Notifications','prowl_api').replace('"','') growlHost = config.get('Notifications','growl_host').replace('"','') growlPort = config.get('Notifications','growl_port').replace('"','') growlPassword = config.get('Notifications','growl_password').replace('"','') notifoUsername = config.get('Notifications','notifo_username').replace('"','') notifoApi = config.get('Notifications','notifo_apikey').replace('"','') prowlEnabled = config.get('SystemGenerated','prowl_enabled').replace('"','') growlEnabled = config.get('SystemGenerated','growl_enabled').replace('"','') notifoEnabled = config.get('SystemGenerated','notifo_enabled').replace('"','') if(prowlEnabled == "1"): if(prowlApi <> ""): SendNotificationToProwl(status,message,prowlApi) else: LogEvent("Missing Prowl API Key") if(growlEnabled == "1"): if(growlHost <> ""): SendNotificationToGrowl(status,message,growlHost,growlPort,growlPassword) else: LogEvent("Growl Settings Incomplete") if(notifoEnabled == "1"): if(notifoUsername <> "" and notifoApi <> ""): SendNotificationToNotifo(status,message,notifoUsername,notifoApi) else: LogEvent("Notifo Settings Incomplete") return
def DownloadTorrent(self, torrentUrl, title, torrentBlackholePath): try: dest = torrentBlackholePath + title + ".torrent" urllib.urlretrieve(torrentUrl, dest) LogEvent("Torrent Added To Blackhole") except: LogEvent("Unable to download torrent to blackhole: " + url) return False return True
def SendNotificationToGrowl(status,message,growlHost,growlPort,growlPassword): if(growlPort == ""): growlPort = "23053" try: growl = gntp.notifier.GrowlNotifier(applicationName = "Gamez",notifications = ["Gamez Download Alert"],defaultNotifications=["Gamez Download Alert"],hostname=growlHost,port=growlPort,password=growlPassword) growl.register() growl.notify(noteType="Gamez Download Alert",title=message,description=message,sticky=False,priority=1,) LogEvent("Growl Notification Sent") except Exception,msg: LogEvent("Growl Notification Error: " + msg)
def AddNZBToBlackhole(self, nzbUrl, nzbBlackholePath, game_name, system): try: dest = nzbBlackholePath + game_name + " - " + system + ".nzb" LogEvent(nzbUrl) urllib.urlretrieve(nzbUrl, dest) LogEvent("NZB Added To Blackhole") except: LogEvent("Unable to download NZB to blackhole: " + url) return False return True
def AddNZBToSab(self, nzbUrl, game_name, sabnzbdApi, sabnzbdHost, sabnzbdPort, game_id, sabnzbdCategory): nzbUrl = urllib.quote(nzbUrl) url = "http://" + sabnzbdHost + ":" + sabnzbdPort + "/sabnzbd/api?mode=addurl&pp=3&apikey=" + sabnzbdApi + "&script=gamezPostProcess.py&name=" + nzbUrl + "&nzbname=[" + game_id + "] - " + game_name if (sabnzbdCategory <> ''): url = url + "&cat=" + sabnzbdCategory 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 True
def UpdateStatus(game_id,status): LogEvent("Update status of game to " + status) db_path = os.path.join(os.path.abspath(""),"Gamez.db") game_name = "" system = "" sql = "select game_name,system from requested_games where ID='" + game_id + "'" connection = sqlite3.connect(db_path) cursor = connection.cursor() cursor.execute(sql) result = cursor.fetchall() tables = list() for record in result: game_name = str(record[0]) system = str(record[1]) cursor.close() sql = "update requested_games set status='" + status + "' where game_name = '" + game_name.replace("'","''") + "' and system = '" + system + "'" connection = sqlite3.connect(db_path) cursor = connection.cursor() cursor.execute(sql) connection.commit() cursor.close() message = "Gamez Notification: " + system + " Game: " + game_name + " has been " + status appPath = os.path.abspath("") Notifications.HandleNotifications(status,message,appPath) return
def UpdateToLatestVersion(app_path): LogEvent("Updating to latest version") filesToIgnore = ["Gamez.ini","Gamez.db"] filesToIgnoreSet = set(filesToIgnore) updatePath = os.path.join(app_path,"update") if not os.path.exists(updatePath): os.makedirs(updatePath) latestVersion = GetLatestVersion() tagUrl = "https://github.com/mdlesk/Gamez/tarball/v" + latestVersion LogEvent("Downloading from GitHub") data = urllib2.urlopen(tagUrl) downloadPath = os.path.join(app_path,data.geturl().split('/')[-1]) downloadedFile = open(downloadPath,'wb') downloadedFile.write(data.read()) downloadedFile.close() LogEvent("Extracting files") tarredFile = tarfile.open(downloadPath) tarredFile.extractall(updatePath) tarredFile.close() os.remove(downloadPath) LogEvent("Upgrading files") contentsDir = [x for x in os.listdir(updatePath) if os.path.isdir(os.path.join(updatePath, x))] updatedFilesPath = os.path.join(updatePath,contentsDir[0]) for dirname, dirnames, filenames in os.walk(updatedFilesPath): dirname = dirname[len(updatedFilesPath)+1:] for file in filenames: src = os.path.join(updatedFilesPath,dirname,file) dest = os.path.join(app_path,dirname,file) if((file in filesToIgnoreSet) == True): continue if(os.path.isfile(dest)): os.remove(dest) os.renames(src,dest) shutil.rmtree(updatePath) config = ConfigParser.RawConfigParser() configFilePath = os.path.join(app_path,'Gamez.ini') config.read(configFilePath) if(config.has_section('SystemGenerated') == False): config.add_section('SystemGenerated') config.set('SystemGenerated','is_to_ignore_update','0') config.set('SystemGenerated','ignored_version','"versionToIgnore"') with open(configFilePath,'wb') as configFile: config.write(configFile) LogEvent("Upgrading complete") return "Successfully Upgraded to Version " + latestVersion
def FindGameOnNZBMatrix(self, game_name, game_id, username, api, sabnzbdApi, sabnzbdHost, sabnzbdPort, system, sabnzbdCategory, isSabEnabled, isNzbBlackholeEnabled, nzbBlackholePath): catToUse = "" if (system == "Wii"): catToUse = "44" elif (system == "Xbox360"): catToUse = "14" else: LogEvent("Unrecognized System") return False url = "http://api.nzbmatrix.com/v1.1/search.php?search=" + game_name + "&num=1&catid=" + catToUse + "&username="******"&apikey=" + api 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" and nzbID <> "API_RATE_LIMIT_REACHED"): LogEvent("Game found on NZB Matrix") nzbUrl = "http://api.nzbmatrix.com/v1.1/download.php?id=" + nzbID + "&username="******"&apikey=" + api result = GameTasks().DownloadNZB(nzbUrl, game_name, sabnzbdApi, sabnzbdHost, sabnzbdPort, game_id, sabnzbdCategory, isSabEnabled, isNzbBlackholeEnabled, nzbBlackholePath, system) if (result): UpdateStatus(game_id, "Snatched") return True return False except: LogEvent("Error getting game [" + game_name + "] from NZB Matrix") return False
def RemoveGameFromDb(db_id): LogEvent("Removing game") db_path = os.path.join(os.path.abspath(""),"Gamez.db") sql = "delete from requested_games where ID='" + db_id + "'" connection = sqlite3.connect(db_path) cursor = connection.cursor() cursor.execute(sql) connection.commit() cursor.close() return
def FindGameOnNewznabServer(self, game_name, game_id, sabnzbdApi, sabnzbdHost, sabnzbdPort, newznabWiiCat, newznabApi, newznabHost, newznabPort, system, newznabXbox360Cat, sabnzbdCategory, isSabEnabled, isNzbBlackholeEnabled, nzbBlackholePath): if (system == "Wii"): catToUse = newznabWiiCat elif (system == "Xbox360"): catToUse = newznabXbox360Cat else: LogEvent("Unrecognized System") return False url = "http://" + newznabHost + ":" + newznabPort + "/api?apikey=" + newznabApi + "&t=search&cat=" + catToUse + "&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: if (response == "[]"): return False jsonObject = json.loads(response) for item in jsonObject: nzbID = item["guid"] LogEvent("Game found on Newznab") nzbUrl = "http://" + newznabHost + ":" + newznabPort + "/api?apikey=" + newznabApi + "&t=get&id=" + nzbID result = GameTasks().DownloadNZB(nzbUrl, game_name, sabnzbdApi, sabnzbdHost, sabnzbdPort, game_id, sabnzbdCategory, isSabEnabled, isNzbBlackholeEnabled, nzbBlackholePath, system) if (result): UpdateStatus(game_id, "Snatched") return True return False except: LogEvent("Error getting game [" + game_name + "] from Newznab") return False
def IgnoreVersion(app_path): LogEvent("Ignoring Version") versionToIgnore = GetLatestVersion() config = ConfigParser.RawConfigParser() configFilePath = os.path.join(app_path,'Gamez.ini') config.read(configFilePath) if(config.has_section('SystemGenerated') == False): config.add_section('SystemGenerated') config.set('SystemGenerated','is_to_ignore_update','1') config.set('SystemGenerated','ignored_version','"' + versionToIgnore + '"') with open(configFilePath,'wb') as configFile: config.write(configFile)
def CheckSabDownloadPath(self, sabnzbdApi, sabnzbdHost, sabnzbdPort): url = "http://" + sabnzbdHost + ":" + sabnzbdPort + "/sabnzbd/api?mode=get_config&apikey=" + sabnzbdApi + "§ion=misc&keyword=complete_dir" try: opener = urllib.FancyURLopener({}) responseObject = opener.open(url) response = responseObject.read() responseObject.close() completedDir = response.split(":")[2].replace("'", "").replace( " ", "").replace("{", "").replace("}", "").replace("\n", "") return completedDir except: LogEvent("Unable to get Sab Download Complete Directory") return "" return
def CheckForNewVersion(app_path): LogEvent("Checking to see if a new version is available") newVersionAvailable = False currentVersion = VersionNumber() mostRecentVersion = GetLatestVersion() config = ConfigParser.RawConfigParser() config.read(os.path.join(app_path,'Gamez.ini')) isToDeferUpgrade = config.get('SystemGenerated','is_to_ignore_update').replace('"','') ignoredVersion = config.get('SystemGenerated','ignored_version').replace('"','') if(LooseVersion(mostRecentVersion) > LooseVersion(currentVersion)): if(isToDeferUpgrade == '0'): newVersionAvailable = True if(isToDeferUpgrade == '1'): if(LooseVersion(mostRecentVersion) > LooseVersion(ignoredVersion)): newVersionAvailable = True return newVersionAvailable
def DownloadNZB(self, nzbUrl, game_name, sabnzbdApi, sabnzbdHost, sabnzbdPort, game_id, sabnzbdCategory, isSabEnabled, isNzbBlackholeEnabled, nzbBlackholePath, system): try: result = False if (isSabEnabled == "1"): result = GameTasks().AddNZBToSab(nzbUrl, game_name, sabnzbdApi, sabnzbdHost, sabnzbdPort, game_id, sabnzbdCategory) if (isNzbBlackholeEnabled == "1"): result = GameTasks().AddNZBToBlackhole(nzbUrl, nzbBlackholePath, game_name, system) return result except: LogEvent("Unable to download NZB: " + url) return False
def GetLatestVersion(): LogEvent("Retrieving the latest version") mostRecentVersion = '0.0.0.0' url = 'https://api.github.com/repos/mdlesk/Gamez/tags' opener = urllib.FancyURLopener({}) responseObject = opener.open(url) response = responseObject.read() responseObject.close() jsonObject = json.loads(response) for val in jsonObject: name = val['name'] tagVersion = name.replace("v","").replace("'","") tagVersion = str(tagVersion) try: if(LooseVersion(tagVersion) > LooseVersion(mostRecentVersion)): mostRecentVersion = tagVersion except: continue return mostRecentVersion
def AddGameToDb(db_id,status): LogEvent("Adding game in 'Wanted' status") db_path = os.path.join(os.path.abspath(""),"Gamez.db") sql = "select game_name,system,game_type,cover from games where ID = '" + db_id + "'" connection = sqlite3.connect(db_path) cursor = connection.cursor() cursor.execute(sql) result = cursor.fetchall()[0] game_name = str(result[0]) system = str(result[1]) game_type = str(result[2]) cover = str(result[3]) cursor.close() sql = "insert into requested_games(GAME_NAME,SYSTEM,GAME_TYPE,status,cover) values('" + game_name.replace("'","''") + "','" + system + "','" + game_type + "','" + status + "','" + cover + "')" connection = sqlite3.connect(db_path) cursor = connection.cursor() cursor.execute(sql) connection.commit() cursor.close() return
def FindGameOnKAT(self, game_id, game_name, system, torrentBlackholePath): url = "http://www.kickasstorrents.com/json.php?q=" + game_name try: opener = urllib.FancyURLopener({}) responseObject = opener.open(url) response = responseObject.read() responseObject.close() jsonObject = json.loads(response) listObject = jsonObject['list'] for record in listObject: title = record['title'] torrentLink = record['torrentLink'] category = record['category'] print category if (category == "Games"): result = GameTasks().DownloadTorrent( torrentLink, title, torrentBlackholePath) if (result == True): UpdateStatus(game_id, "Snatched") return result except: LogEvent("Unable to connect to KickAss Torrents") return
def FindGames(self, manualSearchGame, nzbmatrixusername, nzbmatrixapi, sabnzbdApi, sabnzbdHost, sabnzbdPort, newznabWiiCat, newznabApi, newznabHost, newznabPort, newznabXbox360Cat, sabnzbdCategory, isSabEnabled, isNzbMatrixEnabled, isNewznabEnabled, isNzbBlackholeEnabled, nzbBlackholePath, isTorrentBlackholeEnabled, isTorrentKATEnabled, torrentBlackholePath): if (isSabEnabled == "1"): GameTasks().CheckIfPostProcessExistsInSab(sabnzbdApi, sabnzbdHost, sabnzbdPort) nzbmatrixusername = nzbmatrixusername.replace('"', '') nzbmatrixapi = nzbmatrixapi.replace('"', '') newznabApi = newznabApi.replace('"', '') newznabWiiCat = newznabWiiCat.replace('"', '') games = GetRequestedGamesAsArray(manualSearchGame) for game in games: try: game_name = str(game[0]) game_id = str(game[1]) system = str(game[2]) LogEvent("Searching for game: " + game_name) isDownloaded = False if (isNzbMatrixEnabled == "1"): if (nzbmatrixusername <> '' and nzbmatrixapi <> ''): if (isDownloaded == False): LogEvent("Checking for game [" + game_name + "] on NZB Matrix") isDownloaded = GameTasks().FindGameOnNZBMatrix( game_name, game_id, nzbmatrixusername, nzbmatrixapi, sabnzbdApi, sabnzbdHost, sabnzbdPort, system, sabnzbdCategory, isSabEnabled, isNzbBlackholeEnabled, nzbBlackholePath) else: LogEvent("NZB Matrix Settings Incomplete.") if (isNewznabEnabled == "1"): if (newznabWiiCat <> '' and newznabXbox360Cat <> '' and newznabApi <> '' and newznabHost <> '' and newznabPort <> ''): if (isDownloaded == False): LogEvent("Checking for game [" + game_name + "] on Newznab") isDownloaded = GameTasks().FindGameOnNewznabServer( game_name, game_id, sabnzbdApi, sabnzbdHost, sabnzbdPort, newznabWiiCat, newznabApi, newznabHost, newznabPort, system, newznabXbox360Cat, sabnzbdCategory, isSabEnabled, isNzbBlackholeEnabled, nzbBlackholePath) else: LogEvent("NZB Matrix Settings Incomplete.") if (isTorrentBlackholeEnabled == "1"): if (isTorrentKATEnabled == "1"): if (isDownloaded == False): LogEvent("Checking for game [" + game_name + "] on KickAss Torrents") isDownloaded = GameTasks().FindGameOnKAT( game_id, game_name, system, torrentBlackholePath) except: continue return