Skip to content

Instantly share code, notes, and snippets.

@Lanse505
Created January 30, 2022 18:14
Show Gist options
  • Save Lanse505/9d8aa05096affffd4948aebf7a0c65ce to your computer and use it in GitHub Desktop.
Save Lanse505/9d8aa05096affffd4948aebf7a0c65ce to your computer and use it in GitHub Desktop.
import os.path as path
import sys
import requests
import util
import search
menu = """
############################################
# Welcome to the Main Menu #
# Please enter your choice of action below #
############################################
# 1) Search for Movie #
# 2) View popular search results #
# 3) Exit #
############################################
"""
if __name__ == '__main__':
if not path.exists("./api-key.txt"):
print("A file has been generated in your run-dir named 'api-key.txt' please enter your api-key for omdb there")
with open("./api-key.txt", 'w', encoding='utf-8'):
pass
sys.exit()
with open("./api-key.txt", 'r') as file:
apiKey = file.read(8)
response = requests.get(f"http://www.omdbapi.com/?apikey={apiKey}")
json = response.json()
while 'Error' in json and json['Error'] == 'Invalid API key!':
print("Error: Invalid API Key")
apiKey = input("Please enter your api key: ")
response = requests.get(f"http://www.omdbapi.com/?apikey={apiKey}")
json = response.json()
optionID = -1
while True:
while optionID == -1:
print(menu)
optionID = input("Which program would you like to run: ")
while not util.is_integer(optionID) or not util.is_within(int(optionID), 1, 3):
print("Error: Invalid Program ID")
optionID = input("Which program would you like to run: ")
optionID = int(optionID)
if optionID == 1:
optionID = search.menu.runSearchMenuLogic(apiKey)
elif optionID == 2:
print()
else:
sys.exit()
import re
# Checks if the provided input can be converted to an integer
import urllib.parse
def is_integer(num):
try: # Attempt to execute
int(num) # Attempt parse to int
return True # If success True
except ValueError:
return False # If failure False
# Checks if the provided value is less than the maximum specified value but greater than the minimum specified value.
def is_within(value, minimum_inclusive, maximum_inclusive):
# Check so that the value is:
# Larger than minimum_inclusive
# Smaller than maximum_inclusive
if minimum_inclusive <= value <= maximum_inclusive:
return True # Returns true if it's between min_inclusive and max_inclusive
return False # Returns false if it's outside the bounds of min_inclusive and max_inclusive
def getSearchID():
typeTarget = input("Please input the ID Type [Example: ID, Name]: ")
while typeTarget.lower() != 'id' and typeTarget.lower() != 'name':
print("Error: Invalid Input")
typeTarget = input("Please input the ID Type [Example: ID, Name]: ")
movieId = input("Please input the ID [Example: tt3896198 or Guardians of the Galaxy]: ")
if typeTarget == 'id':
while not re.match(r"[t]{2}\d{7}", movieId) and typeTarget != 'name':
print("Error: input did not match valid regex for an IMDB Id")
movieId = input("Please input the ID [Example: tt3896198 or Guardians of the Galaxy]: ")
else:
movieId = urllib.parse.quote(movieId)
return typeTarget, movieId
import util
import requests
import search
def runSearchMenuLogic(api_key: str):
typeTarget, movieId = util.getSearchID()
if typeTarget.lower() == 'id':
r = requests.get(f"http://www.omdbapi.com/?apikey={api_key}&i={movieId}")
else:
r = requests.get(f"http://www.omdbapi.com/?apikey={api_key}&s={movieId}")
if r.status_code != 200 or 'Error' in r.json():
print()
print("Error: The requested ID was either found no results or returned a status-code other than 200")
print(f"Status Code: {r.status_code}")
print(f"Error: {r.json()['Error']}")
print(f"Reason: {r.reason}")
print()
input("Press any key to continue back to MainMenu")
return -1
else:
rj = r.json()
handlers = []
if 'Search' in rj:
for d in rj['Search']:
handlers.append(f"Option {rj['Search'].index(d)}: {search.handler.SearchHandler(True, d)}")
for h in handlers:
print(h)
target = input("Which of the above movies/series did you want to view?: ")
while not util.is_integer(target) or not util.is_within(int(target), 0, len(rj['Search'])):
print("Error: Invalid Target ID")
target = input("Which of the above movies/series did you want to view?: ")
imdbId = rj['Search'][int(target)]["imdbID"]
r = requests.get(f"http://www.omdbapi.com/?apikey={api_key}&i={imdbId}")
handler = search.handler.SearchHandler(False, r.json())
print(handler)
else:
handler = search.handler.SearchHandler(False, rj)
print(handler)
input("Press any key to continue back to MainMenu")
return -1
import json
import search
class SearchHandler(object):
def SearchHandler(self, partial: bool, input_json: json):
self.__init__(self, partial, input_json)
def __init__(self, partial: bool, input_json: json):
self.raw = input_json
self.partial = partial
if partial:
self.title = input_json['Title']
self.year = input_json['Year']
self.imdbID = input_json['imdbID']
self.type = input_json['Type']
self.poster = input_json['Poster']
else:
self.title = input_json['Title']
self.year = input_json['Year']
self.rated = input_json['Rated']
self.released = input_json['Released']
time = str(input_json['Runtime']).split(' ')[0]
self.runtime = search.runtime.SearchRuntimeHandler(int(time))
self.genre = input_json['Genre']
self.director = input_json['Director']
self.writer = input_json['Writer']
self.actors = input_json['Actors']
self.plot = input_json['Plot']
self.language = input_json['Language']
self.country = input_json['Country']
self.awards = input_json['Awards']
self.poster = input_json['Poster']
self.ratings = search.rating.SearchRatingHandler(input_json['Ratings'])
self.metascore = input_json['Metascore']
self.imdbRating = input_json['imdbRating']
self.imdbVotes = input_json['imdbVotes']
self.imdbID = input_json['imdbID']
self.type = input_json['Type']
def __str__(self):
if self.partial:
return f"""
Title: {self.title}
Year: {self.year}
imdbID: {self.imdbID}
Type: {self.type}
Poster: {self.poster}
"""
else:
return f"""
Title: {self.title}
Year: {self.year}
Rated: {self.rated}
Released: {self.released}
Runtime: {self.runtime}
Genre: {self.genre}
Director: {self.director}
Writer: {self.writer}
Actors: {self.actors}
Plot: {self.plot}
Language: {self.language}
Country: {self.country}
Awards: {self.awards}
Poster: {self.poster}
Ratings: {self.ratings}
Metascore: {self.metascore}
IMDB Rating: {self.imdbRating}
IMDB Votes: {self.imdbVotes}
IMDB ID: {self.imdbID}
Type: {self.type}
"""
class SearchRatingHandler(object):
def __init__(self, response: list):
self.ratings = response
def __str__(self):
printable = "\n\t\t"
for store in self.ratings:
count = 1
for key, value in store.items():
rating = str(value).replace('Value, ', '')
if count % 2 == 0:
printable = printable + f"{rating}\n\t\t"
count = 1
else:
printable = printable + f"{rating}: "
count += 1
return printable[:-3]
class SearchRuntimeHandler(object):
def SearchRuntimeHandler(self, runtime: int):
self.__init__(self, runtime)
def __init__(self, runtime: int):
self.runtime = runtime
self.hours = runtime / 60
self.minutes = (self.hours * 60) % 60
self.seconds = (self.hours * 3600) % 60
def __str__(self):
return "%d:%02d:%02d" % (self.hours, self.minutes, self.seconds)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment