database and scheduling updates

Updated metadata filtering to use locally stored data
Updated database scans to download metadata to local database on update
Added rerun mode, random show sequential episode mode, range of ratings filtering and episode air date filtering
This commit is contained in:
Moe Fwacky
2021-06-15 23:19:16 -07:00
committed by GitHub
parent fbd86d2390
commit 1d33ff7d1b
5 changed files with 1111 additions and 364 deletions

View File

@@ -112,11 +112,27 @@ class PseudoChannel():
if correct_lib_name == "Movies": if correct_lib_name == "Movies":
sectionMedia = self.PLEX.library.section(section.title).all() sectionMedia = self.PLEX.library.section(section.title).all()
for i, media in enumerate(sectionMedia): for i, media in enumerate(sectionMedia):
self.db.add_movies_to_db(1, media.title, media.duration, media.key, section.title) fetchMedia = self.PLEX.fetchItem(media.key)
try:
genres = [genre.tag for genre in fetchMedia.genres]
except:
genres = ''
try:
actors = [actor.tag for actor in fetchMedia.actors]
except:
actors = ''
try:
collections = [collection.tag for collection in fetchMedia.collections]
except:
collections = ''
#actors = {}
#for actor in fetchMedia.actors:
# actors[actor.tag] = str(actor.id)
self.db.add_movies_to_db(media.ratingKey, media.title, media.duration, media.key, section.title, media.contentRating, media.summary, media.originallyAvailableAt, str(genres), str(actors), str(collections), media.studio)
self.print_progress( self.print_progress(
i + 1, i + 1,
len(sectionMedia), len(sectionMedia),
prefix = 'Progress '+section.title+": ", prefix = section.title+" "+str(i+1)+' of '+str(len(sectionMedia))+": ",
suffix = 'Complete ['+media.title+']', suffix = 'Complete ['+media.title+']',
bar_length = 40 bar_length = 40
) )
@@ -124,48 +140,79 @@ class PseudoChannel():
elif correct_lib_name == "TV Shows": elif correct_lib_name == "TV Shows":
sectionMedia = self.PLEX.library.section(section.title).all() sectionMedia = self.PLEX.library.section(section.title).all()
for i, media in enumerate(sectionMedia): for i, media in enumerate(sectionMedia):
fetchMedia = self.PLEX.fetchItem(media.key)
try:
genres = [genre.tag for genre in fetchMedia.genres]
except:
genres = ''
try:
actors = [actor.tag for actor in fetchMedia.actors]
except:
actors = ''
try:
similars = [similar.tag for similar in fetchMedia.similar]
except:
similars = ''
self.db.add_shows_to_db( self.db.add_shows_to_db(
2, media.ratingKey,
media.title, media.title,
media.duration if media.duration else 1, media.duration if media.duration else 1,
'', '',
'', media.originallyAvailableAt,
media.key, media.key,
section.title section.title,
media.contentRating,
str(genres),
str(actors),
str(similars),
media.studio
) )
#add all episodes of each tv show to episodes table self.print_progress(
i + 1,
len(sectionMedia),
prefix = 'TV Show '+str(i+1)+' of '+str(len(sectionMedia))+': ',
suffix = 'Complete ['+media.title[0:40]+']',
bar_length = 40
)
#add all episodes of each tv show to episodes table
for i, media in enumerate(sectionMedia):
episodes = self.PLEX.library.section(section.title).get(media.title).episodes() episodes = self.PLEX.library.section(section.title).get(media.title).episodes()
for j, episode in enumerate(episodes): for j, episode in enumerate(episodes):
duration = episode.duration duration = episode.duration
if duration: if duration:
self.db.add_episodes_to_db( self.db.add_episodes_to_db(
4, media.ratingKey,
episode.title, episode.title,
duration, duration,
episode.index, episode.index,
episode.parentIndex, episode.parentIndex,
media.title, media.title,
episode.key, episode.key,
section.title section.title,
episode.contentRating,
episode.originallyAvailableAt,
episode.summary
) )
else: else:
self.db.add_episodes_to_db( self.db.add_episodes_to_db(
4, episode.ratingKey,
episode.title, episode.title,
0, 0,
episode.index, episode.index,
episode.parentIndex, episode.parentIndex,
media.title, media.title,
episode.key, episode.key,
section.title section.title,
episode.contentRating,
episode.originallyAvailableAt,
episode.summary
) )
self.print_progress( self.print_progress(
j + 1, j + 1,
len(episodes), len(episodes),
prefix = 'Progress TV Show '+str(i+1)+' of '+str(len(sectionMedia))+': ', prefix = str(i+1)+' of '+str(len(sectionMedia))+" "+media.title+': ',
suffix = 'Complete ['+media.title+']', suffix = 'Complete ['+episode.title[0:40]+']',
bar_length = 40 bar_length = 40
) )
#print('') #print('')
@@ -177,8 +224,8 @@ class PseudoChannel():
self.print_progress( self.print_progress(
i + 1, i + 1,
media_length, media_length,
prefix = 'Progress '+section.title+":", prefix = section.title+" "+str(i+1)+' of '+str(len(sectionMedia))+":",
suffix = 'Complete['+media.title[0:12]+']', suffix = 'Complete['+media.title[0:40]+']',
bar_length = 40 bar_length = 40
) )
#print('') #print('')
@@ -187,14 +234,20 @@ class PseudoChannel():
playlists = self.PLEX.playlists() playlists = self.PLEX.playlists()
for i, playlist in enumerate(playlists): for i, playlist in enumerate(playlists):
duration_average = playlist.duration / playlist.leafCount duration_average = playlist.duration / playlist.leafCount
playlist_added = playlist.addedAt.strftime("%Y-%m-%d %H:%M:%S")
self.db.add_shows_to_db( self.db.add_shows_to_db(
2, playlist.ratingKey,
playlist.title, playlist.title,
duration_average, duration_average,
'', '',
'', playlist_added,
playlist.key, playlist.key,
playlist.type playlist.type,
'',
'',
'',
'',
''
) )
# add all entries of playlist to episodes table # add all entries of playlist to episodes table
episodes = self.PLEX.playlist(playlist.title).items() episodes = self.PLEX.playlist(playlist.title).items()
@@ -213,31 +266,37 @@ class PseudoChannel():
plTitle = episode.title + " ("+str(episode.year)+")" plTitle = episode.title + " ("+str(episode.year)+")"
if duration: if duration:
self.db.add_playlist_entries_to_db( self.db.add_playlist_entries_to_db(
5, episode.ratingKey,
plTitle, plTitle,
duration, duration,
eNo, eNo,
sNo, sNo,
playlist.title, playlist.title,
episode.key, episode.key,
sectionTitle sectionTitle,
episode.contentRating,
episode.originallyAvailableAt,
episode.summary
) )
else: else:
self.db.add_playlist_entries_to_db( self.db.add_playlist_entries_to_db(
5, episode.ratingKey,
episode.title, episode.title,
0, 0,
eNo, eNo,
sNo, sNo,
playlist.title, playlist.title,
episode.key, episode.key,
sectionTitle sectionTitle,
episode.contentRating,
episode.originallyAvailableAt,
episode.summary
) )
self.print_progress( self.print_progress(
j + 1, j + 1,
len(episodes), len(episodes),
prefix = 'Progress Playlist '+str(i+1)+' of '+str(len(playlists))+': ', prefix = 'Playlist '+str(i+1)+' of '+str(len(playlists))+': ',
suffix = 'Complete ['+playlist.title+']', suffix = 'Complete ['+playlist.title[0:40]+']',
bar_length = 40 bar_length = 40
) )
print('', end='\r') print('', end='\r')
@@ -310,7 +369,7 @@ class PseudoChannel():
def update_db_movies(self): def update_db_movies(self):
print("NOTICE: Updating Local Database, MOVIES ONLY") print("NOTICE: Updating Local Movies Database")
self.db.create_tables() self.db.create_tables()
libs_dict = config.plexLibraries libs_dict = config.plexLibraries
sections = self.PLEX.library.sections() sections = self.PLEX.library.sections()
@@ -320,7 +379,23 @@ class PseudoChannel():
if correct_lib_name == "Movies": if correct_lib_name == "Movies":
sectionMedia = self.PLEX.library.section(section.title).all() sectionMedia = self.PLEX.library.section(section.title).all()
for i, media in enumerate(sectionMedia): for i, media in enumerate(sectionMedia):
self.db.add_movies_to_db(1, media.title, media.duration, media.key, section.title) fetchMedia = self.PLEX.fetchItem(media.key)
try:
genres = [genre.tag for genre in fetchMedia.genres]
except:
genres = ''
try:
actors = [actor.tag for actor in fetchMedia.actors]
except:
actors = ''
try:
collections = [collection.tag for collection in fetchMedia.collections]
except:
collections = ''
#actors = {}
#for actor in fetchMedia.actors:
# actors[actor.tag] = str(actor.id)
self.db.add_movies_to_db(media.key.replace('/library/metadata/',''), media.title, media.duration, media.key, section.title, media.contentRating, media.summary, media.originallyAvailableAt, str(genres), str(actors), str(collections), media.studio)
self.print_progress( self.print_progress(
i + 1, i + 1,
len(sectionMedia), len(sectionMedia),
@@ -328,10 +403,6 @@ class PseudoChannel():
suffix = 'Complete ['+media.title+']', suffix = 'Complete ['+media.title+']',
bar_length = 40 bar_length = 40
) )
print('', end='\r')
sys.stdout.write("\033[K")
print('NOTICE: Movies Database Update Complete!')
print('')
def update_db_tv(self): def update_db_tv(self):
print("NOTICE: Updating Local Database, TV ONLY") print("NOTICE: Updating Local Database, TV ONLY")
@@ -670,7 +741,9 @@ class PseudoChannel():
section = entry[9] section = entry[9]
for key, val in weekday_dict.items(): for key, val in weekday_dict.items():
if str(entry[7]) in str(val) and int(weekno) == int(key): if str(entry[7]) in str(val) and int(weekno) == int(key):
media_id = entry[2]
if section == "TV Shows": if section == "TV Shows":
next_episode = None
try: try:
minmax = entry[4].split(",") minmax = entry[4].split(",")
min = int(minmax[0]) min = int(minmax[0])
@@ -684,177 +757,94 @@ class PseudoChannel():
max = int(minmax) max = int(minmax)
max = max * 60000 max = max * 60000
if str(entry[3]).lower() == "random": if str(entry[3]).lower() == "random":
media_id = 999
advance_episode = "no"
sections = self.PLEX.library.sections() sections = self.PLEX.library.sections()
shows_list = [] shows_list = []
libs_dict = config.plexLibraries libs_dict = config.plexLibraries
for theSection in sections: for theSection in sections:
for correct_lib_name, user_lib_name in libs_dict.items(): for correct_lib_name, user_lib_name in libs_dict.items():
if theSection.title.lower() in [x.lower() for x in user_lib_name]: if theSection.title.lower() in [x.lower() for x in user_lib_name]:
if correct_lib_name == "TV Shows" and entry[13] != "": if correct_lib_name == "TV Shows":
print("NOTICE: TV SHOW WITH XTRA ARGS FOUND") while next_episode is None:
shows = self.PLEX.library.section(theSection.title) print("----------------------------------")
xtra = '[]' shows = self.PLEX.library.section(theSection.title)
d = {} print("NOTICE: Getting Show That Matches Data Filters")
#thestr = entry[13] the_show = self.db.get_random_show_data("TV Shows",int(min),int(max),entry[15],entry[16],entry[17],entry[18],entry[19],entry[20])
if ";" in xtra: if (the_show == None):
xtra = entry[13].split(';') print("NOTICE: Failed to get shows with data filters, trying with less")
else: the_show = self.db.get_random_show_data("TV Shows",int(min),int(max),entry[15],None,None,None,entry[19],None)
if xtra != None: #the_show = self.db.get_shows(random.choice(shows_list).title)
xtra = str(entry[13]) + ';' try:
xtra = xtra.split(';') print("INFO: "+str(the_show[3]))
try: except:
for thestr in xtra: print("NOTICE: FAILED TO GET RANDOM SHOW")
print("INFO: ARGUMENT = "+thestr) if (the_show is None):
strsplit = thestr.split(':') print("ACTION: Getting random episode of random show")
if strsplit[0] == "decade": next_episode = self.db.get_random_episode_duration(int(min), int(max))
decade = strsplit[1] attempt = 1
lastdigit = 0 episode_duration = next_episode[4]
thestr = "year:" while episode_duration < min or episode_duration > max:
while lastdigit <= 9: print("NOTICE: EPISODE LENGTH OUTSIDE PARAMETERS")
thestr = thestr+decade[0]+decade[1]+decade[2]+str(lastdigit) print("ACTION: Getting random episode of random show")
lastdigit = lastdigit + 1 next_episode = self.db.get_random_episode_duration(int(min), int(max))
if lastdigit < 10: episode_duration = int(next_episode[4])
thestr = thestr+"," attempt = attempt + 1
print("INFO: ARGUMENT = "+thestr) if attempt > 1000:
#d.update(strsplit[0],strsplit[1]) episode_duration = max
elif strsplit[0] == "season": else:
xtraSeason = strsplit[1] episode_duration = int(next_episode[4])
thestr = "" print("INFO: Random Selection: "+next_episode[7]+" - S"+str(next_episode[6])+"E"+str(next_episode[5])+" - "+next_episode[3])
elif strsplit[0] == "episode": else:
xtraEpisode = strsplit[1] if entry[2] == 999:
thestr = "" media_id = 999
if thestr != "": print("ACTION: Choosing random episode of "+the_show[3].upper())
regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)") try:
d.update(regex.findall(thestr)) next_episode = self.db.get_random_episode_of_show_by_data(the_show[2],int(min),int(max),entry[15],entry[21].split(',')[0],entry[21].split(',')[1])
#d = dict(regex.findall(thestr)) except:
print(d) next_episode = self.db.get_random_episode_of_show_by_data(the_show[2],int(min),int(max),entry[15])
#turn values into a list elif entry[2] == 998:
for key, val in d.items(): media_id = 998
d[key] = val.split(',') if entry[14] == 1:
for show in shows.search(None, **d): print("ACTION: Choosing last episode of " +the_show[3].upper())
shows_list.append(show) advance_episode = "no"
except: next_episode = self.db.get_last_episode(the_show[2]) #get last episode
pass try:
if (len(shows_list) > 0): print("INFO: Scheduled: "+next_episode[7]+" - (S"+str(next_episode[6])+"E"+str(next_episode[5])+") "+next_episode[3])
#print shows_list except:
print("ACTION: Using xtra args to choose a random show") pass
the_show = self.db.get_shows(random.choice(shows_list).title) else:
else: print("ACTION: Choosing next episode of " +the_show[3].upper())
print("ACTION: Getting random show") advance_episode = "yes"
the_show = self.db.get_random_show_duration(int(min), int(max)) next_episode = self.db.get_next_episode(the_show[3]) #get next episode
try: try:
print("INFO: "+str(the_show[3])) print("INFO: Scheduled: "+next_episode[7]+" - (S"+str(next_episode[6])+"E"+str(next_episode[5])+") "+next_episode[3])
except: except:
print("NOTICE: FAILED TO GET RANDOM SHOW") pass
if (the_show is None): episode_duration = int(next_episode[4])
print("ACTION: Getting random episode of random show") show_title = next_episode[7]
next_episode = self.db.get_random_episode_duration(int(min), int(max)) xtraSeason = None
attempt = 1 xtraEpisode = None
episode_duration = next_episode[4] print("INFO: " + next_episode[7] + " - " + next_episode[3] + " (S" + str(next_episode[6]) + "E" + str(next_episode[5]) + ")")
while episode_duration < min or episode_duration > max:
print("NOTICE: EPISODE LENGTH OUTSIDE PARAMETERS")
print("ACTION: Getting random episode of random show")
next_episode = self.db.get_random_episode_duration(int(min), int(max))
episode_duration = int(next_episode[4])
attempt = attempt + 1
if attempt > 1000:
episode_duration = max
else:
episode_duration = int(next_episode[4])
print("INFO: Random Selection: "+next_episode[7]+" - S"+str(next_episode[6])+"E"+str(next_episode[5])+" - "+next_episode[3])
else:
i = 0
while i < 1000:
i += 1
try:
if xtraSeason is None and xtraEpisode is None:
print("ACTION: Choosing random episode of "+the_show[3].upper())
next_episode = self.db.get_random_episode_of_show(the_show[3])
elif xtraEpisode is None:
print("ACTION: Choosing random episode of "+the_show[3].upper()+" Season "+xtraSeason)
next_episode = self.db.get_specific_episode(the_show[3], xtraSeason)
elif xtraSeason is None:
print("ACTION: Choosing random episode of "+the_show[3].upper()+" Episode "+xtraEpisode)
next_episode = self.db.get_specific_episode(the_show[3], None, xtraEpisode)
else:
print("ACTION: Choosing random episode of "+the_show[3].upper()+" Season "+xtraSeason+" Episode "+xtraEpisode)
next_episode = self.db.get_specific_episode(the_show[3], xtraSeason, xtraEpisode)
print("INFO: Episode Selected: S"+str(next_episode[6])+"E"+str(next_episode[5])+" "+next_episode[3].upper())
break
except TypeError as e:
print (e)
if (len(shows_list) > 0):
#print shows_list
print("ACTION: Using xtra args to choose a random show")
the_show = self.db.get_shows(random.choice(shows_list).title)
else:
print("ACTION: Getting random show")
the_show = self.db.get_random_show_duration(int(min), int(max))
print("INFO: "+str(the_show[3]))
if (the_show is None):
print("ACTION: Getting random episode of random show")
next_episode = self.db.get_random_episode_duration(int(min), int(max))
continue
episode_duration = int(next_episode[4])
attempt = 1
while episode_duration < min or episode_duration > max or next_episode == None:
i = 0
while i < 1000:
i += 1
try:
print("NOTICE: DURATION OUTSIDE PARAMETERS")
if (len(shows_list) > 0):
print("ACTION: Using xtra args to choose a random show")
the_show = self.db.get_shows(random.choice(shows_list).title)
else:
print("ACTION: Getting random show")
the_show = self.db.get_random_show_duration(int(min), int(max))
print("INFO: "+str(the_show))
if xtraSeason is None and xtraEpisode is None:
print("ACTION: Choosing random episode of "+the_show[3].upper())
next_episode = self.db.get_random_episode_of_show(the_show[3])
elif xtraEpisode is None:
print("ACTION: Choosing random episode of "+the_show[3].upper()+" Season "+xtraSeason)
next_episode = self.db.get_specific_episode(the_show[3], xtraSeason)
elif xtraSeason is None:
print("ACTION: Choosing random episode of "+the_show[3].upper()+" Episode "+xtraEpisode)
next_episode = self.db.get_specific_episode(the_show[3], None, xtraEpisode)
else:
print("ACTION: Choosing random episode of "+the_show[3].upper()+" Season "+xtraSeason+" Episode "+xtraEpisode)
next_episode = self.db.get_specific_episode(the_show[3], xtraSeason, xtraEpisode)
print("INFO: Episode Selected: S"+str(next_episode[6])+"E"+str(next_episode[5])+" "+next_episode[3].upper())
break
except TypeError as e:
print(e)
if (len(shows_list) > 0):
#print shows_list
print("ACTION: Using xtra args to choose a random show")
the_show = self.db.get_shows(random.choice(shows_list).title)
else:
print("ACTION: Getting random show")
the_show = self.db.get_random_show_duration(int(min), int(max))
print("INFO: "+the_show[3])
if (the_show is None):
next_episode = self.db.get_random_episode_duration(int(min), int(max))
continue
attempt = attempt + 1
episode_duration = int(next_episode[4])
if attempt > 1000:
episode_duration = max
else:
episode_duration = int(next_episode[4])
show_title = next_episode[7]
xtraSeason = None
xtraEpisode = None
print("----------------------------------") print("----------------------------------")
elif entry[2] == 9999: elif entry[2] == 9999:
media_id = 9999
advance_episode = "no"
print("ACTION: Getting random episode of "+entry[3]) print("ACTION: Getting random episode of "+entry[3])
if entry[15] != None:
if entry[15][3] == '*':
print("INFO: Decade = " + str(entry[15]))
airDate=entry[15][0:3]
else:
print("INFO: Air Date = " + str(entry[15]))
airDate=entry[15]
else:
airDate=None
try: try:
next_episode = self.db.get_random_episode_of_show_alt(entry[3]) next_episode = self.db.get_random_episode_of_show_by_data_alt(entry[3], int(min), int(max), airDate, entry[21].split(',')[0], entry[21].split(',')[1])
except TypeError as e: except Exception as e:
print(e) print("ERROR: " + str(e))
next_episode = self.db.get_random_episode_of_show_alt(entry[3]) next_episode = self.db.get_random_episode_of_show_by_data_alt(entry[3], int(min), int(max), airDate)
print("INFO: Episode Selected: S"+str(next_episode[6])+"E"+str(next_episode[5])+" "+next_episode[3].upper()) print("INFO: Episode Selected: S"+str(next_episode[6])+"E"+str(next_episode[5])+" "+next_episode[3].upper())
show_title = next_episode[7] show_title = next_episode[7]
episode_duration = next_episode[4] episode_duration = next_episode[4]
@@ -870,7 +860,34 @@ class PseudoChannel():
episode_duration = next_episode[4] episode_duration = next_episode[4]
show_title = next_episode[7] show_title = next_episode[7]
else: else:
next_episode = self.db.get_next_episode(entry[3]) #get next episode print("----------------------------------")
if entry[14] == 1:
advance_episode = "no"
#check for same show in MEDIA list
for m in self.MEDIA:
try:
seriesTitle = m.show_series_title
except:
seriesTitle = None
if seriesTitle == entry[3]:
next_episode = self.db.get_episode_from_plexMediaID(m.plex_media_id)
if next_episode == None:
next_episode = self.db.get_last_episode_alt(entry[3]) #get last episode
else:
advance_episode = "yes"
#check for same show in MEDIA list
episodeID = None
for m in self.MEDIA:
try:
seriesTitle = m.show_series_title
except:
seriesTitle = None
if seriesTitle == entry[3] and m.media_id == 2:
episodeID = self.db.get_episode_id_alternate(m.plex_media_id,seriesTitle)[0]
if episodeID != None:
next_episode = self.db.get_next_episode_alt(seriesTitle, episodeID)
if next_episode == None:
next_episode = self.db.get_next_episode(entry[3]) #get next episode
try: try:
print("INFO: Scheduled: "+next_episode[7]+" - (S"+str(next_episode[6])+"E"+str(next_episode[5])+") "+next_episode[3]) print("INFO: Scheduled: "+next_episode[7]+" - (S"+str(next_episode[6])+"E"+str(next_episode[5])+") "+next_episode[3])
except: except:
@@ -889,12 +906,13 @@ class PseudoChannel():
entry[11], # time_shift entry[11], # time_shift
entry[12], # overlap_max entry[12], # overlap_max
#next_episode[8] if len(next_episode) >= 9 else '', # plex id #next_episode[8] if len(next_episode) >= 9 else '', # plex id
next_episode[8], #plex id next_episode[8], # plex_media_id
customSectionName, # custom lib name customSectionName, # custom lib name
2, #media_id media_id, #media_id
show_title, # show_series_title show_title, # show_series_title
next_episode[5], # episode_number next_episode[5], # episode_number
next_episode[6], # season_number next_episode[6], # season_number
advance_episode, # advance_episode
) )
self.MEDIA.append(episode) self.MEDIA.append(episode)
else: else:
@@ -932,14 +950,18 @@ class PseudoChannel():
xtra = xtra.split(';') xtra = xtra.split(';')
print(xtra) print(xtra)
try: try:
for thestr in xtra: """for thestr in xtra:
print ("INFO: "+thestr) print ("INFO: "+thestr)
regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)") regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)")
d.update(regex.findall(thestr)) d.update(regex.findall(thestr))
# turn values into list # turn values into list
for key, val in d.items(): for key, val in d.items():
d[key] = val.split(',') d[key] = val.split(',')"""
for movie in movies.search(None, **d): if entry[13] != "" and entry[13] != None:
movie_search = self.db.get_movies_xtra(correct_lib_name,int(min),int(max),xtra)
else:
movie_search = self.db.get_movies_data("Movies",int(min),int(max),entry[15],entry[16],entry[17],entry[18],entry[19],entry[20])
for movie in movie_search:
movies_list.append(movie) movies_list.append(movie)
except: except:
pass pass
@@ -947,26 +969,26 @@ class PseudoChannel():
movie_get = random.choice(movies_list) movie_get = random.choice(movies_list)
movies_list.remove(movie_get) movies_list.remove(movie_get)
try: try:
print("INFO: Movie Title - " + movie_get.title) print("INFO: Movie Title - " + movie_get[3])
the_movie = self.db.get_movie_by_id(movie_get.key) the_movie = self.db.get_movie_by_id(movie_get[6])
except Exception as e: except Exception as e:
print("ERROR: Key not found") print("ERROR: Key not found")
print(e) print(e)
print("INFO: " + movie_get.title) print("INFO: " + movie_get[3])
the_movie = self.db.get_movie(movie_get.title) the_movie = self.db.get_movie(movie_get[3])
movie_duration = the_movie[4] movie_duration = the_movie[4]
attempt = 1 attempt = 1
while int(movie_duration) < min or movie_duration > max: while int(movie_duration) < min or movie_duration > max:
movie_get = random.choice(movies_list) movie_get = random.choice(movies_list)
movies_list.remove(movie_get) movies_list.remove(movie_get)
try: try:
print("INFO: Movie Title - " + movie_get.title) print("INFO: Movie Title - " + movie_get[3])
the_movie = self.db.get_movie_by_id(movie_get.key) the_movie = self.db.get_movie_by_id(movie_get[6])
except Exception as e: except Exception as e:
print("ERROR: Key not found") print("ERROR: Key not found")
print(e) print(e)
print("INFO: " + movie_get.title) print("INFO: " + movie_get[3])
the_movie = self.db.get_movie(movie_get.title) the_movie = self.db.get_movie(movie_get[6])
attempt = attempt + 1 attempt = attempt + 1
if attempt > 500: if attempt > 500:
movie_duration = max movie_duration = max
@@ -976,7 +998,20 @@ class PseudoChannel():
self.db.update_movies_table_with_last_played_date(the_movie[3]) self.db.update_movies_table_with_last_played_date(the_movie[3])
else: else:
print("ERROR: xtra args not found, getting random movie") print("ERROR: xtra args not found, getting random movie")
the_movie = self.db.get_random_movie_duration(int(min), int(max)) movie_search = self.db.get_movies_data("Movies",int(min),int(max),None,None,None,None,entry[19],None)
for movie in movie_search:
if movie not in movies_list and movie[3] not in last_movie:
movies_list.append(movie)
movie_get = random.choice(movies_list)
movies_list.remove(movie_get)
try:
print("INFO: Movie Title - " + movie_get[3])
the_movie = self.db.get_movie_by_id(movie_get[6])
except Exception as e:
print("ERROR: Key not found")
print(e)
print("INFO: " + movie_get[3])
the_movie = self.db.get_movie(movie_get[6])
print("INFO: Movie Title - " + str(the_movie[3])) print("INFO: Movie Title - " + str(the_movie[3]))
movie_duration = the_movie[4] movie_duration = the_movie[4]
attempt = 1 attempt = 1
@@ -1032,89 +1067,71 @@ class PseudoChannel():
if theSection.title.lower() in [x.lower() for x in user_lib_name]: if theSection.title.lower() in [x.lower() for x in user_lib_name]:
if correct_lib_name == "Movies": if correct_lib_name == "Movies":
movies = self.PLEX.library.section(theSection.title) movies = self.PLEX.library.section(theSection.title)
if(entry[13] != '' or len(actors_list) > 0): # xtra params '''if(entry[13] != None or len(actors_list) > 0): # xtra params
xtra = [] xtra = []
try: try:
print("INFO: Movie Xtra Arguments: ", entry[13]) print("INFO: Movie Xtra Arguments: ", entry[13])
except: except:
print("INFO: Xtra Arguments Not Found") print("INFO: Xtra Arguments Not Found")
d = {} d = {}'''
if len(actors_list) > 0: if len(actors_list) > 0:
for actorName in actors_list: xtra_actors = []
xtra = [] if entry[17] != None and ',' in entry[17]:
if ";" in entry[13]: xtra_actors = entry[17].split(',')
xtra = entry[13].split(';') elif entry[17] != None and ',' not in entry[17]:
elif entry[13] != '': xtra_actors.append(entry[17])
xtra.append(str(entry[13])) for actorName in actors_list:
#xtra = xtra.split(';') the_actors = []
else: for xActor in xtra_actors:
xtra = [] print("INFO: xtra actor = " + xActor)
actorID = actors_list[actorName] the_actors.append(xActor)
print("----------------------------------") the_actors.append(actorName)
print("INFO: Actor from " + last_movie + " selected - " + actorName) aLoop = 1
try: actor_data = ''
#print("NOTICE: Appending " + actorName + " to xtra args") print("----------------------------------")
xtra.append("actor:"+str(actorID)) print("INFO: Actor from " + last_movie + " selected - " + actorName)
except: print("NOTICE: Executing movies search for matches")
#print("ERROR: Appending failed, creating new list with actor name") print("INFO: " + str(entry[15]) + ', ' + str(entry[16]) + ', ' + str(the_actors) + ', ' + str(entry[18]) + ', ' + str(entry[19]) + ', ' + str(entry[20]))
xtra = ["actor:"+str(actorID)] movie_search = self.db.get_movies_data("Movies",int(min),int(max),entry[15],entry[16],the_actors,entry[18],entry[19],entry[20])
print("INFO: xtra args: " + str(xtra)) print("INFO: " + str(len(movie_search)) + " results found")
try: #except Exception as e:
for thestr in xtra: #print(e)
#print ("INFO: "+thestr) for movie in movie_search:
regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)") if movie not in movies_list and movie[3] not in last_movie:
d.update(regex.findall(thestr)) print(str(movie[3]))
except Exception as e:
print("ERROR: " + str(e))
pass
#print("NOTICE: turning xtra values into a dict")
try:
for key, val in d.items():
d[key] = val.split(',')
except Exception as e:
print("ERROR: " + str(e))
pass
print("NOTICE: Executing movies search for matches")
try:
movie_search = movies.search(None, **d)
print("INFO: " + str(len(movie_search)) + " results found")
except Exception as e:
print(e)
for movie in movie_search:
if movie not in movies_list and movie.title not in last_movie:
print(str(movie.title))
movies_list.append(movie)
#print("INFO: Match Found - " + str(movie))
#for movie in movies.search(None, **d):
# movies_list.append(movie)
# print("INFO: Match Found - " + str(movie))
#except Exception as e:
# print("ERROR: " + str(e))
# pass
#print("INFO: Movies List: " + str(movies_list))
else:
print("NOTICE: No previous actor data, skipping...")
if ";" in entry[13]:
xtra = entry[13].split(';')
else:
if entry[13] != None:
xtra = str(entry[13]) + ';'
xtra = xtra.split(';')
print(xtra)
try:
for thestr in xtra:
print ("INFO: "+thestr)
regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)")
d.update(regex.findall(thestr))
# turn values into list
for key, val in d.items():
d[key] = val.split(',')
for movie in movies.search(None, **d):
movies_list.append(movie) movies_list.append(movie)
#print("INFO: Match Found - " + movie) #print("INFO: Match Found - " + str(movie))
except Exception as e: #for movie in movies.search(None, **d):
print("ERROR: " + str(e)) # movies_list.append(movie)
pass # print("INFO: Match Found - " + str(movie))
#except Exception as e:
# print("ERROR: " + str(e))
# pass
#print("INFO: Movies List: " + str(movies_list))
else:
print("NOTICE: No previous actor data, skipping...")
'''if ";" in entry[13]:
xtra = entry[13].split(';')
else:
if entry[13] != None:
xtra = str(entry[13]) + ';'
xtra = xtra.split(';')
print(xtra)'''
try:
"""for thestr in xtra:
print ("INFO: "+thestr)
regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)")
d.update(regex.findall(thestr))
# turn values into list
for key, val in d.items():
d[key] = val.split(',')"""
movie_search = self.db.get_movies_data("Movies",int(min),int(max),entry[15],entry[16],entry[17],entry[18],entry[19],entry[20])
for movie in movie_search:
movies_list.append(movie)
#print("INFO: Match Found - " + movie)
except Exception as e:
print("ERROR: " + str(e))
pass
#print(xtra) #print(xtra)
if (len(movies_list) > 0): if (len(movies_list) > 0):
@@ -1123,24 +1140,24 @@ class PseudoChannel():
movie_get = random.choice(movies_list) movie_get = random.choice(movies_list)
movies_list.remove(movie_get) movies_list.remove(movie_get)
try: try:
print("INFO: Movie Title - " + movie_get.title) print("INFO: Movie Title - " + movie_get[3])
the_movie = self.db.get_movie_by_id(movie_get.key) the_movie = self.db.get_movie_by_id(movie_get[6])
except Exception as e: except Exception as e:
print("ERROR: Key not found") print("ERROR: Key not found")
print(e) print(e)
print("INFO: " + movie_get.title) print("INFO: " + movie_get[3])
the_movie = self.db.get_movie(movie_get.title) the_movie = self.db.get_movie(movie_get[3])
attempt = 1 attempt = 1
while the_movie[6] in prev_movies and last_movie in the_movie[3] and attempt < 500: while the_movie[6] in prev_movies and last_movie in the_movie[3] and attempt < 500:
movie_get = random.choice(movies_list) movie_get = random.choice(movies_list)
try: try:
print("INFO: Movie Title - " + movie_get.title) print("INFO: Movie Title - " + movie_get[3])
the_movie = self.db.get_movie_by_id(movie_get.key) the_movie = self.db.get_movie_by_id(movie_get[6])
except Exception as e: except Exception as e:
print("ERROR: Key not found") print("ERROR: Key not found")
print(e) print(e)
print("INFO: " + movie_get.title) print("INFO: " + movie_get[3])
the_movie = self.db.get_movie(movie_get.title) the_movie = self.db.get_movie(movie_get[3])
attempt = attempt + 1 attempt = attempt + 1
movie_duration = the_movie[4] movie_duration = the_movie[4]
attempt = 1 attempt = 1
@@ -1149,13 +1166,13 @@ class PseudoChannel():
movie_get = random.choice(movies_list) movie_get = random.choice(movies_list)
movies_list.remove(movie_get) movies_list.remove(movie_get)
try: try:
print("INFO: Movie Title - " + movie_get.title) print("INFO: Movie Title - " + movie_get[3])
the_movie = self.db.get_movie_by_id(movie_get.key) the_movie = self.db.get_movie_by_id(movie_get[6])
except Exception as e: except Exception as e:
print("ERROR: Key not found") print("ERROR: Key not found")
print(e) print(e)
print("INFO: " + movie_get.title) print("INFO: " + movie_get[3])
the_movie = self.db.get_movie(movie_get.title) the_movie = self.db.get_movie(movie_get[3])
else: else:
the_movie = self.db.get_random_movie_duration(int(min), int(max)) the_movie = self.db.get_random_movie_duration(int(min), int(max))
print("ERROR: Falling back to random movie that fits in the duration window") print("ERROR: Falling back to random movie that fits in the duration window")
@@ -1168,29 +1185,29 @@ class PseudoChannel():
"""Updating movies table in the db with lastPlayedDate entry""" """Updating movies table in the db with lastPlayedDate entry"""
self.db.update_movies_table_with_last_played_date(the_movie[3]) self.db.update_movies_table_with_last_played_date(the_movie[3])
else: else:
print("----------------------------------")
print("ERROR: No movies found, re-rolling without xtra args") print("ERROR: No movies found, re-rolling without xtra args")
d = {} d = {}
if len(actors_list) > 0: if len(actors_list) > 0:
for actorName in actors_list: for actorName in actors_list:
actorID = actors_list[actorName] actorID = actorName
print("INFO: Actor from " + last_movie + " selected - " + actorName) print("INFO: Actor from " + last_movie + " selected - " + actorName)
try: try:
xtra = xtra.append("actor:"+str(actorID)) xtra = xtra.append("actor:"+str(actorID))
except: except:
xtra = ["actor:"+str(actorID)] xtra = ["actor:"+str(actorID)]
try: try:
for thestr in xtra: """for thestr in xtra:
print ("INFO: "+thestr) print ("INFO: "+thestr)
regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)") regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)")
d.update(regex.findall(thestr)) d.update(regex.findall(thestr))
# turn values into list # turn values into list
for key, val in d.items(): for key, val in d.items():
d[key] = val.split(',') d[key] = val.split(',')"""
movie_search = movies.search(None, **d) movie_search = self.db.get_movies_data("Movies",int(min),int(max),None,None,actor_data,None,entry[19],None)
#movie_search = movies.search(None, **d)
for movie in movie_search: for movie in movie_search:
print(str(movie.title)) if movie not in movies_list and movie[3] not in last_movie:
if movie not in movies_list and movie.title not in last_movie:
print(str(movie.title))
movies_list.append(movie) movies_list.append(movie)
#print("INFO: Match Found - " + movie) #print("INFO: Match Found - " + movie)
except Exception as e: except Exception as e:
@@ -1204,25 +1221,25 @@ class PseudoChannel():
movie_get = random.choice(movies_list) movie_get = random.choice(movies_list)
movies_list.remove(movie_get) movies_list.remove(movie_get)
try: try:
print("INFO: Movie Title - " + movie_get.title) print("INFO: Movie Title - " + movie_get[3])
the_movie = self.db.get_movie_by_id(movie_get.key) the_movie = self.db.get_movie_by_id(movie_get[6])
except Exception as e: except Exception as e:
print("ERROR: Key not found") print("ERROR: Key not found")
print(e) print(e)
print("INFO: " + movie_get.title) print("INFO: " + movie_get[3])
the_movie = self.db.get_movie(movie_get.title) the_movie = self.db.get_movie(movie_get[3])
attempt = 1 attempt = 1
while the_movie[6] in prev_movies and last_movie in the_movie[3]and attempt < 500: while the_movie[6] in prev_movies and last_movie in the_movie[3] and attempt < 500:
movie_get = random.choice(movies_list) movie_get = random.choice(movies_list)
movies_list.remove(movie_get) movies_list.remove(movie_get)
try: try:
print("INFO: Movie Title - " + movie_get.title) print("INFO: Movie Title - " + movie_get[3])
the_movie = self.db.get_movie_by_id(movie_get.key) the_movie = self.db.get_movie_by_id(movie_get[6])
except Exception as e: except Exception as e:
print("ERROR: Key not found") print("ERROR: Key not found")
print(e) print(e)
print("INFO: " + movie_get.title) print("INFO: " + movie_get[3])
the_movie = self.db.get_movie(movie_get.title) the_movie = self.db.get_movie(movie_get[6])
attempt = attempt + 1 attempt = attempt + 1
attempt = 1 attempt = 1
movie_duration = the_movie[4] movie_duration = the_movie[4]
@@ -1235,13 +1252,13 @@ class PseudoChannel():
print(e) print(e)
movie_get = random.choice(movies_list) movie_get = random.choice(movies_list)
try: try:
print("INFO: Movie Title - " + movie_get.title) print("INFO: Movie Title - " + movie_get[3])
the_movie = self.db.get_movie_by_id(movie_get.key) the_movie = self.db.get_movie_by_id(movie_get[6])
except Exception as e: except Exception as e:
print("ERROR: Key not found") print("ERROR: Key not found")
print(e) print(e)
print("INFO: " + movie_get.title) print("INFO: " + movie_get[3])
the_movie = self.db.get_movie(movie_get.title) the_movie = self.db.get_movie(movie_get[3])
else: else:
the_movie = self.db.get_random_movie_duration(int(min), int(max)) the_movie = self.db.get_random_movie_duration(int(min), int(max))
print("ERROR: Falling back to random movie that fits in the duration window") print("ERROR: Falling back to random movie that fits in the duration window")
@@ -1253,8 +1270,32 @@ class PseudoChannel():
movie_duration = the_movie[4] movie_duration = the_movie[4]
else: else:
print("ERROR: Kevin Bacon Mode failed to find a match, selecting random movie") print("ERROR: Kevin Bacon Mode failed to find a match, selecting random movie")
the_movie = self.db.get_random_movie_duration(int(min), int(max)) movies_list = []
movie_search = self.db.get_movies_data("Movies",int(min),int(max),entry[14],entry[15],entry[16],entry[17],entry[18],entry[19])
for movie in movie_search:
if movie not in movies_list and movie[3] not in last_movie:
movies_list.append(movie)
if len(movies_list) < 1:
print("ERROR: xtra args not found, getting random movie")
movie_search = self.db.get_movies_data("Movies",int(min),int(max),None,None,None,None,entry[19],None)
try:
for movie in movie_search:
if movie not in movies_list and movie[3] not in last_movie:
movies_list.append(movie)
except:
movies_list.append(movie)
movie_get = random.choice(movies_list)
movies_list.remove(movie_get)
try:
print("INFO: Movie Title - " + movie_get[3])
the_movie = self.db.get_movie_by_id(movie_get[6])
except Exception as e:
print("ERROR: Key not found")
print(e)
print("INFO: " + movie_get[3])
the_movie = self.db.get_movie(movie_get[6])
print("INFO: Movie Title - " + str(the_movie[3])) print("INFO: Movie Title - " + str(the_movie[3]))
print("----------------------------------")
movie_duration = the_movie[4] movie_duration = the_movie[4]
attempt = 1 attempt = 1
while int(movie_duration) < min or movie_duration > max: while int(movie_duration) < min or movie_duration > max:
@@ -1285,6 +1326,7 @@ class PseudoChannel():
print("NOTICE: Movie Selected - " + the_movie[3]) print("NOTICE: Movie Selected - " + the_movie[3])
#get plex metadata #get plex metadata
plex_movie = self.PLEX.fetchItem(the_movie[6]) plex_movie = self.PLEX.fetchItem(the_movie[6])
last_data = ""
if str(entry[3]).lower() == "kevinbacon": if str(entry[3]).lower() == "kevinbacon":
actors_list_old = actors_list actors_list_old = actors_list
actors_list = {} actors_list = {}
@@ -1315,7 +1357,7 @@ class PseudoChannel():
the_movie[6], # plex id the_movie[6], # plex id
the_movie[7], # custom lib name the_movie[7], # custom lib name
media_id, # media_id media_id, # media_id
last_data # show_series_title (for storing kevin bacon data) last_data # notes (for storing kevin bacon data)
) )
self.MEDIA.append(movie) self.MEDIA.append(movie)
else: else:
@@ -1388,6 +1430,8 @@ class PseudoChannel():
self.db.add_media_to_daily_schedule(commercial) self.db.add_media_to_daily_schedule(commercial)
self.db.add_media_to_daily_schedule(entry) self.db.add_media_to_daily_schedule(entry)
previous_episode = entry previous_episode = entry
if entry.custom_section_name == "TV Shows" and entry.advance_episode != "no":
self.db.update_shows_table_with_last_episode(entry.show_series_title, entry.plex_media_id)
elif entry.is_strict_time.lower() == "secondary": #This mode starts a show "already in progress" if the previous episode or movie runs past the start time of this one elif entry.is_strict_time.lower() == "secondary": #This mode starts a show "already in progress" if the previous episode or movie runs past the start time of this one
print("INFO Pre-empt Allowed: {}".format(str(entry.title))) print("INFO Pre-empt Allowed: {}".format(str(entry.title)))
try: try:
@@ -1429,6 +1473,8 @@ class PseudoChannel():
self.db.add_media_to_daily_schedule(commercial) self.db.add_media_to_daily_schedule(commercial)
self.db.add_media_to_daily_schedule(entry) self.db.add_media_to_daily_schedule(entry)
previous_episode = entry previous_episode = entry
if entry.custom_section_name == "TV Shows" and entry.advance_episode != "no":
self.db.update_shows_table_with_last_episode(entry.show_series_title, entry.plex_media_id)
else: else:
try: try:
print("INFO: Variable Time: {}".format(str(entry.title).encode(sys.stdout.encoding, errors='replace'))) print("INFO: Variable Time: {}".format(str(entry.title).encode(sys.stdout.encoding, errors='replace')))
@@ -1458,10 +1504,13 @@ class PseudoChannel():
self.db.add_media_to_daily_schedule(commercial) self.db.add_media_to_daily_schedule(commercial)
self.db.add_media_to_daily_schedule(entry) self.db.add_media_to_daily_schedule(entry)
previous_episode = entry previous_episode = entry
if entry.custom_section_name == "TV Shows" and entry.advance_episode != "no":
self.db.update_shows_table_with_last_episode(entry.show_series_title, entry.plex_media_id)
else: else:
self.db.add_media_to_daily_schedule(entry) self.db.add_media_to_daily_schedule(entry)
previous_episode = entry previous_episode = entry
if entry.custom_section_name == "TV Shows" and entry.advance_episode != "no":
self.db.update_shows_table_with_last_episode(entry.show_series_title, entry.plex_media_id)
if self.USING_COMMERCIAL_INJECTION: if self.USING_COMMERCIAL_INJECTION:
list_of_commercials = self.commercials.get_commercials_to_place_between_media( list_of_commercials = self.commercials.get_commercials_to_place_between_media(
previous_episode, previous_episode,

View File

@@ -36,6 +36,7 @@ class Episode(Media):
show_series_title, show_series_title,
episode_number, episode_number,
season_number, season_number,
advance_episode
): ):
super(Episode, self).__init__( super(Episode, self).__init__(
@@ -56,3 +57,4 @@ class Episode(Media):
self.show_series_title = show_series_title self.show_series_title = show_series_title
self.episode_number = episode_number self.episode_number = episode_number
self.season_number = season_number self.season_number = season_number
self.advance_episode = advance_episode

View File

@@ -30,7 +30,7 @@ class Movie(Media):
plex_media_id, plex_media_id,
custom_section_name, custom_section_name,
media_id, media_id,
show_series_title notes,
): ):
super(Movie, self).__init__( super(Movie, self).__init__(
@@ -48,4 +48,4 @@ class Movie(Media):
media_id media_id
) )
self.show_series_title = show_series_title self.notes = notes

View File

@@ -3,6 +3,7 @@
import sqlite3 import sqlite3
import datetime import datetime
import time import time
import random
class PseudoChannelDatabase(): class PseudoChannelDatabase():
@@ -20,7 +21,7 @@ class PseudoChannelDatabase():
self.cursor.execute('CREATE TABLE IF NOT EXISTS ' self.cursor.execute('CREATE TABLE IF NOT EXISTS '
'movies(id INTEGER PRIMARY KEY AUTOINCREMENT, ' 'movies(id INTEGER PRIMARY KEY AUTOINCREMENT, '
'unix INTEGER, mediaID INTEGER, title TEXT, duration INTEGER, ' 'unix INTEGER, mediaID INTEGER, title TEXT, duration INTEGER, '
'lastPlayedDate TEXT, plexMediaID TEXT, customSectionName Text)') 'lastPlayedDate TEXT, plexMediaID TEXT, customSectionName Text, rating TEXT, summary TEXT, releaseYear TEXT, genres TEXT, actors TEXT, collections TEXT, studio TEXT)')
self.cursor.execute('CREATE TABLE IF NOT EXISTS ' self.cursor.execute('CREATE TABLE IF NOT EXISTS '
'videos(id INTEGER PRIMARY KEY AUTOINCREMENT, ' 'videos(id INTEGER PRIMARY KEY AUTOINCREMENT, '
'unix INTEGER, mediaID INTEGER, title TEXT, duration INTEGER, plexMediaID TEXT, customSectionName Text)') 'unix INTEGER, mediaID INTEGER, title TEXT, duration INTEGER, plexMediaID TEXT, customSectionName Text)')
@@ -30,11 +31,11 @@ class PseudoChannelDatabase():
self.cursor.execute('CREATE TABLE IF NOT EXISTS ' self.cursor.execute('CREATE TABLE IF NOT EXISTS '
'shows(id INTEGER PRIMARY KEY AUTOINCREMENT, ' 'shows(id INTEGER PRIMARY KEY AUTOINCREMENT, '
'unix INTEGER, mediaID INTEGER, title TEXT, duration INTEGER, ' 'unix INTEGER, mediaID INTEGER, title TEXT, duration INTEGER, '
'lastEpisodeTitle TEXT, fullImageURL TEXT, plexMediaID TEXT, customSectionName Text)') 'lastEpisodeTitle TEXT, premierDate TEXT, plexMediaID TEXT, customSectionName Text, rating TEXT, genres TEXT, actors TEXT, similar TEXT, studio TEXT)')
self.cursor.execute('CREATE TABLE IF NOT EXISTS ' self.cursor.execute('CREATE TABLE IF NOT EXISTS '
'episodes(id INTEGER PRIMARY KEY AUTOINCREMENT, ' 'episodes(id INTEGER PRIMARY KEY AUTOINCREMENT, '
'unix INTEGER, mediaID INTEGER, title TEXT, duration INTEGER, ' 'unix INTEGER, mediaID INTEGER, title TEXT, duration INTEGER, '
'episodeNumber INTEGER, seasonNumber INTEGER, showTitle TEXT, plexMediaID TEXT, customSectionName Text)') 'episodeNumber INTEGER, seasonNumber INTEGER, showTitle TEXT, plexMediaID TEXT, customSectionName Text, rating TEXT, airDate TEXT, summary TEXT)')
self.cursor.execute('CREATE TABLE IF NOT EXISTS ' self.cursor.execute('CREATE TABLE IF NOT EXISTS '
'commercials(id INTEGER PRIMARY KEY AUTOINCREMENT, unix INTEGER, ' 'commercials(id INTEGER PRIMARY KEY AUTOINCREMENT, unix INTEGER, '
'mediaID INTEGER, title TEXT, duration INTEGER, plexMediaID TEXT, customSectionName Text)') 'mediaID INTEGER, title TEXT, duration INTEGER, plexMediaID TEXT, customSectionName Text)')
@@ -42,12 +43,12 @@ class PseudoChannelDatabase():
'schedule(id INTEGER PRIMARY KEY AUTOINCREMENT, unix INTEGER, ' 'schedule(id INTEGER PRIMARY KEY AUTOINCREMENT, unix INTEGER, '
'mediaID INTEGER, title TEXT, duration INTEGER, startTime TEXT, ' 'mediaID INTEGER, title TEXT, duration INTEGER, startTime TEXT, '
'endTime TEXT, dayOfWeek TEXT, startTimeUnix INTEGER, section TEXT, ' 'endTime TEXT, dayOfWeek TEXT, startTimeUnix INTEGER, section TEXT, '
'strictTime TEXT, timeShift TEXT, overlapMax TEXT, xtra TEXT)') 'strictTime TEXT, timeShift TEXT, overlapMax TEXT, xtra TEXT, rerun INTEGER, year INTEGER, genres TEXT, actors TEXT, collections TEXT, rating TEXT, studio TEXT, seasonEpisode TEXT)')
self.cursor.execute('CREATE TABLE IF NOT EXISTS ' self.cursor.execute('CREATE TABLE IF NOT EXISTS '
'daily_schedule(id INTEGER PRIMARY KEY AUTOINCREMENT, unix INTEGER, ' 'daily_schedule(id INTEGER PRIMARY KEY AUTOINCREMENT, unix INTEGER, '
'mediaID INTEGER, title TEXT, episodeNumber INTEGER, seasonNumber INTEGER, ' 'mediaID INTEGER, title TEXT, episodeNumber INTEGER, seasonNumber INTEGER, '
'showTitle TEXT, duration INTEGER, startTime TEXT, endTime TEXT, ' 'showTitle TEXT, duration INTEGER, startTime TEXT, endTime TEXT, '
'dayOfWeek TEXT, sectionType TEXT, plexMediaID TEXT, customSectionName TEXT)') 'dayOfWeek TEXT, sectionType TEXT, plexMediaID TEXT, customSectionName TEXT, notes TEXT)')
self.cursor.execute('CREATE TABLE IF NOT EXISTS ' self.cursor.execute('CREATE TABLE IF NOT EXISTS '
'app_settings(id INTEGER PRIMARY KEY AUTOINCREMENT, version TEXT)') 'app_settings(id INTEGER PRIMARY KEY AUTOINCREMENT, version TEXT)')
#index #index
@@ -91,7 +92,7 @@ class PseudoChannelDatabase():
'daily_schedule(id INTEGER PRIMARY KEY AUTOINCREMENT, unix INTEGER, ' 'daily_schedule(id INTEGER PRIMARY KEY AUTOINCREMENT, unix INTEGER, '
'mediaID INTEGER, title TEXT, episodeNumber INTEGER, seasonNumber INTEGER, ' 'mediaID INTEGER, title TEXT, episodeNumber INTEGER, seasonNumber INTEGER, '
'showTitle TEXT, duration INTEGER, startTime TEXT, endTime TEXT, ' 'showTitle TEXT, duration INTEGER, startTime TEXT, endTime TEXT, '
'dayOfWeek TEXT, sectionType TEXT, plexMediaID TEXT, customSectionName TEXT)') 'dayOfWeek TEXT, sectionType TEXT, plexMediaID TEXT, customSectionName TEXT, notes TEXT)')
self.conn.commit() self.conn.commit()
def remove_all_scheduled_items(self): def remove_all_scheduled_items(self):
@@ -125,13 +126,20 @@ class PseudoChannelDatabase():
title, title,
duration, duration,
plexMediaID, plexMediaID,
customSectionName): customSectionName,
rating,
summary,
releaseYear,
genres,
actors,
collections,
studio):
unix = int(time.time()) unix = int(time.time())
try: try:
self.cursor.execute("REPLACE INTO movies " self.cursor.execute("REPLACE INTO movies "
"(unix, mediaID, title, duration, plexMediaID, customSectionName) VALUES (?, ?, ?, ?, ?, ?)", "(unix, mediaID, title, duration, plexMediaID, customSectionName, rating, summary, releaseYear, genres, actors, collections, studio) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(unix, mediaID, title, duration, plexMediaID, customSectionName)) (unix, mediaID, title, duration, plexMediaID, customSectionName, rating, summary, releaseYear, genres, actors, collections, studio))
self.conn.commit() self.conn.commit()
# Catch the exception # Catch the exception
except Exception as e: except Exception as e:
@@ -166,15 +174,20 @@ class PseudoChannelDatabase():
title, title,
duration, duration,
lastEpisodeTitle, lastEpisodeTitle,
fullImageURL, premierDate,
plexMediaID, plexMediaID,
customSectionName): customSectionName,
rating,
genres,
actors,
similar,
studio):
unix = int(time.time()) unix = int(time.time())
try: try:
self.cursor.execute("INSERT OR IGNORE INTO shows " self.cursor.execute("INSERT OR IGNORE INTO shows "
"(unix, mediaID, title, duration, lastEpisodeTitle, fullImageURL, plexMediaID, customSectionName) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", "(unix, mediaID, title, duration, lastEpisodeTitle, premierDate, plexMediaID, customSectionName, rating, genres, actors, similar, studio) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(unix, mediaID, title, duration, lastEpisodeTitle, fullImageURL, plexMediaID, customSectionName)) (unix, mediaID, title, duration, lastEpisodeTitle, premierDate, plexMediaID, customSectionName, rating, genres, actors, similar, studio))
self.conn.commit() self.conn.commit()
# Catch the exception # Catch the exception
except Exception as e: except Exception as e:
@@ -191,13 +204,16 @@ class PseudoChannelDatabase():
seasonNumber, seasonNumber,
showTitle, showTitle,
plexMediaID, plexMediaID,
customSectionName): customSectionName,
rating,
airDate,
summary):
unix = int(time.time()) unix = int(time.time())
try: try:
self.cursor.execute("INSERT INTO episodes " self.cursor.execute("INSERT INTO episodes "
"(unix, mediaID, title, duration, episodeNumber, seasonNumber, showTitle, plexMediaID, customSectionName) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", "(unix, mediaID, title, duration, episodeNumber, seasonNumber, showTitle, plexMediaID, customSectionName, rating, airDate, summary) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(unix, mediaID, title, duration, episodeNumber, seasonNumber, showTitle, plexMediaID, customSectionName)) (unix, mediaID, title, duration, episodeNumber, seasonNumber, showTitle, plexMediaID, customSectionName, rating, airDate, summary))
self.conn.commit() self.conn.commit()
# Catch the exception # Catch the exception
except Exception as e: except Exception as e:
@@ -214,13 +230,16 @@ class PseudoChannelDatabase():
seasonNumber, seasonNumber,
showTitle, showTitle,
plexMediaID, plexMediaID,
customSectionName): customSectionName,
rating,
airDate,
summary):
unix = int(time.time()) unix = int(time.time())
try: try:
self.cursor.execute("REPLACE INTO episodes " self.cursor.execute("REPLACE INTO episodes "
"(unix, mediaID, title, duration, episodeNumber, seasonNumber, showTitle, plexMediaID, customSectionName) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", "(unix, mediaID, title, duration, episodeNumber, seasonNumber, showTitle, plexMediaID, customSectionName, rating, airDate, summary) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(unix, mediaID, title, duration, episodeNumber, seasonNumber, showTitle, plexMediaID, customSectionName)) (unix, mediaID, title, duration, episodeNumber, seasonNumber, showTitle, plexMediaID, customSectionName, rating, airDate, summary))
self.conn.commit() self.conn.commit()
# Catch the exception # Catch the exception
except Exception as e: except Exception as e:
@@ -262,13 +281,21 @@ class PseudoChannelDatabase():
strictTime, strictTime,
timeShift, timeShift,
overlapMax, overlapMax,
xtra): xtra,
rerun,
year,
genres,
actors,
collections,
rating,
studio,
seasonEpisode):
unix = int(time.time()) unix = int(time.time())
try: try:
self.cursor.execute("REPLACE INTO schedule " self.cursor.execute("REPLACE INTO schedule "
"(unix, mediaID, title, duration, startTime, endTime, dayOfWeek, startTimeUnix, section, strictTime, timeShift, overlapMax, xtra) " "(unix, mediaID, title, duration, startTime, endTime, dayOfWeek, startTimeUnix, section, strictTime, timeShift, overlapMax, xtra, rerun, year, genres, actors, collections, rating, studio, seasonEpisode) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(unix, mediaID, title, duration, startTime, endTime, dayOfWeek, startTimeUnix, section, strictTime, timeShift, overlapMax, xtra)) (unix, mediaID, title, duration, startTime, endTime, dayOfWeek, startTimeUnix, section, strictTime, timeShift, overlapMax, xtra, rerun, year, genres, actors, collections, rating, studio, seasonEpisode))
self.conn.commit() self.conn.commit()
# Catch the exception # Catch the exception
except Exception as e: except Exception as e:
@@ -289,15 +316,16 @@ class PseudoChannelDatabase():
dayOfWeek, dayOfWeek,
sectionType, sectionType,
plexMediaID, plexMediaID,
customSectionName customSectionName,
notes
): ):
unix = int(time.time()) unix = int(time.time())
try: try:
self.cursor.execute("INSERT OR REPLACE INTO daily_schedule " self.cursor.execute("INSERT OR REPLACE INTO daily_schedule "
"(unix, mediaID, title, episodeNumber, seasonNumber, " "(unix, mediaID, title, episodeNumber, seasonNumber, "
"showTitle, duration, startTime, endTime, dayOfWeek, sectionType, plexMediaID, customSectionName) " "showTitle, duration, startTime, endTime, dayOfWeek, sectionType, plexMediaID, customSectionName, notes) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
( (
unix, unix,
mediaID, mediaID,
@@ -311,7 +339,8 @@ class PseudoChannelDatabase():
dayOfWeek, dayOfWeek,
sectionType, sectionType,
plexMediaID, plexMediaID,
customSectionName customSectionName,
notes
)) ))
self.conn.commit() self.conn.commit()
# Catch the exception # Catch the exception
@@ -330,10 +359,12 @@ class PseudoChannelDatabase():
#print(str("{}: {} - {}".format(media.start_time, media.title, media.custom_section_name)).encode('UTF-8')) #print(str("{}: {} - {}".format(media.start_time, media.title, media.custom_section_name)).encode('UTF-8'))
except: except:
print("ERROR: Not outputting media info due to ascii code issues.") print("ERROR: Not outputting media info due to ascii code issues.")
if media.media_id == 112:
notes = media.notes
else:
notes = ""
if media.__class__.__name__ == "Episode": if media.__class__.__name__ == "Episode":
seriesTitle = media.show_series_title seriesTitle = media.show_series_title
elif media.media_id == 112:
seriesTitle = media.show_series_title
else: else:
seriesTitle = '' seriesTitle = ''
self.add_daily_schedule_to_db( self.add_daily_schedule_to_db(
@@ -348,7 +379,8 @@ class PseudoChannelDatabase():
media.day_of_week, media.day_of_week,
media.section_type, media.section_type,
media.plex_media_id, media.plex_media_id,
media.custom_section_name media.custom_section_name,
notes
) )
def import_shows_table_by_row( def import_shows_table_by_row(
@@ -435,6 +467,11 @@ class PseudoChannelDatabase():
self.cursor.execute(sql1, (lastEpisodeTitle, '%'+showTitle+'%', )) self.cursor.execute(sql1, (lastEpisodeTitle, '%'+showTitle+'%', ))
self.conn.commit() self.conn.commit()
def update_shows_table_with_last_episode_by_id(self, showKey, lastEpisodeKey):
sql1 = "UPDATE shows SET lastEpisodeTitle = ? WHERE plexMediaID LIKE ? COLLATE NOCASE"
self.cursor.execute(sql1, (lastEpisodeKey, showKey, ))
self.conn.commit()
def update_movies_table_with_last_played_date(self, movieTitle): def update_movies_table_with_last_played_date(self, movieTitle):
now = datetime.datetime.now() now = datetime.datetime.now()
@@ -558,6 +595,207 @@ class PseudoChannelDatabase():
datalist = list(self.cursor.fetchall()) datalist = list(self.cursor.fetchall())
return datalist return datalist
def get_movies_xtra(self,min,max,xtra=None):
xtraArgs = ['rating','releaseYear','decade','genre','actor','collection','studio']
xtraDict = {}
xtraDict['rating']=None
xtraDict['release']=None
xtraDict['decade']=None
xtraDict['genre']=None
xtraDict['actor']=None
xtraDict['collection']=None
xtraDict['studio']=None
print("INFO: xtra = " + str(xtra))
if xtra != None:
for x in xtra:
x = x.replace("'",r"''")
x = x.replace('"',r'""')
x = x.split(':')
if x[0] in xtraArgs and x[1] != None:
xtraDict[x[0]] = []
if ',' in x[1]:
data = x[1].split(',')
for eachArg in data:
xtraDict[x[0]].append(eachArg)
else:
xtraDict[x[0]].append(x[1])
cursor_execute = "SELECT * FROM movies WHERE (duration BETWEEN "+str(min)+" and "+str(max)+")"
if xtraDict['rating'] != None:
cursor_execute = cursor_execute + "and rating LIKE \""+xtraDict['rating'][0]+"\""
if xtraDict['release'] != None:
cursor_execute = cursor_execute + " and releaseYear LIKE "+str(xtraDict['release'][0])+"\""
elif xtraDict['decade'] != None:
dec = str(xtraDict['decade'][0][0:3])
cursor_execute = cursor_execute + "and releaseYear LIKE \""+dec+"%\""
if xtraDict['genre'] != None:
for g in xtraDict['genre']:
if g != '':
cursor_execute = cursor_execute + " and genres LIKE \"%" + g + "%\""
if xtraDict['actor'] != None:
for a in xtraDict['actor']:
if a != '':
cursor_execute = cursor_execute + " and (actors LIKE \"%"+a+"%\")"
if xtraDict['collection'] != None:
for a in xtraDict['collection']:
if a != '':
cursor_execute = cursor_execute + " and (collections LIKE \"%"+a+"%\")"
if xtraDict['studio'] != None:
cursor_execute = cursor_execute + "and studio LIKE \"%"+xtraDict['studio'][0]+"%\""
cursor_execute = cursor_execute + " ORDER BY date(lastPlayedDate) ASC"
print("ACTION: " + cursor_execute)
self.cursor.execute(cursor_execute)
datalist = self.cursor.fetchall()
return datalist
def get_movies_data(self,section,min,max,year,genres,actors,collections,rating,studios):
print("INFO: " + str(min) + ', ' + str(max) + ', ' + str(year) + ', ' + str(genres) + ', ' + str(actors) + ', ' + str(collections) + ', ' + str(rating) + ', ' + str(studios))
genresList = []
actorsList = []
collectionsList = []
studiosList = []
movieRatingsUS = ['G','PG','PG-13','R','NC-17','NR']
movieRatingsAUS = ['AUS-G','AUS-PG','AUS-M','MA15+','R18+','X18+']
movieRatingsCA = ['G','PG','14A','18A','R','A']
movieRatingsUK = ['U','12A','15','18','R18']
tvRatingsUS = ['TV-Y','TV-Y7','TV-G','TV-PG','TV-14','TV-MA','NR']
tvRatingsAUS = ['C','P','G','PG','M','MA15+','AV15+','R18+','E']
tvRatingsCA = ['C','C8','G','PG','14+','18+','Exempt']
tvRatingsUK = ['U','12A','15','18','R18']
print("INFO: "+section)
if rating != None:
ratingsAllowed = []
rating=rating.split(',')
if rating[0] == 'US' and section == 'Movies':
ratingsList = movieRatingsUS
elif rating[0] == 'US' and section == 'TV Shows':
ratingsList = tvRatingsUS
elif rating[0] == 'AUS' and section == 'Movies':
ratingsList = movieRatingsAUS
elif rating[0] == 'AUS' and section == 'TV Shows':
ratingsList = tvRatingsAUS
elif rating[0] == 'CA' and section == 'Movies':
ratingsList = movieRatingsCA
elif rating[0] == 'CA' and section == 'TV Shows':
ratingsList = tvRatingsCA
elif rating[0] == 'UK' and section == 'Movies':
ratingsList = movieRatingsUK
elif rating[0] == 'UK' and section == 'TV Shows':
ratingsList = tvRatingsUK
else:
if section == 'Movies':
ratingsList = movieRatingsUS
elif section == 'TV Shows':
ratingsList = tvRatingsUS
if rating[2] == '=':
print("INFO: Rating = " + rating[0] +', ' + rating[1])
ratingsAllowed.append(rating[1])
elif rating[2] == '<':
ratingPos = ratingsList.index(rating[1])
ratings = ''
while ratingPos >= 0:
ratings = ratings + ', ' + ratingsList[ratingPos]
ratingsAllowed.append(ratingsList[ratingPos])
ratingPos = ratingPos - 1
elif rating[2] == '>':
ratingPos = ratingsList.index(rating[1])
ratings = ''
ratingsListLength = len(ratingsList)
print("INFO: Rating = " + rating[0] +', ')
while ratingPos < ratingsListLength:
ratings = ratings + ', ' + ratingsList[ratingPos]
ratingsAllowed.append(ratingsList[ratingPos])
ratingPos = ratingPos + 1
if year != None:
if year[3] == '*':
print("INFO: Decade = " + str(year))
decade=year
release=None
else:
print("INFO: Year = " + str(year))
release=year
decade=None
else:
release=None
decade=None
if genres != None and ',' in genres:
genres=genres.replace("'",r"''").replace('"',r'""').split(',')
for genre in genres:
print("INFO: Genre = " + genre)
genresList.append(genre)
elif genres != None:
genres=genres.replace("'",r"''").replace('"',r'""')
print("INFO: Genre = " + genres)
genresList.append(genres)
if actors != None:
if type(actors) == list:
for actor in actors:
print("INFO: Actor = " + actor)
actor=actor.replace("'",r"''").replace('"',r'""')
actorsList.append(actor)
else:
print("INFO: Actor = " + actors)
actors=actors.replace("'",r"''").replace('"',r'""')
actorsList.append(actors)
if collections != None and ',' in collections:
collections=collections.replace("'",r"''")
collections=collections.replace('"',r'""')
collections=collections.split(',')
for collection in collections:
print("INFO: Collection = " + collection)
collectionsList.append(collection)
elif collections != None:
collections=collections.replace("'",r"''").replace('"',r'""')
print("INFO: Collection = " + collections)
collectionsList.append(collections)
if studios != None and ',' in studios:
studios=studios.replace("'",r"''").replace('"',r'""').split(',')
for studio in studios:
print("INFO: Studio = " + studio)
studiosList.append(studio)
elif studios != None:
studios=studio.replace("'",r"''").replace('"',r'""')
print("INFO: Studio = " + studios)
studiosList.append(studios)
cursor_execute = "SELECT * FROM movies WHERE (duration BETWEEN "+str(min)+" and "+str(max)+")"
if rating != None:
if len(ratingsAllowed) == 1:
cursor_execute = cursor_execute + " and rating LIKE \""+rating[1]+"\""
elif len(ratingsAllowed) > 0:
c = 0
for r in ratingsAllowed:
if c == 0:
cursor_execute = cursor_execute + " and (rating IN (\""+r+"\""
else:
cursor_execute = cursor_execute + ", \""+r+"\""
c = c + 1
cursor_execute = cursor_execute + "))"
if release != None:
cursor_execute = cursor_execute + " and releaseYear LIKE "+str(release)+"%\""
elif decade != None:
dec = str(decade[0:3])
cursor_execute = cursor_execute + " and releaseYear LIKE \""+dec+"%\""
if genresList != None:
for g in genresList:
if g != '':
cursor_execute = cursor_execute + " and genres LIKE \"%" + g + "%\""
if actorsList != None:
for a in actorsList:
if a != '':
cursor_execute = cursor_execute + " and (actors LIKE \"%"+a+"%\")"
if collectionsList != None:
for c in collectionsList:
if c != '':
cursor_execute = cursor_execute + " and (collections LIKE \"%"+c+"%\")"
if studiosList != None:
for s in studiosList:
if s != '':
cursor_execute = cursor_execute + "and studio LIKE \"%"+s+"%\""
cursor_execute = cursor_execute + " ORDER BY date(lastPlayedDate) ASC"
print("ACTION: " + cursor_execute)
self.cursor.execute(cursor_execute)
datalist = self.cursor.fetchall()
return datalist
def get_specific_episode(self, tvshow, season=None, episode=None): def get_specific_episode(self, tvshow, season=None, episode=None):
if season is None and episode is None: if season is None and episode is None:
print("ERROR: Season and Episode Numbers Not Found") print("ERROR: Season and Episode Numbers Not Found")
@@ -586,6 +824,14 @@ class PseudoChannelDatabase():
first_episode = self.cursor.fetchone() first_episode = self.cursor.fetchone()
return first_episode return first_episode
def get_first_episode_by_id(self, tvshow):
sql = ("SELECT id, unix, mediaID, title, duration, MIN(episodeNumber), MIN(seasonNumber), "
"showTitle, plexMediaID, customSectionName FROM episodes WHERE ( mediaID LIKE ?) COLLATE NOCASE")
self.cursor.execute(sql, (tvshow, ))
first_episode = self.cursor.fetchone()
return first_episode
''' '''
* *
* When incrementing episodes in a series I am advancing by "id" * When incrementing episodes in a series I am advancing by "id"
@@ -596,7 +842,13 @@ class PseudoChannelDatabase():
self.cursor.execute(sql, (episodeTitle, )) self.cursor.execute(sql, (episodeTitle, ))
episode_id = self.cursor.fetchone() episode_id = self.cursor.fetchone()
return episode_id return episode_id
def get_episode_from_plexMediaID(self,plexMediaID):
sql = "SELECT * FROM episodes WHERE (plexMediaID LIKE ?) COLLATE NOCASE"
self.cursor.execute(sql, (plexMediaID, ))
episode = self.cursor.fetchone()
return episode
####mutto233 made this one#### UPDATED 5/2/2020 ####mutto233 made this one#### UPDATED 5/2/2020
def get_episode_id_alternate(self,plexMediaID,series): def get_episode_id_alternate(self,plexMediaID,series):
sql = "SELECT id FROM episodes WHERE (showTitle LIKE ? AND plexMediaID LIKE ?) COLLATE NOCASE" sql = "SELECT id FROM episodes WHERE (showTitle LIKE ? AND plexMediaID LIKE ?) COLLATE NOCASE"
@@ -605,6 +857,18 @@ class PseudoChannelDatabase():
return episode_id return episode_id
####mutto233 made this one#### ####mutto233 made this one####
def get_episode_from_id(self,ID):
print("NOTICE: Getting episode of by matching ID")
sql = ("SELECT * FROM episodes WHERE ( id = "+str(ID)+") ORDER BY id LIMIT 1 COLLATE NOCASE")
self.cursor.execute(sql)
return self.cursor.fetchone()
def get_episode_id_by_show_id(self,plexMediaID,series):
sql = "SELECT id FROM episodes WHERE (mediaID LIKE ? AND plexMediaID LIKE ?) COLLATE NOCASE"
self.cursor.execute(sql, (series,plexMediaID, ))
episode_id = self.cursor.fetchone()
return episode_id
def get_random_episode(self): def get_random_episode(self):
sql = "SELECT * FROM episodes WHERE id IN (SELECT id FROM episodes ORDER BY RANDOM() LIMIT 1)" sql = "SELECT * FROM episodes WHERE id IN (SELECT id FROM episodes ORDER BY RANDOM() LIMIT 1)"
@@ -663,6 +927,225 @@ class PseudoChannelDatabase():
self.cursor.execute(sql, (min, max, )) self.cursor.execute(sql, (min, max, ))
return self.cursor.fetchone() return self.cursor.fetchone()
def get_random_show_data(self,section,min,max,airDate,genres,actors,similar,rating,studios):
print("INFO: " + str(min) + ', ' + str(max) + ', ' + str(airDate) + ', ' + str(genres) + ', ' + str(actors) + ', ' + str(similar) + ', ' + str(rating) + ', ' + str(studios))
if airDate != None:
if str(airDate)[3] == '*':
print("INFO: Decade = " + str(airDate)[0:3])
datestring=str(airDate)[0:3]
else:
print("INFO: Air Date = " + str(airDate))
datestring=airDate
else:
datestring = None
genresList = []
actorsList = []
similarList = []
studiosList = []
tvRatingsUS = ['TV-Y','TV-Y7','TV-G','TV-PG','TV-14','TV-MA','NR']
tvRatingsAUS = ['C','P','G','PG','M','MA15+','AV15+','R18+','E']
tvRatingsCA = ['C','C8','G','PG','14+','18+','Exempt']
tvRatingsUK = ['U','12A','15','18','R18']
print("INFO: "+section)
if rating != None:
ratingsAllowed = []
rating=rating.split(',')
if rating[0] == 'US':
ratingsList = tvRatingsUS
elif rating[0] == 'AUS':
ratingsList = tvRatingsAUS
elif rating[0] == 'CA':
ratingsList = tvRatingsCA
elif rating[0] == 'UK':
ratingsList = tvRatingsUK
else:
ratingsList = tvRatingsUS
if rating[2] == '=':
print("INFO: Rating = " + rating[0] +', ' + rating[1])
ratingsAllowed.append(rating[1])
elif rating[2] == '<':
ratingPos = ratingsList.index(rating[1])
ratings = ''
while ratingPos >= 0:
ratings = ratings + ', ' + ratingsList[ratingPos]
ratingsAllowed.append(ratingsList[ratingPos])
ratingPos = ratingPos - 1
elif rating[2] == '>':
ratingPos = ratingsList.index(rating[1])
ratings = ''
ratingsListLength = len(ratingsList)
print("INFO: Rating = " + rating[0] +', '+rating[1])
while ratingPos < ratingsListLength:
ratings = ratings + ', ' + ratingsList[ratingPos]
ratingsAllowed.append(ratingsList[ratingPos])
ratingPos = ratingPos + 1
if genres != None and ',' in genres:
genres=genres.replace("'",r"''").replace('"',r'""').split(',')
for genre in genres:
print("INFO: Genre = " + genre)
genresList.append(genre)
elif genres != None:
genres=genres.replace("'",r"''").replace('"',r'""')
print("INFO: Genre = " + genres)
genresList.append(genres)
if actors != None:
if type(actors) == list:
for actor in actors:
print("INFO: Actor = " + actor)
actor=actor.replace("'",r"''").replace('"',r'""')
actorsList.append(actor)
else:
print("INFO: Actor = " + actors)
actors=actors.replace("'",r"''").replace('"',r'""')
actorsList.append(actors)
if similar != None and ',' in similar:
similar=similar.replace("'",r"''")
similar=similar.replace('"',r'""')
similar=similar.split(',')
for s in similar:
print("INFO: Similar = " + s)
similarList.append(s)
elif similar != None:
similar=similar.replace("'",r"''").replace('"',r'""')
print("INFO: Similar = " + similar)
similarList.append(similar)
if studios != None and ',' in studios:
studios=studios.replace("'",r"''").replace('"',r'""').split(',')
for studio in studios:
print("INFO: Studio = " + studio)
studiosList.append(studio)
elif studios != None:
studios=studio.replace("'",r"''").replace('"',r'""')
print("INFO: Studio = " + studios)
studiosList.append(studios)
cursor_execute = "SELECT * FROM shows WHERE (customSectionName LIKE \"TV Shows\")"
leading_and = True
if rating != None:
if len(ratingsAllowed) == 1:
cursor_execute = cursor_execute + " and rating LIKE \""+rating[1]+"\""
leading_and = True
elif len(ratingsAllowed) > 0:
c = 0
for r in ratingsAllowed:
if c == 0:
cursor_execute = cursor_execute + " and (rating IN (\""+r+"\""
else:
cursor_execute = cursor_execute + ", \""+r+"\""
c = c + 1
cursor_execute = cursor_execute + "))"
if genresList != None:
for g in genresList:
if g != '':
cursor_execute = cursor_execute + " and genres LIKE \"%" + g + "%\""
leading_and = True
if actorsList != None:
for a in actorsList:
if a != '':
cursor_execute = cursor_execute + " and (actors LIKE \"%"+a+"%\")"
leading_and = True
if similarList != None:
for sim in similarList:
if sim != '':
cursor_execute = cursor_execute + " and (similar LIKE \"%"+sim+"%\")"
leading_and = True
if studiosList != None:
for s in studiosList:
if s != '':
cursor_execute = cursor_execute + " and studio LIKE \"%"+s+"%\""
leading_and = True
cursor_execute = cursor_execute + " ORDER BY mediaID ASC"
print("ACTION: " + cursor_execute)
self.cursor.execute(cursor_execute)
showslist = self.cursor.fetchall()
if datestring != None:
episode_execute = "SELECT * FROM episodes WHERE (duration BETWEEN "+str(min)+" and "+str(max)+") and airDate LIKE \""+str(datestring)+"%\" ORDER BY mediaID ASC"
print("INFO: " + episode_execute)
self.cursor.execute(episode_execute)
episodelist = self.cursor.fetchall()
datalist = []
else:
episode_execute = "SELECT * FROM episodes WHERE (duration BETWEEN "+str(min)+" and "+str(max)+") ORDER BY mediaID ASC"
print("INFO: " + episode_execute)
self.cursor.execute(episode_execute)
episodelist = self.cursor.fetchall()
datalist = []
for one_episode in episodelist:
for one_show in showslist:
if one_episode[2] == one_show[2] and one_show not in datalist:
datalist.append(one_show)
print("INFO: " + str(len(showslist)) + " shows found.")
if datalist != []:
print("INFO: " + str(len(datalist)) + " matching shows found")
the_show = random.choice(datalist)
else:
print("INFO: NO MATCHING SHOWS FOUND, TRYING AGAIN WITHOUT SOME METADATA")
#get shows list with only length, rating and date filters
cursor_execute = "SELECT * FROM shows WHERE (customSectionName LIKE \"TV Shows\")"
if rating != None:
if len(ratingsAllowed) == 1:
cursor_execute = cursor_execute + " and rating LIKE \""+rating[1]+"\""
leading_and = True
elif len(ratingsAllowed) > 0:
c = 0
for r in ratingsAllowed:
if c == 0:
cursor_execute = cursor_execute + " and (rating IN (\""+r+"\""
else:
cursor_execute = cursor_execute + ", \""+r+"\""
c = c + 1
cursor_execute = cursor_execute + "))"
cursor_execute = cursor_execute + " ORDER BY mediaID ASC"
print("ACTION: " + cursor_execute)
self.cursor.execute(cursor_execute)
showslist = self.cursor.fetchall()
episode_execute = "SELECT * FROM episodes WHERE (duration BETWEEN "+str(min)+" and "+str(max)+") ORDER BY mediaID ASC"
print("INFO: " + episode_execute)
self.cursor.execute(episode_execute)
episodelist = self.cursor.fetchall()
datalist = []
for one_episode in episodelist:
for one_show in showslist:
if one_episode[2] == one_show[2] and one_show not in datalist:
datalist.append(one_show)
print("INFO: " + str(len(showslist)) + " shows found.")
if datalist != []:
print("INFO: " + str(len(datalist)) + " matching shows found")
the_show = random.choice(datalist)
#print(str(the_show))
return the_show
def get_random_episode_of_show_by_data(self, seriesID, min, max, date, season=None, episode=None):
print("INFO: "+ str(seriesID) + ', ' + str(min) + ', ' + str(max) + ', ' + str(date) + ', Season: ' + str(season) + ', Episode: ' + str(episode))
cursor_execute = "SELECT * FROM episodes WHERE mediaID LIKE \""+str(seriesID)+"\" AND duration BETWEEN \""+str(min)+"\" and \""+str(max)+"\""
if season != None:
cursor_execute = cursor_execute + " and seasonNumber LIKE \""+str(season)+"\""
if episode != None:
cursor_execute = cursor_execute + " and episodeNumber LIKE \""+str(episode)+"\""
if date != None:
if str(date)[3] == '*':
date = str(date)[0:3]
cursor_execute = cursor_execute + " and airDate LIKE \""+str(date)+"%\""
cursor_execute = cursor_execute + " ORDER BY RANDOM() LIMIT 1"
print("INFO: " + cursor_execute)
self.cursor.execute(cursor_execute)
return self.cursor.fetchone()
def get_random_episode_of_show_by_data_alt(self, series, min, max, date, season=None, episode=None):
print("INFO: "+ str(series) + ', ' + str(min) + ', ' + str(max) + ', ' + str(date) + ', Season: ' + str(season) + ', Episode: ' + str(episode))
cursor_execute = "SELECT * FROM episodes WHERE showTitle LIKE \""+series+"\" AND duration BETWEEN \""+str(min)+"\" and \""+str(max)+"\""
if season != None:
cursor_execute = cursor_execute + " and seasonNumber LIKE \""+str(season)+"\""
if episode != None:
cursor_execute = cursor_execute + " and episodeNumber LIKE \""+str(episode)+"\""
if date != None:
cursor_execute = cursor_execute + " and airDate LIKE \""+date+"%\""
cursor_execute = cursor_execute + " ORDER BY RANDOM() LIMIT 1"
print("INFO: " + cursor_execute)
self.cursor.execute(cursor_execute)
random_episode = self.cursor.fetchone()
print("INFO: "+str(random_episode))
return random_episode
####mutto233 made this one#### ####mutto233 made this one####
def get_next_episode(self, series): def get_next_episode(self, series):
''' '''
@@ -692,7 +1175,7 @@ class PseudoChannelDatabase():
* Add this episdoe title to the "shows" table for the queue functionality to work * Add this episdoe title to the "shows" table for the queue functionality to work
* *
''' '''
self.update_shows_table_with_last_episode(series, first_episode_title) #self.update_shows_table_with_last_episode(series, first_episode_title)
return first_episode return first_episode
elif last_title_list: elif last_title_list:
@@ -709,19 +1192,19 @@ class PseudoChannelDatabase():
try: try:
print("NOTICE: Getting next episode of "+series.upper()+ " by matching ID and series or playlist name") print("NOTICE: Getting next episode of "+series.upper()+ " by matching ID and series or playlist name")
sql = ("SELECT * FROM episodes WHERE ( id > "+str(self.get_episode_id_alternate(last_title_list[0],series)[0])+ sql = ("SELECT * FROM episodes WHERE ( id > "+str(self.get_episode_id_alternate(last_title_list[0],series)[0])+
" AND showTitle LIKE ? ) ORDER BY seasonNumber LIMIT 1 COLLATE NOCASE") " AND showTitle LIKE ? ) ORDER BY id LIMIT 1 COLLATE NOCASE")
except TypeError: except TypeError:
try: try:
print("NOTICE: Getting next episode by matching title") print("NOTICE: Getting next episode by matching title")
sql = ("SELECT * FROM episodes WHERE ( id > "+str(self.get_episode_id(last_title_list[0])[0])+ sql = ("SELECT * FROM episodes WHERE ( id > "+str(self.get_episode_id(last_title_list[0])[0])+
" AND showTitle LIKE ? ) ORDER BY seasonNumber LIMIT 1 COLLATE NOCASE") " AND showTitle LIKE ? ) ORDER BY id LIMIT 1 COLLATE NOCASE")
print("NOTICE: We have an old school last episode title. Using old method, then converting to new method") print("NOTICE: We have an old school last episode title. Using old method, then converting to new method")
except TypeError: except TypeError:
sql = "" sql = ""
print("ERROR: For some reason, episode was not stored correctly. Maybe you updated your database and lost last episode? Reverting to first episode") print("ERROR: For some reason, episode was not stored correctly. Maybe you updated your database and lost last episode? Reverting to first episode")
if sql=="": if sql=="":
first_episode = self.get_first_episode(series) first_episode = self.get_first_episode(series)
self.update_shows_table_with_last_episode(series, first_episode[8]) #self.update_shows_table_with_last_episode(series, first_episode[8])
return first_episode return first_episode
self.cursor.execute(sql, (series, )) self.cursor.execute(sql, (series, ))
@@ -739,12 +1222,220 @@ class PseudoChannelDatabase():
# self.cursor.execute(sql, (series, )) # self.cursor.execute(sql, (series, ))
if next_episode != None: if next_episode != None:
self.update_shows_table_with_last_episode(series, next_episode[8]) #self.update_shows_table_with_last_episode(series, next_episode[8])
return next_episode return next_episode
else: else:
print("NOTICE: Not grabbing next episode restarting series, series must be over. Restarting from episode 1.") print("NOTICE: Not grabbing next episode restarting series, series must be over. Restarting from episode 1.")
first_episode = self.get_first_episode(series) first_episode = self.get_first_episode(series)
self.update_shows_table_with_last_episode(series, first_episode[8]) #self.update_shows_table_with_last_episode(series, first_episode[8])
return first_episode
def get_next_episode_alt(self, series, ID):
'''
*
* As a way of storing a "queue", I am storing the *next episode title in the "shows" table so I can
* determine what has been previously scheduled for each show
*
*
* If the last episode stored in the "shows" table is empty, then this is probably a first run...
*
'''
if ID == '':
'''
*
* Find the first episode of the series
*
'''
first_episode = self.get_first_episode(series)
first_episode_title = first_episode[8]
'''
*
* Add this episdoe title to the "shows" table for the queue functionality to work
*
'''
return first_episode
else:
'''
*
* The last episode stored in the "shows" table was not empty... get the next episode in the series
*
'''
"""
*
* If this isn't a first run, then grabbing the next episode by incrementing id
*
"""
try:
print("NOTICE: Getting next episode of "+series.upper()+ " by matching ID and series or playlist name")
sql = ("SELECT * FROM episodes WHERE ( id > "+str(ID)+
" AND showTitle LIKE ? ) ORDER BY id LIMIT 1 COLLATE NOCASE")
except TypeError:
try:
print("NOTICE: Getting next episode by matching ID and series or playlist name")
sql = ("SELECT * FROM episodes WHERE ( id > "+str(ID)+
" AND showTitle LIKE ? ) ORDER BY id LIMIT 1 COLLATE NOCASE")
print("NOTICE: We have an old school last episode title. Using old method, then converting to new method")
except TypeError:
sql = ""
print("ERROR: For some reason, episode was not stored correctly. Maybe you updated your database and lost last episode? Reverting to first episode")
if sql=="":
first_episode = self.get_first_episode(series)
#self.update_shows_table_with_last_episode(series, first_episode[8])
return first_episode
self.cursor.execute(sql, (series, ))
'''
*
* Try and advance to the next episode in the series, if it returns None then that means it reached the end...
*
'''
next_episode = self.cursor.fetchone()
if next_episode != None:
#self.update_shows_table_with_last_episode(series, next_episode[8])
return next_episode
else:
print("NOTICE: Not grabbing next episode restarting series, series must be over. Restarting from episode 1.")
first_episode = self.get_first_episode(series)
#self.update_shows_table_with_last_episode(series, first_episode[8])
return first_episode
def get_last_episode(self, series):
'''
*
* As a way of storing a "queue", I am storing the *next episode title in the "shows" table so I can
* determine what has been previously scheduled for each show
*
'''
self.cursor.execute("SELECT lastEpisodeTitle FROM shows WHERE mediaID LIKE ? COLLATE NOCASE", (series, ))
last_title_list = self.cursor.fetchone()
'''
*
* If the last episode stored in the "shows" table is empty, then this is probably a first run...
*
'''
if last_title_list and last_title_list[0] == '':
'''
*
* Find the first episode of the series
*
'''
first_episode = self.get_first_episode_by_id(series)
first_episode_title = first_episode[8]
'''
*
* Add this episdoe title to the "shows" table for the queue functionality to work
*
'''
return first_episode
elif last_title_list:
'''
*
* The last episode stored in the "shows" table was not empty... get the next episode in the series
*
'''
"""
*
* If this isn't a first run, then grabbing the next episode by incrementing id
*
"""
try:
print("NOTICE: Getting last episode of "+str(series)+ " by matching ID and series or playlist ID")
sql = ("SELECT * FROM episodes WHERE ( id = "+str(self.get_episode_id_by_show_id(last_title_list[0],series)[0])+
" AND mediaID LIKE ? ) ORDER BY id LIMIT 1 COLLATE NOCASE")
except TypeError as e:
print("ERROR: " + str(e))
try:
print("NOTICE: Getting last episode by matching title")
sql = ("SELECT * FROM episodes WHERE ( id = "+str(self.get_episode_id(last_title_list[0])[0])+
" AND mediaID LIKE ? ) ORDER BY id LIMIT 1 COLLATE NOCASE")
print("NOTICE: We have an old school last episode title. Using old method, then converting to new method")
except TypeError:
sql = ""
print("ERROR: For some reason, episode was not stored correctly. Maybe you updated your database and lost last episode? Reverting to first episode")
if sql=="":
first_episode = self.get_first_episode_by_id(series)
return first_episode
self.cursor.execute(sql, (series, ))
next_episode = self.cursor.fetchone()
if next_episode != None:
return next_episode
else:
print("NOTICE: Not grabbing next episode restarting series, series must be over. Restarting from episode 1.")
first_episode = self.get_first_episode_by_id(series)
return first_episode
def get_last_episode_alt(self, series):
'''
*
* As a way of storing a "queue", I am storing the *next episode title in the "shows" table so I can
* determine what has been previously scheduled for each show
*
'''
self.cursor.execute("SELECT lastEpisodeTitle FROM shows WHERE title LIKE ? COLLATE NOCASE", (series, ))
last_title_list = self.cursor.fetchone()
'''
*
* If the last episode stored in the "shows" table is empty, then this is probably a first run...
*
'''
if last_title_list and last_title_list[0] == '':
'''
*
* Find the first episode of the series
*
'''
first_episode = self.get_first_episode(series)
first_episode_title = first_episode[8]
'''
*
* Add this episdoe title to the "shows" table for the queue functionality to work
*
'''
return first_episode
elif last_title_list:
'''
*
* The last episode stored in the "shows" table was not empty... get the next episode in the series
*
'''
"""
*
* If this isn't a first run, then grabbing the next episode by incrementing id
*
"""
try:
print("NOTICE: Getting last episode of "+str(series)+ " by matching ID and series or playlist name")
sql = ("SELECT * FROM episodes WHERE ( id = "+str(self.get_episode_id_alternate(last_title_list[0],series)[0])+
" AND showTitle LIKE ? ) ORDER BY id LIMIT 1 COLLATE NOCASE")
except TypeError as e:
print("ERROR: " + str(e))
try:
print("NOTICE: Getting last episode by matching title")
sql = ("SELECT * FROM episodes WHERE ( id = "+str(self.get_episode_id(last_title_list[0])[0])+
" AND showTitle LIKE ? ) ORDER BY id LIMIT 1 COLLATE NOCASE")
print("NOTICE: We have an old school last episode title. Using old method, then converting to new method")
except TypeError:
sql = ""
print("ERROR: For some reason, episode was not stored correctly. Maybe you updated your database and lost last episode? Reverting to first episode")
if sql=="":
first_episode = self.get_first_episode(series)
return first_episode
self.cursor.execute(sql, (series, ))
next_episode = self.cursor.fetchone()
if next_episode != None:
return next_episode
else:
print("NOTICE: Not grabbing next episode restarting series, series must be over. Restarting from episode 1.")
first_episode = self.get_first_episode_by_id(series)
return first_episode return first_episode
def get_commercial(self, title): def get_commercial(self, title):

View File

@@ -188,14 +188,19 @@ for channel_dir in channel_dirs:
endloop = 1 endloop = 1
else: else:
for i in range(0,len(schedule)): for i in range(0,len(schedule)):
sql = "INSERT INTO schedule(id,unix,mediaID,title,duration,startTime,endTime,dayOfWeek,startTimeUnix,section,strictTime,timeShift,overlapMax,xtra) \ sql = "INSERT INTO schedule(id,unix,mediaID,title,duration,startTime,endTime,dayOfWeek,startTimeUnix,section,strictTime,timeShift,overlapMax,xtra,rerun,year,genres,actors,collections,rating,studio,seasonEpisode) \
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)" VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
table.execute(sql,schedule[i]) table.execute(sql,schedule[i])
for i in range(0,len(daily_schedule)): for i in range(0,len(daily_schedule)):
sql = "INSERT INTO daily_schedule(id,unix,mediaID,title,episodeNumber,seasonNumber,showTitle,duration,startTime,endTime,dayOfWeek,sectionType,plexMediaID,customSectionName) \ try:
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)" sql = "INSERT INTO daily_schedule(id,unix,mediaID,title,episodeNumber,seasonNumber,showTitle,duration,startTime,endTime,dayOfWeek,sectionType,plexMediaID,customSectionName,notes) \
table.execute(sql,daily_schedule[i]) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
table.execute(sql,daily_schedule[i])
except Exception as e:
print("ERROR: "+str(e))
sql = "INSERT INTO daily_schedule(id,unix,mediaID,title,episodeNumber,seasonNumber,showTitle,duration,startTime,endTime,dayOfWeek,sectionType,plexMediaID,customSectionName) \
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
table.execute(sql,daily_schedule[i])
# Step FIVE: Remove any media not in the directories set of commerical archives # Step FIVE: Remove any media not in the directories set of commerical archives
print("NOTICE: Trimming database at " + db_path) print("NOTICE: Trimming database at " + db_path)