Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/better watched tracking #28

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions .gitignore

This file was deleted.

103 changes: 103 additions & 0 deletions accounts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# This file helps grab details pertaining to plex and sonarr

from config import *
from plexapi.server import PlexServer
import requests
from logic import main as workhorse # import primary logic flows

# SONARR
def sonarr_shows(): # grab sonarr details
sonarr_fetch_shows = requests.get(
SONARR_URL + "/api/series?apiKey=" + SONARR_API_KEY
)
sonarr_shows = None
if sonarr_fetch_shows.status_code == 200:
sonarr_shows = sonarr_fetch_shows.json()

if sonarr_shows == None:
print(
"Failed to fetch series from Sonarr. Please double check your Sonarr URL and API Key"
)
exit(1)
return sonarr_shows


# PLEX
def plex_details(): # grab plex details
plex = PlexServer(PLEX_URL, PLEX_TOKEN)
account = plex.myPlexAccount()
return plex, account


def all_accounts_finder(plex): # grab all accounts on system
ALL_PLEX_ACCOUNTS = plex.systemAccounts()

ALL_PLEX_ACCOUNTS.pop(0) # remove first output that isn't a user
allAccounts = getNames(ALL_PLEX_ACCOUNTS) # converts to just names
# print(allAccounts)
# print(allAccounts)
return allAccounts


def getNames(ALL_PLEX_ACCOUNTS):
newList = []

for i in ALL_PLEX_ACCOUNTS:
item = str(i)
newItem = item.rsplit(":")[2] # remove all before second ":"
newItem2 = newItem.rsplit(">")[0] # remove ">" after name
# print(newItem2)
newList.append(newItem2)

return newList


def try_plex_user(currentAccountOriginal, plex):
try:
x = plex.switchUser(currentAccountOriginal)
return x
except:
x = "failed"
return x


# Iterate through plex accounts for manual
def plex_account_iterator(
test_mode,
sonarr_shows,
plex,
x,
currentAccountOriginal,
currentAccountNice,
):
if x == 0: # owners account
currentAccountNice = currentAccountOriginal
print(PRINTLINE)
print("Now Working on " + currentAccountNice + "'s Current Series")
print(PRINTLINE)
workhorse(
sonarr_shows,
plex,
test_mode,
)
print(PRINTLINE)
else: # all other accounts
print(PRINTLINE)
print("Now Working on " + currentAccountNice + "'s Current Series")
print(PRINTLINE)

plex = try_plex_user(currentAccountOriginal, plex) # switch plex user

# break upon user failing
if plex != "failed":
workhorse(
sonarr_shows,
plex,
test_mode,
)
print(PRINTLINE)
else:
print("Failed to Access", currentAccountNice, "'s Account")
print(PRINTLINE)

return plex
2 changes: 1 addition & 1 deletion autoDownloader.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# gignsky 5.8.22 - TEMPLATE - AUTO - WITH MONITOR FUNCTION
# AUTO - WITH MONITOR FUNCTION
# automatic version of script that allows for scanning plex for in-progress shows from all plex.server users and requesting sonarr monitor and download the next season if the next season is not already downloaded or doesn't have any episodes downloaded already.

"""
Expand Down
64 changes: 29 additions & 35 deletions config.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,29 @@
def initialConfigs():
"""CONFIGURATION

Returns:
initial config variables
"""
# General
LOG_LEVEL = 1
# Only Full Season at this time. Perhaps 'First Episode' in the future?
DOWNLOAD_TARGET = "FULL_SEASON"

# START HERE

# Determines how many episodes before the end of the season a new season should be downloaded.
EPISODE_THRESHOLD = 2

# Plex
PLEX_URL = "http://IP_TO_PLEX_SERVER:32400/"
PLEX_TOKEN = "PLEX_TOKEN"
PLEX_TV_SHOWS_LIBRARY = "TV_SHOW_LIBRARY_NAME_FROM_PLEX"

# Sonarr
SONARR_URL = "http://IP_TO_SONARR:8989"
SONARR_API_KEY = "API_KEY"

return (
LOG_LEVEL,
EPISODE_THRESHOLD,
DOWNLOAD_TARGET,
PLEX_URL,
PLEX_TOKEN,
PLEX_TV_SHOWS_LIBRARY,
SONARR_URL,
SONARR_API_KEY,
)
"""CONFIGURATION

Returns:
initial config variables
"""

# START HERE

# Determines how many episodes before the end of the season a new season should be downloaded.
EPISODE_THRESHOLD = 2

# Plex
PLEX_URL = "http://IP_TO_PLEX_SERVER:32400/"
PLEX_TOKEN = "PLEX_TOKEN"
PLEX_TV_SHOWS_LIBRARY = "TV_SHOW_LIBRARY_NAME_FROM_PLEX"

# Sonarr
SONARR_URL = "http://IP_TO_SONARR:8989"
SONARR_API_KEY = "API_KEY"


# STATIC
# define printline
PRINTLINE = "============================================="

LOG_LEVEL = 1

# Only Full Season at this time. Perhaps 'First Episode' in the future?
DOWNLOAD_TARGET = "FULL_SEASON"
170 changes: 170 additions & 0 deletions logic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
from plexapi.exceptions import NotFound
from config import *
import sonarrHandler


def main(
sonarr_shows,
plex,
test_mode,
):
"""Primary Workthread that does the heavy lifting in terms of actually selecting and downloading episodes

Args:
from main()
"""
try:
tvshows = plex.library.section(PLEX_TV_SHOWS_LIBRARY)
print("Found Library '" + PLEX_TV_SHOWS_LIBRARY + "'")
except NotFound:
print("Library with name '" + PLEX_TV_SHOWS_LIBRARY + "' not found.")
return Exception("Nothing is currently in progress for this user.")

PlexTVShowsToCheck = {}

iterate = tvshows.search(None, None, None, "episode", inProgress=True)

for episode in iterate:
plex_show = episode.show()
# print("plex_show: ", plex_show)
plex_season = episode.season()
plex_episode = episode
plex_show_tvdb = plex_show_tvdb_CHECKER(plex_show)

# print("plex_show_tvbd: ", plex_show_tvdb)
# print("plex_show: " + str(plex_show.guids[2].id))

if not (plex_show_tvdb in PlexTVShowsToCheck):
PlexTVShowsToCheck[plex_show_tvdb] = {
"show": plex_show,
"season": plex_season,
"episode": plex_episode,
}
else:
if plex_season.index > PlexTVShowsToCheck[plex_show_tvdb]["season"].index:
# This episode is from a newer season than the existing one. We want the latest, so overwrite
PlexTVShowsToCheck[plex_show_tvdb] = {
"show": plex_show,
"season": plex_season,
"episode": plex_episode,
}
else:
if (
plex_season.index
== PlexTVShowsToCheck[plex_show_tvdb]["season"].index
):
if (
plex_episode.index
> PlexTVShowsToCheck[plex_show_tvdb]["episode"].index
):
# The episode is from the same season and has a higher number. We want the latest, so overwrite
PlexTVShowsToCheck[plex_show_tvdb] = {
"show": plex_show,
"season": plex_season,
"episode": plex_episode,
}

if len(PlexTVShowsToCheck) >= 1:
for tvdbstring in PlexTVShowsToCheck:
PlexTVShow = PlexTVShowsToCheck[tvdbstring]
plex_show = PlexTVShow["show"]
plex_season = PlexTVShow["season"]
plex_episode = PlexTVShow["episode"]

print(
"\nAnalyzing TV Show '"
+ plex_show.title
+ "' with latest in progress episode '"
+ plex_episode.title
+ "' ("
+ plex_season.title
+ ", episode "
+ str(plex_episode.index)
+ ")"
)
sonarr_show = False
for show in sonarr_shows:
if str(show["tvdbId"]) == plex_show_tvdb_CHECKER(plex_show):
sonarr_show = show

if not sonarr_show:
print("Could not match Sonarr show with Plex show. SKIPPING...")
continue

print(
" Matched Plex Show with Sonarr Show ("
+ sonarr_show["title"]
+ " with ID: "
+ str(sonarr_show["id"])
+ ")"
)
assumed_sonarr_season_number = plex_season.title
assumed_sonarr_season_number = int(
assumed_sonarr_season_number.replace("Season ", "")
)
print(
" Assumed Sonarr season match: "
+ str(assumed_sonarr_season_number)
)

try:
sonarr_season = sonarr_show["seasons"][
int(assumed_sonarr_season_number)
]
print(" Found current season on Sonarr.")
except IndexError:
print(" Can't match Sonarr Season. SKIPPING...")
continue

if assumed_sonarr_season_number == 1:
if plex_season.leafCount == 1:
print(
f"Current Season downloaded is first season in {plex_show} and inprogress episode is pilot. Downloading remaining episodes in this first season."
)
sonarr_next_season = sonarr_show["seasons"][1]
sonarrHandler.downloadNewEpisodes(
sonarr_show,
sonarr_next_season,
test_mode,
)
else:
# print("elsed nothing to report") # was used for testing purposes
status = sonarrHandler.not_first_season_checker(
sonarr_show,
assumed_sonarr_season_number,
plex_episode,
sonarr_season,
test_mode,
)
if status == "continue":
continue
else:
print("ALL GOOD!")

else:
status = sonarrHandler.not_first_season_checker(
sonarr_show,
assumed_sonarr_season_number,
plex_episode,
sonarr_season,
test_mode,
)
if status == "continue":
continue
else:
print("ALL GOOD!")

else:
print("NO in progress TV shows found.")


def plex_show_tvdb_CHECKER(plex_show):
"""Prevents end of index issues with some user accounts containing large histories"""
try:
x = str(plex_show.guids[2].id).replace("tvdb://", "")
# print("Index -- No Error")
return x
except:
x = str(plex_show.guids[1].id).replace("tvdb://", "")
# print("End of Index -- Due to Error")
return x
Loading