Skip to content

Commit

Permalink
Merge pull request #10 from Amateur-God/optimisations-and-improvements
Browse files Browse the repository at this point in the history
Optimisations and improvements
  • Loading branch information
Amateur-God authored Mar 26, 2024
2 parents 62aa456 + 5883542 commit 13f5ead
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 23 deletions.
65 changes: 44 additions & 21 deletions EmbyArrSync.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@
import os
import requests
import json
import re

# Load environment variables from .env file
env_file = 'config/EmbyArrSync.env'
load_dotenv(dotenv_path=env_file)

IGNORE_FAVOURITES = os.getenv('IGNORE_FAVOURITES', 'False') == 'True'
HANDLE_TV = os.getenv('HANDLE_TV', 'False') == 'True'
HANDLE_MOVIES = os.getenv('HANDLE_MOVIES', 'False') == 'True'
TV_DELETE = os.getenv('TV_DELETE', 'False') == 'True'
Expand Down Expand Up @@ -85,7 +87,12 @@ def get_watched_items(user_id):
print(f"Error fetching watched items from Emby: {response.status_code}, {response.text}")
return None

def get_tmdb_id(movie_name):
def get_tmdb_id(movie_name, movie_path):
# Try to extract TMDBID from the path
match = re.search(r'tmdbid-(\d+)', movie_path)
if match:
return match.group(1) # Returns the first matching group (the ID)
# If the ID is not found in the path, proceed to search via the API
search_url = f'https://api.themoviedb.org/3/search/movie'
params = {
'api_key': TMDB_API_KEY,
Expand Down Expand Up @@ -120,7 +127,12 @@ def get_tvdb_token():

TVDB_TOKEN = get_tvdb_token()

def get_tvdb_id(series_name):
def get_tvdb_id(series_name, series_path):
# Try to extract TVDBID from the path
match = re.search(r'tvdbid-(\d+)', series_path)
if match:
return match.group(1) # Returns the first matching group (the ID)
# If the ID is not found in the path, proceed to search via the API
search_url = f"https://api4.thetvdb.com/v4/search?query={series_name}"
headers = {
'Authorization': f'Bearer {TVDB_TOKEN}',
Expand Down Expand Up @@ -295,38 +307,48 @@ def delete_movie_file(radarr_id, movie_name):
print(f"Failed to delete movie ID {movie_name} from Radarr: {response.status_code}, {response.text}")

def main():
# Check and print the status of HANDLE_TV and HANDLE_MOVIES at the start
if not HANDLE_TV:
print("Handling of TV shows is disabled, Skipping to Movies.")
if not HANDLE_MOVIES:
print("Handling of movies is disabled, Ending script.")
# Update Blacklist with Favourites at start based on Env Variables
watched_series = get_series_info(EMBY_USER_ID)
if watched_series:
if watched_series and IGNORE_FAVOURITES:
for item in watched_series:
if item['UserData']['IsFavorite']:
print(f"favorite item: {item['Name']} and adding {item['Path']} to blacklisted paths")
BLACKLISTED_PATHS.append(item['Path']) # Add the path to blacklisted paths
if item['UserData']['IsFavorite'] and item['Type'] == 'Series' and HANDLE_TV:
BLACKLISTED_PATHS.append(item['Path']) # Add the path to blacklisted paths (should capture everything)
print(f"Favorite Series: {item['Name']} and adding {item['Path']} to blacklisted paths")
BLACKLISTED_TV_SHOWS.append(item['Name']) # Add the Name to blacklisted Movies (Fall back for if path misses something)
print(f"Favorite Series: {item['Name']} and adding to blacklisted TV Shows")
elif item['UserData']['IsFavorite'] and item['Type'] == 'Movie' and HANDLE_MOVIES:
BLACKLISTED_PATHS.append(item['Path']) # Add the path to blacklisted paths (should capture everything)
print(f"Favorite Movie: {item['Name']} and adding {item['Path']} to blacklisted paths")
BLACKLISTED_MOVIES.append(item['Name']) # Add the Name to blacklisted Movies (Fall back for if path misses something)
print(f"Favorite Series: {item['Name']} and adding to blacklisted TV Shows")
continue
if not IGNORE_FAVOURITES:
print("Ignore Favourites set to false, WARNING FAVOURITES WILL BE HANDLED BY THE SCRIPT.")
# Print statement for Handle TV = False
if not HANDLE_TV:
print("Handling of TV shows is disabled, Skipping to Movies.")
# Logic for hadnling everything and calling the rest of the funcions
#Gets list of watched items from emby
watched_items = get_watched_items(EMBY_USER_ID)
if watched_items:
for item in watched_items:
if item['Type'] == 'Episode' and HANDLE_TV:
if watched_items: # only acts on results from emby in watched items
for item in watched_items: #Loops through each item in watched items and applies the following logic
if item['Type'] == 'Episode' and HANDLE_TV: #Checks if item type is an episode and if handle TV = True
series_name = item['SeriesName']
episode_name = item['Name']
season_number = item['ParentIndexNumber']
episode_number = item['IndexNumber']
item_info = f"{episode_name} from {series_name}"
if item['UserData']['IsFavorite']:
if item['UserData']['IsFavorite']: #Checks if episode is favourited in emby
print(f"Skipping favourite item: {item['Name']}")
continue
if any(blacklisted_path in item['Path'] for blacklisted_path in BLACKLISTED_PATHS):
if any(blacklisted_path in item['Path'] for blacklisted_path in BLACKLISTED_PATHS): # Checks if file path is in blacklisted Path
print(f"Skipping item in blacklisted path: {item['Name']}")
continue
if series_name in BLACKLISTED_TV_SHOWS:
if series_name in BLACKLISTED_TV_SHOWS: # Checks if series name is blacklisted
print(f"Skipping blacklisted show: {series_name}")
continue # Skip this iteration if the show is blacklisted
# Fetch TVDB ID using series name
tvdb_id = get_tvdb_id(series_name)
# Fetch TVDB ID using series name
tvdb_id = get_tvdb_id(series_name, item['Path'])
if tvdb_id:
# Fetch Sonarr series ID using TVDB ID
series_id = get_series_id_by_tvdb(tvdb_id)
Expand Down Expand Up @@ -369,7 +391,7 @@ def main():
continue # Skip this iteration if the Movie is blacklisted
elif movie_name not in BLACKLISTED_MOVIES:
# Use the movie name to fetch the TMDB ID directly
tmdb_id = get_tmdb_id(movie_name)
tmdb_id = get_tmdb_id(movie_name, item['Path'])
if tmdb_id:
movie_info = get_movie_info(tmdb_id, movie_name)
if movie_info:
Expand All @@ -395,9 +417,10 @@ def main():
print(f"No valid release dates available for comparison: {movie_name}")
else:
print(f"TMDB ID not found for movie '{item_info}'.")

else:
print("No watched items found from Emby.")
if not HANDLE_MOVIES:
print("Handling of movies is disabled, Ending script.")

if __name__ == "__main__":
main()
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ Login to Emby, go to Dashboard and then to users, select the user you want the s

Open EmbyArrSync.env in the config Folder with your prefered text editor and Replace the placeholders with the correct variables

Warning setting "IGNORE_FAVOURITES" to False means the script will run on items that are favourited in emby, Setting to true means items Favourited in emby will be blacklisted and ignored by the script

It is reccomended to lower the limit after first run, this limit is just as high as possible so that first run gets as many watched shows as possible.

if installed in its own folder in /opt

```
Expand All @@ -66,6 +70,7 @@ HANDLE_TV = True # Set to false to disable the script from touching TV shows
HANDLE_MOVIES = True # Set to false to disable the script from touching Movies shows
TV_DELETE = True # Set to false to disable the script from Deleting TV shows
MOVIE_DELETE = True # Set to false to disable the script from Deleting Movies shows
IGNORE_FAVOURITES = True # Set to True if you want the script to ignore items that are marked as favourites in emby (Not Unmonitor and Not Delete)


# Sonarr API details
Expand Down
4 changes: 2 additions & 2 deletions config/EmbyArrSync.env
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# TV and Movie Handling Logic
# TV, Movie and Favourite Handling Logic
HANDLE_TV = True # Set to false to disable the script from touching TV shows
HANDLE_MOVIES = True # Set to false to disable the script from touching Movies shows
TV_DELETE = True # Set to false to disable the script from Deleting TV shows
MOVIE_DELETE = True # Set to false to disable the script from Deleting Movies shows

IGNORE_FAVOURITES = True # Set to True if you want the script to ignore items that are marked as favourites in emby (Not Unmonitor and Not Delete)

# Sonarr API details
SONARR_API_KEY = 'SONARR_API_KEY'
Expand Down

0 comments on commit 13f5ead

Please sign in to comment.