This commit is contained in:
Clayton Wilson 2017-11-03 17:48:08 -04:00
commit d5610f0b6d
6 changed files with 106 additions and 32 deletions

1
.gitignore vendored
View File

@ -2,4 +2,3 @@
login.json login.json
api info.txt api info.txt
__pycache__ __pycache__
menuLayout.txt

View File

@ -1,10 +1,61 @@
import requests import requests
import shutil import shutil
import json import json
import datetime
import dateutil
import os import os
import subprocess
from checks import checkTimestamp
from checks import getToken
def clear_screen():
IS_WINDOWS = os.name == "nt"
if IS_WINDOWS:
os.system("cls")
else:
os.system("clear")
def refreshToken(): def refreshToken():
print("Not implemented yet") if os.path.exists("login.json"):
try:
with open("login.json") as json_data:
login = json.load(json_data)
saveTime = dateutil.parser.parse(login["TIMESTAMP"])
curTime = datetime.datetime.now().replace(tzinfo=None)# TODO use UTC time?
json_data.close()
LOGIN_DATA = {
"apikey": login["API_KEY"],
"userkey": login["USER_KEY"],
"username": login["USER_NAME"]
}
if checkTimestamp(saveTime, curTime):
while True:
print("Your current token is still valid. Are you sure you want to grab a different one?")
choice = input("(y/n) ")
if choice is "n":
break
elif choice is "y":
login["TOKEN"] = getToken(LOGIN_DATA) # TODO find a better way to run this on both paths
login["TIMESTAMP"] = str(datetime.datetime.now().replace(tzinfo=None))
obj = open("login.json", "w")
obj.write(json.dumps(login))
obj.close()
print("\nNew token acquired!\n")
break
clear_screen()
else:
login["TOKEN"] = getToken(LOGIN_DATA)
login["TIMESTAMP"] = str(datetime.datetime.now().replace(tzinfo=None))
obj = open("login.json", "w")
obj.write(json.dumps(login))
obj.close()
print("New token acquired!\n")
except Exception as e:
print("You need to log in first. Select Login/Change login.\n") # TODO make a set of constants for error codes
else:
print("You need to log in first. Select Login/Change login.\n")
def clearLogin(): def clearLogin():
try: try:
@ -12,21 +63,25 @@ def clearLogin():
except Exception as e: except Exception as e:
pass pass
def clearFolders():# TODO implement this def clearFolders(): # TODO implement this
if os.path.exists("banner"): folders = ["banner", "fanart", "poster"]
print("cleared") for folder in folders:
else: if os.path.exists(folder):
print("empty") imageList = os.listdir(folder)
if len(imageList) != 0:
for x in imageList: # TODO check if folder is empty
print("Deleting " + x)
delPath = os.path.join(folder + "\\" + x)
os.remove(delPath)
print(folder + " cleared\n")
else:
print(folder + " is already empty")
else:
createFolder(folder)
print("")
if os.path.exists("fanart"): def createFolder(folder):
print("cleared") os.makedirs(folder)
else:
print("empty")
if os.path.exists("poster"):
print("cleared")
else:
print("empty")
def getImages(idNum, keyType, authHeaders): def getImages(idNum, keyType, authHeaders):
@ -73,3 +128,29 @@ def download(imageType, parsed_respObj):
else: else:
quit() quit()
return saveNameList return saveNameList
# The following code is from Red-DiscordBot
# https://github.com/Cog-Creators/Red-DiscordBot
def is_git_installed():
try:
subprocess.call(["git", "--version"], stdout=subprocess.DEVNULL,
stdin =subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
except FileNotFoundError:
return False
else:
return True
def update():
try:
code = subprocess.call(("git", "pull", "--ff-only"))
except FileNotFoundError:
print("\nError: Git not found. It's either not installed or you did "
"not clone this using git. Install instructions are on the GitHub: "
"https://github.com/ClaytonWWilson/Image-fetcher-for-theTVDB.com")
return
if code == 0:
print("\nThe program has been updated.\n")
else:
print("\nThere was an error while updating. This may be caused by edits "
"you have made to the code.")

View File

@ -32,8 +32,8 @@ def checkStatus(response, v):
else: else:
return True return True
def checkTimestamp(saveTime, curTime): def checkTimestamp(saveTime, curTime): # Returns true if the token is still valid
if curTime - saveTime < datetime.timedelta(0, 86100, 0):# if less than 23h 55m since last token grab if curTime - saveTime < datetime.timedelta(0, 86100, 0):
return True return True
else: else:
return False return False

View File

@ -2,19 +2,13 @@ import os # TODO: change the order of all import statements to
from login import * # TODO: 2. related 3rd party from login import * # TODO: 2. related 3rd party
from actions import * # TODO: 3. local application. with blank lines between and remove wilcard symbols from actions import * # TODO: 3. local application. with blank lines between and remove wilcard symbols
def clear_screen():
IS_WINDOWS = os.name == "nt"
if IS_WINDOWS:
os.system("cls")
else:
os.system("clear")
def user_choice(): def user_choice():
return input("> ").lower().strip() return input("> ").lower().strip()
def wait(): def wait():
input("Press enter to continue.") input("Press enter to continue.")
while True: while True:
clear_screen() clear_screen()
print("=============================\n" print("=============================\n"
@ -23,7 +17,7 @@ while True:
print("1. Search theTVDB.com") print("1. Search theTVDB.com")
print("2. Clear download folders") print("2. Clear download folders")
print("3. Change login") print("3. Login/Change login")
print("4. Refresh API Token") print("4. Refresh API Token")
print("5. Install Requirements") print("5. Install Requirements")
print("6. Check for updates\n") print("6. Check for updates\n")
@ -35,6 +29,7 @@ while True:
print("Search") print("Search")
break break
elif choice == "2": elif choice == "2":
clear_screen()
clearFolders() clearFolders()
wait() wait()
elif choice == "3": elif choice == "3":
@ -43,13 +38,14 @@ while True:
login() login()
wait() wait()
elif choice == "4": elif choice == "4":
refreshToken()# TODO implement this clear_screen()
refreshToken()
wait() wait()
elif choice == "5": elif choice == "5":
print("install requirements") print("install requirements")
break break
elif choice == "6": elif choice == "6":
print("update") update()
break wait()
elif choice == "0": elif choice == "0":
exit() exit()

View File

@ -52,6 +52,7 @@ def login():
obj = open("login.json", "w") obj = open("login.json", "w")
obj.write(json.dumps(login)) obj.write(json.dumps(login))
obj.close() obj.close()
print("\nLogin successful!")
else:# if login.json already exists else:# if login.json already exists
with open("login.json") as json_data:# TODO add a check for a login that is damaged/modified with open("login.json") as json_data:# TODO add a check for a login that is damaged/modified
login = json.load(json_data) login = json.load(json_data)

View File

@ -1,3 +0,0 @@
from login import login
login()