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
api info.txt
__pycache__
menuLayout.txt

View File

@ -1,10 +1,61 @@
import requests
import shutil
import json
import datetime
import dateutil
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():
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():
try:
@ -13,20 +64,24 @@ def clearLogin():
pass
def clearFolders(): # TODO implement this
if os.path.exists("banner"):
print("cleared")
folders = ["banner", "fanart", "poster"]
for folder in folders:
if os.path.exists(folder):
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("empty")
print(folder + " is already empty")
else:
createFolder(folder)
print("")
if os.path.exists("fanart"):
print("cleared")
else:
print("empty")
if os.path.exists("poster"):
print("cleared")
else:
print("empty")
def createFolder(folder):
os.makedirs(folder)
def getImages(idNum, keyType, authHeaders):
@ -73,3 +128,29 @@ def download(imageType, parsed_respObj):
else:
quit()
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:
return True
def checkTimestamp(saveTime, curTime):
if curTime - saveTime < datetime.timedelta(0, 86100, 0):# if less than 23h 55m since last token grab
def checkTimestamp(saveTime, curTime): # Returns true if the token is still valid
if curTime - saveTime < datetime.timedelta(0, 86100, 0):
return True
else:
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 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():
return input("> ").lower().strip()
def wait():
input("Press enter to continue.")
while True:
clear_screen()
print("=============================\n"
@ -23,7 +17,7 @@ while True:
print("1. Search theTVDB.com")
print("2. Clear download folders")
print("3. Change login")
print("3. Login/Change login")
print("4. Refresh API Token")
print("5. Install Requirements")
print("6. Check for updates\n")
@ -35,6 +29,7 @@ while True:
print("Search")
break
elif choice == "2":
clear_screen()
clearFolders()
wait()
elif choice == "3":
@ -43,13 +38,14 @@ while True:
login()
wait()
elif choice == "4":
refreshToken()# TODO implement this
clear_screen()
refreshToken()
wait()
elif choice == "5":
print("install requirements")
break
elif choice == "6":
print("update")
break
update()
wait()
elif choice == "0":
exit()

View File

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

View File

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