bhdupload/bhdgaps.py
pwgen 8d1f836ce2 Add 'bhdgaps.py'
Initial hack file to find all missing "info" on the site
2021-04-14 08:30:52 +00:00

147 lines
4.4 KiB
Python

#!/usr/bin/env python
import argparse
import guessit
import requests
import os
import sys
import tempfile
from dotenv import load_dotenv
def absoluteFilePaths(directory):
""" Get full file paths within a specific directory
Keyword arguments:
directory -- directory path containing files
"""
files = []
for dirpath, _, filenames in os.walk(directory):
for f in sorted(filenames):
files.append(os.path.abspath(os.path.join(dirpath, f)))
return files
def readFiles(files, key='image[]'):
""" Open files for Requests payload
Keyword arguments:
files -- list of files (full paths)
key -- Requests payload form field name
"""
result = []
for f in files:
result.append((key, (os.path.basename(f), open(f, 'rb'))))
return result
def getArgs():
""" Get command-line arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument('input', action='store', type=str, help='Input file')
parser.add_argument('-a', dest='anon', action='store_true', help='Set an Anonymous upload')
return parser.parse_args()
def find_gaps(name, _source, _reso=""):
'''
payload = {'name': name,
'description': BBCODE,
'category_id': category,
'type': reso,
'source': source,
'imdb_id': imdbid,
'tmdb_id': tmdbid,
'pack': pack,
'live': live,
'anon': anon}
'''
torrent_name = str(name)
source = str(_source)
reso = str(_reso)
action = ""
print(f"Searching for {torrent_name} - {source} - {reso}...")
# first search on name
r = SESS.post(BHD_SEARCH, data={
'action': 'search',
'search': torrent_name,
'source': source,
'types': reso})
try:
if r.status_code == 200:
_json = r.json()
if _json['total_results'] >= 1:
action = False
print(f"Found {_json['total_results']} matching our criteria...")
# BUG - sets the last item ...
for result in _json['results']:
if result['seeders'] < 1:
print(f"{result['name']} - Could be dead")
action = True
elif result['seeders'] >= 1 and result['seeders'] <= 3:
print(f"{result['name']} - Needs saving, not uploading")
action = False
else:
# No torrents match our Source & Resolution, We can upload safely!
print(f"Couldn't find torrents matching: {torrent_name}.{source}.{reso}")
action = True
return action
except Exception as e:
print(f"Error finding torrent information: {e}")
print(f"{_json}")
return False
# MAIN
# initialize variables
load_dotenv()
BHD_PASSKEY = os.getenv("BHD_PASSKEY")
BHD_API = os.getenv("BHD_API")
BHD_SEARCH = f'https://beyond-hd.me/api/torrents/{BHD_API}'
BHD_UPLOAD = f'https://beyond-hd.me/api/upload/{BHD_API}'
SESS = requests.session()
BBCODE = ""
tempdir = tempfile.mkdtemp()
args = getArgs()
directory = args.input
file_name = os.path.basename(args.input)
# USE GUESSIT TO DEFINE MORE VARIABLES
guess = dict(guessit.guessit(args.input))
searchterm = (guess['title'])
reso = guess.get('screen_size', None)
source = (guess['source'])
other = guess.get('other', None)
lastchar = file_name[len(file_name)-4:]
if lastchar == ".mkv" or lastchar == ".avi" or lastchar == ".mp4":
name = str(file_name.replace(".", " ")[:-4])
else:
name = str(file_name.replace(".", " "))
# JANKY IF STATEMENTS TO MAKE GUESSIT OUTPUT API FRIENDLY
if "Web" in source:
source = "WEB"
elif ((source == "Blu-ray") and (other == "Remux") and (reso == "1080p")):
reso = "BD Remux"
elif "DVD" in name:
reso = "DVD Remux"
elif ((source == "Ultra HD Blu-ray") and (other == "Remux") and (reso == "2160p")):
reso = "UHD Remux"
source = "Blu-ray"
# Find the required info before we upload (hopefully BHD already has it uploaded)
# Split on the Resolution, that way we search just for the name of the file
search_name = file_name.split(reso)
answer = find_gaps(searchterm, source, reso)
if answer is True:
print(f"{search_name[0]} - Not Found on BHD - UPLOAD IT NOW!")
sys.exit(0)
else:
print(f"{search_name[0]} - Found... Better luck next time")
sys.exit(1)