Skip to content

Commit

Permalink
Merge pull request #9 from RileyXX/clean-up-code-and-increase-perform…
Browse files Browse the repository at this point in the history
…ance

Clean up code and increase performance
  • Loading branch information
RileyXX authored May 5, 2023
2 parents 7538f96 + 67b509a commit 14c6ca5
Show file tree
Hide file tree
Showing 6 changed files with 100 additions and 128 deletions.
28 changes: 12 additions & 16 deletions IMDbTraktSyncer/IMDbTraktSyncer.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,14 @@

def main():

here = os.path.abspath(os.path.dirname(__file__))
file_path = os.path.join(here, 'credentials.txt')
with open(file_path, "r") as f:
lines = f.readlines()
values = {}
for line in lines:
key, value = line.strip().split("=")
values[key] = value
trakt_client_id = values["trakt_client_id"]
trakt_client_secret = values["trakt_client_secret"]
trakt_access_token = values["trakt_access_token"]
imdb_username = values["imdb_username"]
imdb_password = values["imdb_password"]

#Get credentials
trakt_client_id = verifyCredentials.trakt_client_id
trakt_client_secret = verifyCredentials.trakt_client_secret
trakt_access_token = verifyCredentials.trakt_access_token
imdb_username = verifyCredentials.imdb_username
imdb_password = verifyCredentials.imdb_password

#Start web driver
options = Options()
options.add_argument("--headless=new")
options.add_argument('--disable-notifications')
Expand Down Expand Up @@ -80,8 +74,10 @@ def main():

print('Setting IMDB Ratings')

#Get trakt and imdb ratings and filter out trakt ratings wish missing imbd id
trakt_ratings = [rating for rating in traktRatings.trakt_ratings if rating['ID'] is not None]
imdb_ratings = [rating for rating in imdbRatings.imdb_ratings if rating['ID'] is not None]
#Filter out ratings already set
imdb_ratings_to_set = [rating for rating in trakt_ratings if rating['ID'] not in [imdb_rating['ID'] for imdb_rating in imdb_ratings]]
trakt_ratings_to_set = [rating for rating in imdb_ratings if rating['ID'] not in [trakt_rating['ID'] for trakt_rating in trakt_ratings]]

Expand Down Expand Up @@ -161,10 +157,10 @@ def main():
if response.status_code != 201:
print(f"Error rating {item}: {response.content}")


#Close web driver
print("Closing webdriver...")
driver.quit()
service.stop()

if __name__ == '__main__':
main()
main()
109 changes: 46 additions & 63 deletions IMDbTraktSyncer/authTrakt.py
Original file line number Diff line number Diff line change
@@ -1,66 +1,49 @@
import requests
import os

here = os.path.abspath(os.path.dirname(__file__))
file_path = os.path.join(here, 'credentials.txt')

with open(file_path, "r") as f:
lines = f.readlines()
values = {}
for line in lines:
key, value = line.strip().split("=")
values[key] = value
CLIENT_ID = values["trakt_client_id"]
CLIENT_SECRET = values["trakt_client_secret"]
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

# Set up the authorization endpoint URL
auth_url = 'https://trakt.tv/oauth/authorize'

# Construct the authorization URL with the necessary parameters
params = {
'response_type': 'code',
'client_id': CLIENT_ID,
'redirect_uri': REDIRECT_URI,
'state': 'mystate', # Optional - used for CSRF protection
}
auth_url += '?' + '&'.join([f'{key}={value}' for key, value in params.items()])

# Print out the authorization URL and instruct the user to visit it
print(f'\nPlease visit the following URL to authorize this application: \n{auth_url}\n')

# After the user grants authorization, they will be redirected back to the redirect URI with a temporary authorization code.
# Extract the authorization code from the URL and use it to request an access token from the Trakt API.
authorization_code = input('Please enter the authorization code from the URL: ')

# Set up the access token request
headers = {
'Content-Type': 'application/json'
}
data = {
'code': authorization_code,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
'grant_type': 'authorization_code'
}

# Make the request to get the access token
response = requests.post('https://api.trakt.tv/oauth/token', headers=headers, json=data)

# Parse the JSON response from the API
json_data = response.json()

# Extract the access token from the response
ACCESS_TOKEN = json_data['access_token']

# Save the access token value to the credentials file
with open(file_path, "w") as f:
for key, value in values.items():
if key == "trakt_access_token":
f.write(f"{key}={ACCESS_TOKEN}\n")
else:
f.write(f"{key}={value}\n")

# Print out a message indicating that the token has been saved
print(f'Trakt access token saved to credentials.txt')
def authenticate(client_id, client_secret):
CLIENT_ID = client_id
CLIENT_SECRET = client_secret
REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob'

# Set up the authorization endpoint URL
auth_url = 'https://trakt.tv/oauth/authorize'

# Construct the authorization URL with the necessary parameters
params = {
'response_type': 'code',
'client_id': CLIENT_ID,
'redirect_uri': REDIRECT_URI,
'state': 'mystate', # Optional - used for CSRF protection
}
auth_url += '?' + '&'.join([f'{key}={value}' for key, value in params.items()])

# Print out the authorization URL and instruct the user to visit it
print(f'\nPlease visit the following URL to authorize this application: \n{auth_url}\n')

# After the user grants authorization, they will be redirected back to the redirect URI with a temporary authorization code.
# Extract the authorization code from the URL and use it to request an access token from the Trakt API.
authorization_code = input('Please enter the authorization code from the URL: ')

# Set up the access token request
headers = {
'Content-Type': 'application/json'
}
data = {
'code': authorization_code,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
'grant_type': 'authorization_code'
}

# Make the request to get the access token
response = requests.post('https://api.trakt.tv/oauth/token', headers=headers, json=data)

# Parse the JSON response from the API
json_data = response.json()

# Extract the access token from the response
ACCESS_TOKEN = json_data['access_token']

return ACCESS_TOKEN
30 changes: 13 additions & 17 deletions IMDbTraktSyncer/imdbRatings.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,20 @@
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from chromedriver_py import binary_path
try:
from IMDbTraktSyncer import verifyCredentials
except:
import verifyCredentials

#Get IMDb Ratings
print('Getting IMDB Ratings')

here = os.path.abspath(os.path.dirname(__file__))
file_path = os.path.join(here, 'credentials.txt')
with open(file_path, "r") as f:
lines = f.readlines()
values = {}
for line in lines:
key, value = line.strip().split("=")
values[key] = value
imdb_username = values["imdb_username"]
imdb_password = values["imdb_password"]
imdb_username = verifyCredentials.imdb_username
imdb_password = verifyCredentials.imdb_password

directory = os.path.dirname(os.path.realpath(__file__))

#Start web driver
options = Options()
options.add_argument("--headless=new")
options.add_argument('--disable-notifications')
Expand All @@ -45,8 +44,8 @@
email_input = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "input[type='email']")))[0]
password_input = wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "input[type='password']")))[0]

email_input.send_keys(values["imdb_username"])
password_input.send_keys(values["imdb_password"])
email_input.send_keys(imdb_username)
password_input.send_keys(imdb_password)

submit_button = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='submit']")))
submit_button.click()
Expand All @@ -68,14 +67,15 @@
csv_link = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".pop-up-menu-list-items a.pop-up-menu-list-item-link")))
csv_link.click()

#Wait for csv download to complete
#Wait for csv download to complete and close web driver
time.sleep(10)
driver.quit()
service.stop()

imdb_ratings = []

# Read the ratings from the CSV file
here = os.path.abspath(os.path.dirname(__file__))
ratings_path = os.path.join(here, 'ratings.csv')
try:
with open(ratings_path, 'r') as file:
Expand All @@ -99,10 +99,6 @@
if file.endswith('.csv'):
os.remove(os.path.join(directory, file))

# Print the results
#for rating in imdb_ratings:
# print(f'Title: {rating["Title"]}, Year: {rating["Year"]}, Rating: {rating["Rating"]}, IMDB ID: {rating["ID"]}')

print('Getting IMDB Ratings Complete')


27 changes: 8 additions & 19 deletions IMDbTraktSyncer/traktRatings.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
import os
import json
import subprocess
import requests
import requests
try:
from IMDbTraktSyncer import verifyCredentials
except:
import verifyCredentials

#Get Trakt Ratings
print('Getting Trakt Ratings')

here = os.path.abspath(os.path.dirname(__file__))
file_path = os.path.join(here, 'credentials.txt')
with open(file_path, "r") as f:
lines = f.readlines()
values = {}
for line in lines:
key, value = line.strip().split("=")
values[key] = value
CLIENT_ID = values["trakt_client_id"]
ACCESS_TOKEN = values["trakt_access_token"]
CLIENT_ID = verifyCredentials.trakt_client_id
ACCESS_TOKEN = verifyCredentials.trakt_access_token

headers = {
'Content-Type': 'application/json',
Expand Down Expand Up @@ -44,12 +41,4 @@

trakt_ratings = movie_ratings + show_ratings

#print('Movie ratings:')
#for item in movie_ratings:
# print(f'{item["Title"]} ({item["Year"]}): {item["Rating"]}/10 (IMDb ID: {item["ID"]})')
#
#print('\nShow ratings:')
#for item in show_ratings:
# print(f'{item["Title"]} ({item["Year"]}): {item["Rating"]}/10 (IMDb ID: {item["ID"]})')

print('Getting Trakt Ratings Complete')
30 changes: 19 additions & 11 deletions IMDbTraktSyncer/verifyCredentials.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import os
try:
from IMDbTraktSyncer import authTrakt
except:
import authTrakt

# Define the file path
here = os.path.abspath(os.path.dirname(__file__))
Expand Down Expand Up @@ -32,18 +36,22 @@
for key, value in values.items():
f.write(f"{key}={value}\n")

# Get the trakt_access_token value if it exists, or run the authTrakt.py script to get it
# Get the trakt_access_token value if it exists, or run the authTrakt.py function to get it
trakt_access_token = None
if "trakt_access_token" in values and values["trakt_access_token"] != "empty":
trakt_access_token = values["trakt_access_token"]
else:
here = os.path.abspath(os.path.dirname(__file__))
authTraktPath = os.path.join(here, 'authTrakt.py')
os.system(f"python {authTraktPath}")
with open(file_path, "r") as f:
lines = f.readlines()
for line in lines:
key, value = line.strip().split("=")
if key == "trakt_access_token":
trakt_access_token = value
break
client_id = values["trakt_client_id"]
client_secret = values["trakt_client_secret"]
trakt_access_token = authTrakt.authenticate(client_id, client_secret)
values["trakt_access_token"] = trakt_access_token
with open(file_path, "w") as f:
for key, value in values.items():
f.write(f"{key}={value}\n")

# Save the credential values as variables
trakt_client_id = values["trakt_client_id"]
trakt_client_secret = values["trakt_client_secret"]
trakt_access_token = values["trakt_access_token"]
imdb_username = values["imdb_username"]
imdb_password = values["imdb_password"]
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
with codecs.open(os.path.join(here, "README.md"), encoding="utf-8") as fh:
long_description = "\n" + fh.read()

VERSION = '1.0.5'
VERSION = '1.0.6'
DESCRIPTION = 'This script will sync user ratings for Movies and TV Shows both ways between Trakt and IMDb.'

# Setting up
Expand All @@ -35,4 +35,4 @@
'IMDbTraktSyncer = IMDbTraktSyncer.IMDbTraktSyncer:main'
]
}
)
)

0 comments on commit 14c6ca5

Please sign in to comment.