Recent Posts
C++ | 4 sec ago
None | 15 sec ago
Lua | 23 sec ago
None | 28 sec ago
None | 28 sec ago
None | 49 sec ago
None | 51 sec ago
None | 1 min ago
PHP | 1 min ago
None | 1 min ago
Sitereport
Find cool info about any domain on the internet?
visit sitereport
Free Subdomains
Want a pastebin.com sub-domain for your community?
learn more...
What is pastebin?
Pastebin is a website that hosts all your text & code on dedicated servers for easy sharing.
learn more...
Learn a little bit about the new Pastebin.com on our help page. hide message
By binhex on the 22nd of Apr 2009 08:47:17 AM Download | Raw | Embed | Report
  1. #automated nzb downloader based on gamespot ratings using rss feed and api from newzbin.com
  2. #this script is designed to download game nzb files from newzbin.com (requires registration and payment)
  3. #created by binhex
  4. #ver 1.0
  5.  
  6. #problems/features
  7.  
  8. import urllib
  9. import httplib
  10. import xml.dom.minidom
  11. import re
  12. import time
  13. import os
  14. import traceback
  15. import logging
  16. import socket
  17. import fileinput
  18. import subprocess
  19.  
  20. #put your own folder names below as specified in sabnzbd+
  21. watch_dir="H:\\Downloads\\Usenet\\SABnzbd\\Watched\\"
  22. nzb_dir="H:\\Downloads\\Usenet\\SABnzbd\\NZBs\\"
  23. completed_dir="H:\\Downloads\\Usenet\\SABnzbd\\Completed\\"
  24.  
  25. #put your own folder and filenames below to specify location of log files
  26. mainlog="F:\\Scripts\\Logs\\Errors\\newzbin_autodl_games_main.log"
  27. tracelog="F:\\Scripts\\Logs\\Errors\\newzbin_autodl_games_traceback.log"
  28. cachelog="F:\\Scripts\\Logs\\Output\\newzbin_autodl_games_cache" + time.strftime("_%m%y") + ".log"
  29.  
  30. #put your own notification message process below for error logging
  31. notifylog="cmd /c msg console /TIME:43200 Newzbin Games Script Error, Check Logs"
  32.  
  33. #send failure messages to log file
  34. main_logger = logging.getLogger('myapp1')
  35. main_handler = logging.FileHandler(mainlog)
  36. main_formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
  37. main_handler.setFormatter(main_formatter)
  38. main_logger.addHandler(main_handler)
  39. main_logger.setLevel(logging.INFO)
  40.  
  41. #sets timeout period for urlretrieve (in seconds)
  42. socket.setdefaulttimeout(240)
  43.  
  44. #newzbin account details
  45. newzbin_username="yourusername"
  46. newzbin_password="yourpassword"
  47.  
  48. #newzbin rss feed for "Saved Searches"
  49. newzbin_com_feed="https://www.newzbin.com/search/therestofyourrssfeed"
  50.  
  51. #define platform search for gamerankings
  52. #gamerankings_platform="site=pc"         #pc platform
  53. gamerankings_platform="site=xbox360"    #xbox360 platform
  54. #gamerankings_platform="site=wii"        #wii platform
  55. #gamerankings_platform="site=ds"         #ds platform
  56.  
  57. #define release time period search for gamerankings
  58. gamerankings_released="&year=0"         #anytime release
  59. #gamerankings_released="&year=1"         #in the past release
  60. #gamerankings_released="&year=2"         #last month release
  61. #gamerankings_released="&year=3"         #last 3 months release
  62. #gamerankings_released="&year=4"         #last 6 months release
  63. #gamerankings_released="&year=5"         #last year release
  64.  
  65. #define minimum number of reviews search for gamerankings
  66. #gamerankings_reviews="&numrev=0"         #0+ reviews
  67. #gamerankings_reviews="&numrev=1"         #1+ reviews
  68. #gamerankings_reviews="&numrev=2"         #5+ reviews
  69. gamerankings_reviews="&numrev=3"         #10+ reviews
  70. #gamerankings_reviews="&numrev=4"         #20+ reviews
  71.  
  72. #gamerankings search page
  73. gamerankings_search_url="http://www.gamerankings.com/browse.html?" + gamerankings_platform + "&cat=0" + gamerankings_released + gamerankings_reviews + "&sort=0&letter=&search="
  74.  
  75.  
  76.  
  77. #check for internet connectivity
  78. pingtest = "ping www.google.co.uk"
  79. process = subprocess.Popen(pingtest, shell=True, stdout=subprocess.PIPE)
  80. process.wait()
  81.  
  82. if process.returncode == 0:
  83.  
  84.         ##############
  85.         # os filters #
  86.         ##############
  87.  
  88.         try:
  89.                 def isInWatched(check_watched_folder):
  90.                
  91.                         #this is set to download only if the nzb file doesn't exist in the watch folder (watch_dir)
  92.                         if os.path.exists(watch_dir + check_watched_folder + ".nzb"):
  93.                        
  94.                                 return 0
  95.                         else:
  96.                                 return 1
  97.                
  98.                 def isInNZB(check_nzb_folder):
  99.                
  100.                         #this is set to download only if the nzb file doesn't exist in the nzb folder (nzb_dir)
  101.                         if os.path.exists(nzb_dir + check_nzb_folder + ".nzb.gz"):
  102.                                  
  103.                                 return 0
  104.                         else:
  105.                                 return 1
  106.                
  107.                 def isCompleted(check_completed_folder):
  108.                
  109.                         #this is set to download only if the game doesn't exist in the completed folder (completed_dir)
  110.                         if os.path.exists(completed_dir + check_completed_folder):
  111.                          
  112.                                 return 0
  113.                         else:
  114.                                 return 1
  115.  
  116.         except:
  117.                 print("Error: OS Filter Error")
  118.                 main_logger.error("OS Filter Error")
  119.                 traceback.print_exc(file=open(tracelog,"a"))
  120.                 os.system(notifylog)
  121.  
  122.         ########################
  123.         # gamerankings filters #
  124.         ########################
  125.  
  126.         try:
  127.                 def isGoodRatings(check_ratings):
  128.                
  129.                         #this is set to download games with a min rating 85% (gamerankings)
  130.                         if re.compile("<b>8[5-9]\.[0-9][0-9]\%</b>|<b>9[0-9]\.[0-9][0-9]\%</b>").search(check_ratings):
  131.                        
  132.                                 return 1
  133.                         else:
  134.                                 return 0
  135.                                        
  136.                 def isGoodTitle(check_title):
  137.  
  138.                         #this is set to ignore gamerankings filters for games with certain titles
  139.                         if re.compile("Good Game", re.IGNORECASE).search(check_title):
  140.                          
  141.                                 return 1
  142.                         else:
  143.                                 return 0
  144.  
  145.                 def isGoodMatch(check_match):
  146.  
  147.                         #this is set to check that release title and gamerankings search result match
  148.                         gamerankings_search_result_title = re.compile("/xbox360/[0-9]+.*\>.*\</a\>").search(check_match)
  149.  
  150.                         if gamerankings_search_result_title is not None:
  151.                                
  152.                                 if re.search(newzbin_game_title + "\</a\>", gamerankings_search_result_title.group()):
  153.  
  154.                                         return 1
  155.                                 else:
  156.                                         return 0
  157.  
  158.                 def isBadSearch(check_search):
  159.  
  160.                         #this is set to search for no title match found on gamerankings
  161.                         if re.compile("No results were found for your search", re.IGNORECASE).search(check_search):
  162.                          
  163.                                 return 0
  164.                         else:
  165.                                 return 1
  166.                                                
  167.         except:
  168.                 print("Error: Gamerankings Filter Error")
  169.                 main_logger.error("Gamerankings Filter Error")
  170.                 traceback.print_exc(file=open(tracelog,"a"))
  171.                 os.system(notifylog)
  172.  
  173.         try:      
  174.                 def download(download_nzb):
  175.  
  176.                         print("------------------------------")
  177.                         print("Status: Downloading Game.....")
  178.                         print("Release Game Title: " + newzbin_game_title)
  179.                         print("NZB Filename: " + newzbin_game_title_strip)
  180.                         print("")
  181.  
  182.                         #the following code uses the newzbin api
  183.                         headers = {
  184.                            'User-Agent': 'grabnzb.py',
  185.                         }
  186.                         conn = httplib.HTTPSConnection('v3.newzbin.com')
  187.                         postdata = { 'username': newzbin_username, 'password': newzbin_password, 'reportid': report_id }
  188.                         postdata = urllib.urlencode(postdata)
  189.                         headers['Content-type'] = 'application/x-www-form-urlencoded'
  190.                         fetchurl = '/api/dnzb/'
  191.                         conn.request('POST', fetchurl, postdata, headers)
  192.                         response = conn.getresponse()
  193.                         rcode = response.getheader('X-DNZB-RCode')
  194.  
  195.                         if re.compile("200", re.IGNORECASE).search(rcode):
  196.                                 print("Debug: (Newzbin API) OK, NZB content follows")
  197.                                
  198.                                 data = response.read()
  199.  
  200.                                 #save response to nzb file
  201.                                 nzbfile=file(watch_dir + newzbin_game_title_strip + ".nzb","a")
  202.                                 nzbfile.write(data + "\n")
  203.                                 nzbfile.close()
  204.  
  205.                         elif re.compile("400", re.IGNORECASE).search(rcode):
  206.                                 print("Debug: (Newzbin API) Bad Request, please supply all parameters")
  207.  
  208.                         elif re.compile("401", re.IGNORECASE).search(rcode):
  209.                                 print("Debug: (Newzbin API) Unauthorised, check username/password?")
  210.                                
  211.                         elif re.compile("402", re.IGNORECASE).search(rcode):
  212.                                 print("Debug: (Newzbin API) Payment Required, not Premium")
  213.                                
  214.                         elif re.compile("404", re.IGNORECASE).search(rcode):
  215.                                 print("Debug: (Newzbin API) Not Found, data doesn't exist? ")
  216.                                                        
  217.                         elif re.compile("450", re.IGNORECASE).search(rcode):
  218.                                 print("Debug: (Newzbin API) Try Later, wait 60 seconds for counter to reset")
  219.                                 time.sleep(60)
  220.                                 conn.request('POST', fetchurl, postdata, headers)
  221.                                 response = conn.getresponse()
  222.                                 data = response.read()
  223.  
  224.                                 #save response to nzb file
  225.                                 nzbfile=file(watch_dir + newzbin_game_title_strip + ".nzb","a")
  226.                                 nzbfile.write(data + "\n")
  227.                                 nzbfile.close()
  228.  
  229.                         elif re.compile("500", re.IGNORECASE).search(rcode):
  230.                                 print("Debug: (Newzbin API) Internal Server Error, please report to Administrator")
  231.  
  232.                         elif re.compile("503", re.IGNORECASE).search(rcode):
  233.                                 print("Debug: (Newzbin API) Service Unavailable, site is currently down")
  234.  
  235.                         #read response back from newzbin (debug)
  236.                         #rcode = response.getheader('X-DNZB-RCode')
  237.                         #print("Debug: Newzbin API Return Code: " + rcode)
  238.                         #rtext = response.getheader('X-DNZB-RText')
  239.                         #print("Debug: Newzbin API Resturn Code Text: " + rtext)
  240.                         #report_name = response.getheader('X-DNZB-Name')
  241.                         #print("Debug: Newzbin API Returned Report: " + report_name)
  242.                         #report_cat  = response.getheader('X-DNZB-Category')
  243.                         #print("Debug: Newzbin API Returned Category: " + report_cat)                      
  244.                         #report_extlink  = response.getheader('X-DNZB-MoreInfo')
  245.                         #print("Debug: Newzbin API Returned External Link: " + report_extlink)              
  246.                        
  247.         except:
  248.                 print("Error: Download Of NZB Failed")
  249.                 main_logger.error("Download Of Game " + newzbin_game_title_strip + " Failed")
  250.                 traceback.print_exc(file=open(tracelog,"a"))
  251.                 os.system(notifylog)
  252.  
  253.                 #this retries the deletion of partial nzb downloads
  254.                 removeRetryCount = 0
  255.                 while removeRetryCount < 5:
  256.                                
  257.                         #sleep and retry to delete partial nzb download 5 times with 30 sec gap
  258.                         try:
  259.                                 os.remove(watch_dir + newzbin_game_title_strip + ".nzb")
  260.                                 break
  261.                         except:
  262.                                 removeRetryCount += 1
  263.                                 time.sleep(30)
  264.                 else:
  265.                         print("Error: Deletion Of Partial NZB Failed")
  266.                         main_logger.error("Deletion Of NZB " + newzbin_game_title_strip + " Failed")
  267.                         traceback.print_exc(file=open(tracelog,"a"))
  268.                         os.system(notifylog)
  269.                  
  270.         #this reads the content of the rss feed from newzbin.com
  271.         rssfeedRetryCount = 0
  272.         while rssfeedRetryCount < 5:
  273.                        
  274.                 #sleep and retry to read the content of the rss feed from newzbin.com 5 times with 2 min gap
  275.                 try:
  276.                         dom=xml.dom.minidom.parse(urllib.urlopen(newzbin_com_feed))
  277.                         break
  278.                 except:
  279.                         rssfeedRetryCount += 1
  280.                         time.sleep(120)
  281.         else:
  282.                 print("Error: RSS Feed Error")
  283.                 main_logger.error("RSS Feed Error")
  284.                 traceback.print_exc(file=open(tracelog,"a"))
  285.                 os.system(notifylog)
  286.  
  287.         #this breaks down the rss feed page into tag sections
  288.         for node in dom.getElementsByTagName("item"):
  289.              
  290.                 newzbin_game_title = node.getElementsByTagName("title")[0].childNodes[0].data
  291.  
  292.                 #remove unwanted characters from newzbin title
  293.                 newzbin_game_title = re.sub("\(.*\)+$|\[.*\]$","" ,newzbin_game_title)
  294.                 newzbin_game_title = re.sub("\s+$","" ,newzbin_game_title)
  295.                 newzbin_game_title = re.sub("40K","40,000" ,newzbin_game_title)
  296.  
  297.                 #remove/replace illegal characters from newzbin title (used for nzb filename)
  298.                 newzbin_game_title_strip = re.sub("\:","" ,newzbin_game_title)
  299.                 newzbin_game_title_strip = re.sub("\*","" ,newzbin_game_title_strip)
  300.                 newzbin_game_title_strip = re.sub("\"","" ,newzbin_game_title_strip)
  301.                 newzbin_game_title_strip = re.sub("/"," " ,newzbin_game_title_strip)
  302.                 newzbin_game_title_strip = re.sub("\\\\"," " ,newzbin_game_title_strip)
  303.                 newzbin_game_title_strip = re.sub("\?","" ,newzbin_game_title_strip)
  304.                 newzbin_game_title_strip = re.sub("\|","" ,newzbin_game_title_strip)
  305.                 newzbin_game_title_strip = re.sub("\<","" ,newzbin_game_title_strip)
  306.                 newzbin_game_title_strip = re.sub("\>","" ,newzbin_game_title_strip)
  307.  
  308.                 #replaces spaces with + used for searching gamerankings
  309.                 gamerankings_search_title = re.sub(" ","+" ,newzbin_game_title)
  310.  
  311.                 #create cache of game titles and check cachefile, skip if match found
  312.                 cachefile=file(cachelog, "a")
  313.                 cachefile.close()
  314.                 cachefile=file(cachelog,"r")
  315.                 cacheread=cachefile.readlines()
  316.                 cachefile.close()
  317.                
  318.                 if newzbin_game_title_strip + "\n" not in cacheread:
  319.  
  320.                         #write game title to cachelog
  321.                         cachefile=file(cachelog,"a")
  322.                         cachefile.write(newzbin_game_title_strip + "\n")
  323.                         cachefile.close()
  324.  
  325.                         gamerankings_search_result = gamerankings_search_url + gamerankings_search_title
  326.                                        
  327.                         try:
  328.                                 sock = urllib.urlopen(gamerankings_search_result)
  329.                                 gamerankings_search_result_page = sock.read()                    
  330.                                 sock.close()
  331.                                
  332.                         except:
  333.                                 print("Error: RSS Feed Tag Error")
  334.                                 main_logger.error("RSS Feed Tag Error")
  335.                                 traceback.print_exc(file=open(tracelog,"a"))
  336.                                 os.system(notifylog)
  337.  
  338.                         try:
  339.                                 #######################
  340.                                 # check filter values #
  341.                                 #######################
  342.  
  343.                                 if (isInWatched(newzbin_game_title_strip) == 1):
  344.  
  345.                                         VisInWatched = 1
  346.                                 else:
  347.                                         VisInWatched = 0
  348.  
  349.                                 if ((isInWatched(newzbin_game_title_strip) == 1) and (isInNZB(newzbin_game_title_strip) == 1) and (isCompleted(newzbin_game_title_strip) == 1) and (isGoodMatch(gamerankings_search_result_page) == 1) and (isBadSearch(gamerankings_search_result_page) == 1)) and ((isGoodRatings(gamerankings_search_result_page) == 1) or (isGoodTitle(newzbin_game_title_strip) == 1)):
  350.  
  351.                                         report_id = node.getElementsByTagName("report:id")[0].childNodes[0].data
  352.                                        
  353.                                         download(report_id)
  354.  
  355.                                 else:
  356.                                         print("---------------------------")
  357.                                         print("Status: Skipping Game.....")
  358.                                         print("Release Game Title: " + newzbin_game_title)
  359.                                         print("NZB Filename: " + newzbin_game_title_strip)
  360.                                         print("")
  361.                                        
  362.                         except:
  363.                                 print("Error: Filter Value Check Error")
  364.                                 main_logger.error("Filter Value Check Error")
  365.                                 traceback.print_exc(file=open(tracelog,"a"))
  366.                                 os.system(notifylog)
  367.  
  368.                         #############
  369.                         # Debugging #
  370.                         #############
  371.                        
  372.                         #file system checks
  373.                         if (isCompleted(newzbin_game_title_strip) == 0):
  374.                                 print("Debug: (File System Check) Game Exists In Completed Folder")
  375.  
  376.                         if (VisInWatched == 0):
  377.                                 print("Debug: (File System Check) NZB Exists In Watch Folder")
  378.                                
  379.                         if (isInNZB(newzbin_game_title_strip) == 0):
  380.                                 print("Debug: (File System Check) NZB Exists In NZB Folder")
  381.  
  382.                         #gamerankings website checks
  383.                         if (isBadSearch(gamerankings_search_result_page) == 0):
  384.                                 print("Debug: (Gamerankings Website Check) No Results For Game Title")
  385.  
  386.                         elif (isGoodMatch(gamerankings_search_result_page) == 0):
  387.                                 print("Debug: (Gamerankings Website Check) Search Result NOT Equal To Release Title")
  388.  
  389.                         elif (isGoodTitle(newzbin_game_title_strip) == 1):
  390.                                 print("Debug: (Gamerankings Website Check) Title Is In Exempt List")
  391.  
  392.                         elif (isGoodRatings(gamerankings_search_result_page) == 0):
  393.                                 print("Debug: (Gamerankings Website Check) Rating Below Threshold")
  394.  
  395. else:
  396.         print("ping failed")
Submit a correction or amendment below. Make A New Post
To highlight particular lines, prefix each line with @h@
Syntax highlighting:
Post expiration:
Post exposure:
Name / Title:
Email: