Skip to content

Commit

Permalink
More linting
Browse files Browse the repository at this point in the history
  • Loading branch information
Audionut committed Aug 31, 2024
1 parent 7c46235 commit b7ed255
Show file tree
Hide file tree
Showing 15 changed files with 277 additions and 305 deletions.
2 changes: 1 addition & 1 deletion cogs/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ async def send_embed_and_upload(self, ctx, meta):
res = meta['resolution']
missing = await self.get_missing(meta)

embed=discord.Embed(title=f"Upload: {meta['title']}", url=f"https://www.themoviedb.org/{meta['category'].lower()}/{meta['tmdb']}", description=meta['overview'], color=0x0080ff, timestamp=datetime.utcnow())
embed=discord.Embed(title = f"Upload: {meta['title']}", url=f"https://www.themoviedb.org/{meta['category'].lower()}/{meta['tmdb']}", description=meta['overview'], color=0x0080ff, timestamp=datetime.utcnow())
embed.add_field(name="Links", value=f"[TMDB](https://www.themoviedb.org/{meta['category'].lower()}/{meta['tmdb']}){imdb}{tvdb}")
embed.add_field(name=f"{res} / {meta['type']}{tag}", value=f"```{meta['name']}```", inline=False)
if missing != []:
Expand Down
1 change: 1 addition & 0 deletions discordbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ async def on_message(self, message):
return # ignore all bots
await self.process_commands(message)


if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)

Expand Down
6 changes: 3 additions & 3 deletions src/args.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def parse(self, args, meta):
parsed = urllib.parse.urlparse(value2)
try:
meta['ptp'] = urllib.parse.parse_qs(parsed.query)['torrentid'][0]
except:
except Exception:
console.print('[red]Your terminal ate part of the url, please surround in quotes next time, or pass only the torrentid')
console.print('[red]Continuing without -ptp')
else:
Expand All @@ -131,7 +131,7 @@ def parse(self, args, meta):
if blupath.endswith('/'):
blupath = blupath[:-1]
meta['blu'] = blupath.split('/')[-1]
except:
except Exception:
console.print('[red]Unable to parse id from url')
console.print('[red]Continuing without --blu')
else:
Expand All @@ -141,7 +141,7 @@ def parse(self, args, meta):
parsed = urllib.parse.urlparse(value2)
try:
meta['hdb'] = urllib.parse.parse_qs(parsed.query)['id'][0]
except:
except Exception:
console.print('[red]Your terminal ate part of the url, please surround in quotes next time, or pass only the torrentid')
console.print('[red]Continuing without -hdb')
else:
Expand Down
4 changes: 2 additions & 2 deletions src/prep.py
Original file line number Diff line number Diff line change
Expand Up @@ -1441,7 +1441,7 @@ def get_keywords(self, tmdb_info):
keywords = [f"{keyword['name'].replace(',', ' ')}" for keyword in tmdb_keywords.get('keywords')]
elif tmdb_keywords.get('results') is not None:
keywords = [f"{keyword['name'].replace(',', ' ')}" for keyword in tmdb_keywords.get('results')]
return(', '.join (keywords))
return (', '.join(keywords))
else:
return ''

Expand All @@ -1450,7 +1450,7 @@ def get_genres(self, tmdb_info):
tmdb_genres = tmdb_info.get('genres', [])
if tmdb_genres is not []:
genres = [f"{genre['name'].replace(',', ' ')}" for genre in tmdb_genres]
return(', '.join (genres))
return (', '.join(genres))
else:
return ''

Expand Down
4 changes: 2 additions & 2 deletions src/trackers/ACM.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ async def upload(self, meta):
region_id = await common.unit3d_region_ids(meta.get('region'))
distributor_id = await common.unit3d_distributor_ids(meta.get('distributor'))
acm_name = await self.edit_name(meta)
if meta['anon'] == 0 and bool(str2bool(str(self.config['TRACKERS'][self.tracker].get('anon', "False")))) == False:
if meta['anon'] == 0 and bool(str2bool(str(self.config['TRACKERS'][self.tracker].get('anon', "False")))) is False:
anon = 0
else:
anon = 1
Expand Down Expand Up @@ -262,7 +262,7 @@ async def upload(self, meta):
console.print("It may have uploaded, go check")
return
else:
console.print(f"[cyan]Request Data:")
console.print("[cyan]Request Data:")
console.print(data)
open_torrent.close()

Expand Down
2 changes: 1 addition & 1 deletion src/trackers/CBR.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ async def get_type_id(self, type):

async def get_res_id(self, resolution):
resolution_id = {
'4320p': '1',
'4320p': '1',
'2160p': '2',
'1080p': '3',
'1080i': '4',
Expand Down
12 changes: 6 additions & 6 deletions src/trackers/HDB.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ async def get_tags(self, meta):
"MASTERS OF CINEMA": 19, "MOC": 19,
"KINO LORBER": 55, "KINO": 55,
"BFI VIDEO": 63, "BFI": 63, "BRITISH FILM INSTITUTE": 63,
"STUDIO CANAL":65,
"STUDIO CANAL": 65,
"ARROW": 64
}
if meta.get('distributor') in distributor_dict.keys():
Expand Down Expand Up @@ -330,16 +330,16 @@ async def search_existing(self, meta):
'search': meta['resolution']
}
if int(meta.get('imdb_id', '0').replace('tt', '0')) != 0:
data['imdb'] = {'id' : meta['imdb_id']}
data['imdb'] = {'id': meta['imdb_id']}
if int(meta.get('tvdb_id', '0')) != 0:
data['tvdb'] = {'id' : meta['tvdb_id']}
data['tvdb'] = {'id': meta['tvdb_id']}
try:
response = requests.get(url=url, data=json.dumps(data))
response = response.json()
for each in response['data']:
result = each['name']
dupes.append(result)
except:
except Exception:
console.print('[bold red]Unable to search for existing torrents on site. Either the site is down or your passkey is incorrect')
await asyncio.sleep(5)

Expand Down Expand Up @@ -367,7 +367,7 @@ async def validate_api(self):
if r.get('status', 5) == 0:
return True
return False
except:
except Exception:
return False

async def validate_cookies(self, meta):
Expand Down Expand Up @@ -503,7 +503,7 @@ async def get_info_from_torrent_id(self, hdb_id):
hdb_name = response['data'][0]['name']
hdb_torrenthash = response['data'][0]['hash']

except:
except Exception:
console.print_exception()
else:
console.print("Failed to get info from HDB ID. Either the site is down or your credentials are invalid")
Expand Down
89 changes: 45 additions & 44 deletions src/trackers/MTV.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
import cli_ui
import pickle
import re
import traceback
from pathlib import Path
from str2bool import str2bool
from src.trackers.COMMON import COMMON
from datetime import datetime, date
from datetime import datetime


class MTV():
"""
Expand Down Expand Up @@ -43,7 +43,7 @@ async def upload(self, meta):

# Initiate the upload with retry logic
await self.upload_with_retry(meta, cookiefile, common)

async def upload_with_retry(self, meta, cookiefile, common, img_host_index=1):
approved_image_hosts = ['ptpimg', 'imgbox']

Expand Down Expand Up @@ -102,16 +102,16 @@ async def upload_with_retry(self, meta, cookiefile, common, img_host_index=1):
comment="Created by L4G's Upload Assistant",
created_by="L4G's Upload Assistant"
)

# Explicitly set the piece size and update metainfo
new_torrent.piece_size = 8388608 # 8 MiB in bytes
new_torrent.metainfo['info']['piece length'] = 8388608 # Ensure 'piece length' is set

# Validate and write the new torrent
new_torrent.validate_piece_size()
new_torrent.generate(callback=prep.torf_cb, interval=5)
new_torrent.write(f"{meta['base_dir']}/tmp/{meta['uuid']}/MTV.torrent", overwrite=True)

torrent_filename = "MTV"

await common.edit_torrent(meta, self.tracker, self.source_flag, torrent_filename=torrent_filename)
Expand Down Expand Up @@ -170,17 +170,17 @@ async def upload_with_retry(self, meta, cookiefile, common, img_host_index=1):
console.print(response.url)
else:
if "authkey.php" in response.url:
console.print(f"[red]No DL link in response, It may have uploaded, check manually.")
console.print("[red]No DL link in response, It may have uploaded, check manually.")
else:
console.print(f"[red]Upload Failed. It doesn't look like you are logged in.")
except:
console.print(f"[red]It may have uploaded, check manually.")
console.print("[red]Upload Failed. It doesn't look like you are logged in.")
except Exception:
console.print("[red]It may have uploaded, check manually.")
print(traceback.print_exc())
else:
console.print(f"[cyan]Request Data:")
console.print("[cyan]Request Data:")
console.print(data)
return

async def handle_image_upload(self, meta, img_host_index=1, approved_image_hosts=None):
if approved_image_hosts is None:
approved_image_hosts = ['ptpimg', 'imgbox']
Expand Down Expand Up @@ -229,7 +229,7 @@ async def edit_desc(self, meta):
base = open(f"{meta['base_dir']}/tmp/{meta['uuid']}/DESCRIPTION.txt", 'r').read()
with open(f"{meta['base_dir']}/tmp/{meta['uuid']}/[{self.tracker}]DESCRIPTION.txt", 'w') as desc:
# adding bd_dump to description if it exits and adding empty string to mediainfo
if meta['bdinfo'] != None:
if meta['bdinfo'] is not None:
mi_dump = None
bd_dump = open(f"{meta['base_dir']}/tmp/{meta['uuid']}/BD_SUMMARY_00.txt", 'r', encoding='utf-8').read()
else:
Expand All @@ -241,19 +241,19 @@ async def edit_desc(self, meta):
desc.write("[mediainfo]" + mi_dump + "[/mediainfo]\n\n")
images = meta['image_list']
if len(images) > 0:
desc.write(f"[spoiler=Screenshots]")
desc.write("[spoiler=Screenshots]")
for each in range(len(images)):
raw_url = images[each]['raw_url']
img_url = images[each]['img_url']
desc.write(f"[url={raw_url}][img=250]{img_url}[/img][/url]")
desc.write(f"[/spoiler]")
desc.write("[/spoiler]")
desc.write(f"\n\n{base}")
desc.close()
return

async def edit_group_desc(self, meta):
description = ""
if meta['imdb_id'] not in ("0", "", None):
if meta['imdb_id'] not in ("0", "", None):
description += f"https://www.imdb.com/title/tt{meta['imdb_id']}"
if meta['tmdb'] != 0:
description += f"\nhttps://www.themoviedb.org/{str(meta['category'].lower())}/{str(meta['tmdb'])}"
Expand Down Expand Up @@ -289,15 +289,15 @@ async def edit_name(self, meta):
mtv_name = re.sub(r"[^0-9a-zA-ZÀ-ÿ. &+'\-\[\]]+", "", mtv_name)
mtv_name = mtv_name.replace(' ', '.').replace('..', '.')
return mtv_name

async def get_res_id(self, resolution):
resolution_id = {
'8640p':'0',
'8640p': '0',
'4320p': '4000',
'2160p': '2160',
'1440p' : '1440',
'1440p': '1440',
'1080p': '1080',
'1080i':'1080',
'1080i': '1080',
'720p': '720',
'576p': '0',
'576i': '0',
Expand Down Expand Up @@ -355,6 +355,7 @@ async def get_origin_id(self, meta):
# returning P2P
else:
return '3'

async def get_tags(self, meta):
tags = []
# Genres
Expand All @@ -369,7 +370,7 @@ async def get_tags(self, meta):
tags.append('hd')
# Streaming Service
if str(meta['service_longname']) != "":
tags.append(f"{meta['service_longname'].lower().replace(' ', '.')}.source")
tags.append(f"{meta['service_longname'].lower().replace(' ', '.')}.source")
# Release Type/Source
for each in ['remux', 'WEB.DL', 'WEBRip', 'HDTV', 'BluRay', 'DVD', 'HDDVD']:
if (each.lower().replace('.', '') in meta['type'].lower()) or (each.lower().replace('-', '') in meta['source']):
Expand All @@ -388,14 +389,14 @@ async def get_tags(self, meta):
tags.append('sd.season')
else:
tags.append('hd.season')

# movie tags
if meta['category'] == 'MOVIE':
if meta['sd'] == 1:
tags.append('sd.movie')
else:
tags.append('hd.movie')

# Audio tags
audio_tag = ""
for each in ['dd', 'ddp', 'aac', 'truehd', 'mp3', 'mp2', 'dts', 'dts.hd', 'dts.x']:
Expand Down Expand Up @@ -436,10 +437,10 @@ async def validate_credentials(self, meta):
if not os.path.exists(cookiefile):
await self.login(cookiefile)
vcookie = await self.validate_cookies(meta, cookiefile)
if vcookie != True:
if vcookie is not True:
console.print('[red]Failed to validate cookies. Please confirm that the site is up and your username and password is valid.')
recreate = cli_ui.ask_yes_no("Log in again and create new session?")
if recreate == True:
if recreate is True:
if os.path.exists(cookiefile):
os.remove(cookiefile)
await self.login(cookiefile)
Expand All @@ -448,14 +449,14 @@ async def validate_credentials(self, meta):
else:
return False
vapi = await self.validate_api()
if vapi != True:
if vapi is not True:
console.print('[red]Failed to validate API. Please confirm that the site is up and your API key is valid.')
return True

async def validate_api(self):
url = self.search_url
params = {
'apikey' : self.config['TRACKERS'][self.tracker]['api_key'].strip(),
'apikey': self.config['TRACKERS'][self.tracker]['api_key'].strip(),
}
try:
r = requests.get(url, params=params)
Expand All @@ -464,7 +465,7 @@ async def validate_api(self):
console.print("[red]Invalid API Key")
return False
return True
except:
except Exception:
return False

async def validate_cookies(self, meta, cookiefile):
Expand Down Expand Up @@ -499,12 +500,12 @@ async def login(self, cookiefile):
with requests.Session() as session:
url = 'https://www.morethantv.me/login'
payload = {
'username' : self.config['TRACKERS'][self.tracker].get('username'),
'password' : self.config['TRACKERS'][self.tracker].get('password'),
'keeploggedin' : 1,
'cinfo' : '1920|1080|24|0',
'submit' : 'login',
'iplocked' : 1,
'username': self.config['TRACKERS'][self.tracker].get('username'),
'password': self.config['TRACKERS'][self.tracker].get('password'),
'keeploggedin': 1,
'cinfo': '1920|1080|24|0',
'submit': 'login',
'iplocked': 1,
# 'ssl' : 'yes'
}
res = session.get(url="https://www.morethantv.me/login")
Expand All @@ -521,11 +522,11 @@ async def login(self, cookiefile):
mfa_code = pyotp.parse_uri(otp_uri).now()
else:
mfa_code = console.input('[yellow]MTV 2FA Code: ')

two_factor_payload = {
'token' : resp.text.rsplit('name="token" value="', 1)[1][:48],
'code' : mfa_code,
'submit' : 'login'
'token': resp.text.rsplit('name="token" value="', 1)[1][:48],
'code': mfa_code,
'submit': 'login'
}
resp = session.post(url="https://www.morethantv.me/twofactor/login", data=two_factor_payload)
# checking if logged in
Expand All @@ -543,9 +544,9 @@ async def search_existing(self, meta):
dupes = []
console.print("[yellow]Searching for existing torrents on site...")
params = {
't' : 'search',
't': 'search',
'apikey' : self.config['TRACKERS'][self.tracker]['api_key'].strip(),
'q' : ""
'q': ""
}
if meta['imdb_id'] not in ("0", "", None):
params['imdbid'] = "tt" + meta['imdb_id']
Expand All @@ -569,11 +570,11 @@ async def search_existing(self, meta):
console.print(f"[yellow]{rr.get('status_message')}")
await asyncio.sleep(5)
else:
console.print(f"[red]Site Seems to be down or not responding to API")
except:
console.print(f"[red]Unable to search for existing torrents on site. Most likely the site is down.")
console.print("[red]Site Seems to be down or not responding to API")
except Exception:
console.print("[red]Unable to search for existing torrents on site. Most likely the site is down.")
dupes.append("FAILED SEARCH")
print(traceback.print_exc())
await asyncio.sleep(5)

return dupes
return dupes
Loading

0 comments on commit b7ed255

Please sign in to comment.