Inital major Python3 change

In an effort to update this code to fit standards of Python3, changes have been made to code allowing it to run.

NOTE: At this point the basics have been tested.  i.e. -g -xml -u -m -r in that order.  More extensive testing should occur before we throw this to master.
This commit is contained in:
mutto233
2019-07-01 23:07:23 -04:00
parent 520958aa59
commit 670a005609
11 changed files with 138 additions and 127 deletions

View File

@@ -1,7 +1,7 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import sys # import importlib
import signal import signal
import datetime import datetime
from datetime import time from datetime import time
@@ -11,7 +11,8 @@ import calendar
import itertools import itertools
import argparse import argparse
import textwrap import textwrap
import os, sys import os
import sys
from xml.dom import minidom from xml.dom import minidom
import xml.etree.ElementTree as ET import xml.etree.ElementTree as ET
import json import json
@@ -32,8 +33,8 @@ from src import PseudoChannelCommercial
from src import PseudoChannelRandomMovie from src import PseudoChannelRandomMovie
import pseudo_config as config import pseudo_config as config
reload(sys) # importlib.reload(sys)
sys.setdefaultencoding('utf-8') # sys.setdefaultencoding('utf-8')
class PseudoChannel(): class PseudoChannel():
@@ -172,7 +173,7 @@ class PseudoChannel():
) )
elif correct_lib_name == "Commercials": elif correct_lib_name == "Commercials":
print "user_lib_name", section.title print("user_lib_name", section.title)
sectionMedia = self.PLEX.library.section(section.title).all() sectionMedia = self.PLEX.library.section(section.title).all()
media_length = len(sectionMedia) media_length = len(sectionMedia)
for i, media in enumerate(sectionMedia): for i, media in enumerate(sectionMedia):
@@ -267,7 +268,6 @@ class PseudoChannel():
section.title section.title
) )
def update_db_comm(self): def update_db_comm(self):
print("#### Updating Local Database, COMMERCIALS ONLY") print("#### Updating Local Database, COMMERCIALS ONLY")
@@ -278,7 +278,7 @@ class PseudoChannel():
for correct_lib_name, user_lib_name in libs_dict.items(): for correct_lib_name, user_lib_name in libs_dict.items():
if section.title.lower() in [x.lower() for x in user_lib_name]: if section.title.lower() in [x.lower() for x in user_lib_name]:
if correct_lib_name == "Commercials": if correct_lib_name == "Commercials":
print "user_lib_name", section.title print("user_lib_name", section.title)
sectionMedia = self.PLEX.library.section(section.title).all() sectionMedia = self.PLEX.library.section(section.title).all()
media_length = len(sectionMedia) media_length = len(sectionMedia)
for i, media in enumerate(sectionMedia): for i, media in enumerate(sectionMedia):
@@ -350,7 +350,7 @@ class PseudoChannel():
) )
print "Adding: ", time.tag, section, time.text, time.attrib['title'] print("Adding: ", time.tag, section, time.text, time.attrib['title'])
self.db.add_schedule_to_db( self.db.add_schedule_to_db(
mediaID_place, # mediaID mediaID_place, # mediaID
title, # title title, # title
@@ -422,7 +422,7 @@ class PseudoChannel():
self.OVERLAP_MAX = overlapMax self.OVERLAP_MAX = overlapMax
time1 = prevEndTime.strftime('%I:%M:%S %p') time1 = prevEndTime.strftime('%I:%M:%S %p')
timeB = datetime.datetime.strptime(intendedStartTime, '%I:%M:%S %p').strftime(self.APP_TIME_FORMAT_STR) timeB = datetime.datetime.strptime(intendedStartTime, '%I:%M:%S %p').strftime(self.APP_TIME_FORMAT_STR)
print "++++ Previous End Time: ", time1, "Intended start time: ", timeB print("++++ Previous End Time: ", time1, "Intended start time: ", timeB)
timeDiff = self.time_diff(time1, timeB) timeDiff = self.time_diff(time1, timeB)
print("++++timeDiff "+ str(timeDiff)) print("++++timeDiff "+ str(timeDiff))
# print("++++startTimeUNIX: "+ str(intendedStartTime)) # print("++++startTimeUNIX: "+ str(intendedStartTime))
@@ -441,16 +441,16 @@ class PseudoChannel():
''' '''
time1A=prevEndTime.strftime('%H:%M') time1A=prevEndTime.strftime('%H:%M')
time1A_comp = datetime.datetime.strptime(time1A, '%H:%M') # there was an issue with the date changing to 1/2, so we had to do this for correct comparison time1A_comp = datetime.datetime.strptime(time1A, '%H:%M') # there was an issue with the date changing to 1/2, so we had to do this for correct comparison
timeset=[datetime.time(h,m).strftime("%H:%M") for h,m in itertools.product(xrange(0,24),xrange(0,60,int(self.OVERLAP_GAP)))] timeset=[datetime.time(h,m).strftime("%H:%M") for h,m in itertools.product(range(0,24),range(0,60,int(self.OVERLAP_GAP)))]
timeset_last = timeset[-1] timeset_last = timeset[-1]
theTimeSetInterval_last = datetime.datetime.strptime(timeset_last, '%H:%M') theTimeSetInterval_last = datetime.datetime.strptime(timeset_last, '%H:%M')
prevEndTime = time1A_comp #maybe this will change things? prevEndTime = time1A_comp #maybe this will change things?
print "++++ Previous End Time: ", time1A_comp print("++++ Previous End Time: ", time1A_comp)
print "++++ Last Element of the Day: ", theTimeSetInterval_last print("++++ Last Element of the Day: ", theTimeSetInterval_last)
if time1A_comp > theTimeSetInterval_last: if time1A_comp > theTimeSetInterval_last:
print "++++ We are starting a show with the new day. Using first element of the next day" print("++++ We are starting a show with the new day. Using first element of the next day")
theTimeSetInterval = datetime.datetime.strptime(timeset[0], '%H:%M') #This must be the element we are looking for theTimeSetInterval = datetime.datetime.strptime(timeset[0], '%H:%M') #This must be the element we are looking for
newStartTime = theTimeSetInterval newStartTime = theTimeSetInterval
''' '''
@@ -474,7 +474,7 @@ class PseudoChannel():
for time in timeset: for time in timeset:
theTimeSetInterval = datetime.datetime.strptime(time, '%H:%M') theTimeSetInterval = datetime.datetime.strptime(time, '%H:%M')
if theTimeSetInterval >= prevEndTime: if theTimeSetInterval >= prevEndTime:
print "++++ There is overlap. Setting new time-interval:", theTimeSetInterval print("++++ There is overlap. Setting new time-interval:", theTimeSetInterval)
newStartTime = theTimeSetInterval newStartTime = theTimeSetInterval
break break
elif (timeDiff >= 0) and (self.TIME_GAP != -1): elif (timeDiff >= 0) and (self.TIME_GAP != -1):
@@ -495,7 +495,7 @@ class PseudoChannel():
tempTimeTwoStr = datetime.datetime.strptime(time1, self.APP_TIME_FORMAT_STR).strftime('%H:%M') tempTimeTwoStr = datetime.datetime.strptime(time1, self.APP_TIME_FORMAT_STR).strftime('%H:%M')
formatted_time_two = datetime.datetime.strptime(tempTimeTwoStr, '%H:%M') formatted_time_two = datetime.datetime.strptime(tempTimeTwoStr, '%H:%M')
if theTimeSetInterval >= formatted_time_two: if theTimeSetInterval >= formatted_time_two:
print "++++ Setting new time-interval:", theTimeSetInterval print("++++ Setting new time-interval:", theTimeSetInterval)
newStartTime = theTimeSetInterval newStartTime = theTimeSetInterval
break break
else: else:
@@ -539,7 +539,7 @@ class PseudoChannel():
for entry in schedule: for entry in schedule:
schedule_advance_watcher += 1 schedule_advance_watcher += 1
section = entry[9] section = entry[9]
for key, val in weekday_dict.iteritems(): 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):
if section == "TV Shows": if section == "TV Shows":
if str(entry[3]).lower() == "random": if str(entry[3]).lower() == "random":
@@ -585,10 +585,10 @@ class PseudoChannel():
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]:
print "correct_lib_name", correct_lib_name print("correct_lib_name", correct_lib_name)
if correct_lib_name == "Movies": if correct_lib_name == "Movies":
print "entry[13]", entry[13] print("entry[13]", entry[13])
movies = self.PLEX.library.section(theSection.title) movies = self.PLEX.library.section(theSection.title)
try: try:
@@ -596,7 +596,7 @@ class PseudoChannel():
regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)") regex = re.compile(r"\b(\w+)\s*:\s*([^:]*)(?=\s+\w+\s*:|$)")
d = dict(regex.findall(thestr)) d = dict(regex.findall(thestr))
# turn values into list # turn values into list
for key, val in d.iteritems(): for key, val in d.items():
d[key] = val.split(',') d[key] = val.split(',')
for movie in movies.search(None, **d): for movie in movies.search(None, **d):
movies_list.append(movie) movies_list.append(movie)
@@ -620,7 +620,7 @@ class PseudoChannel():
else: else:
print "movies_list", movies_list print("movies_list", movies_list)
print("For some reason, I've failed getting movie with xtra args.") print("For some reason, I've failed getting movie with xtra args.")
the_movie = self.db.get_random_movie() the_movie = self.db.get_random_movie()
@@ -658,7 +658,7 @@ class PseudoChannel():
) )
self.MEDIA.append(movie) self.MEDIA.append(movie)
else: else:
print str("Cannot find Movie, {} in the local db".format(entry[3])).encode('UTF-8') print(str("Cannot find Movie, {} in the local db".format(entry[3])).encode('UTF-8'))
elif section == "Music": elif section == "Music":
the_music = self.db.get_music(entry[3]) the_music = self.db.get_music(entry[3])
if the_music != None: if the_music != None:
@@ -677,7 +677,7 @@ class PseudoChannel():
) )
self.MEDIA.append(music) self.MEDIA.append(music)
else: else:
print str("Cannot find Music, {} in the local db".format(entry[3])).encode('UTF-8') print(str("Cannot find Music, {} in the local db".format(entry[3])).encode('UTF-8'))
elif section == "Video": elif section == "Video":
the_video = self.db.get_video(entry[3]) the_video = self.db.get_video(entry[3])
if the_music != None: if the_music != None:
@@ -696,21 +696,21 @@ class PseudoChannel():
) )
self.MEDIA.append(video) self.MEDIA.append(video)
else: else:
print str("Cannot find Video, {} in the local db".format(entry[3])).encode('UTF-8') print(str("Cannot find Video, {} in the local db".format(entry[3])).encode('UTF-8'))
else: else:
pass pass
"""If we reached the end of the scheduled items for today, add them to the daily schedule """If we reached the end of the scheduled items for today, add them to the daily schedule
""" """
if schedule_advance_watcher >= len(schedule): if schedule_advance_watcher >= len(schedule):
print "+++++ Finished processing time entries, recreating daily_schedule" print("+++++ Finished processing time entries, recreating daily_schedule")
previous_episode = None previous_episode = None
for entry in self.MEDIA: for entry in self.MEDIA:
if previous_episode != None: if previous_episode != None:
natural_start_time = datetime.datetime.strptime(entry.natural_start_time, self.APP_TIME_FORMAT_STR) natural_start_time = datetime.datetime.strptime(entry.natural_start_time, self.APP_TIME_FORMAT_STR)
natural_end_time = entry.natural_end_time natural_end_time = entry.natural_end_time
if entry.is_strict_time.lower() == "true": if entry.is_strict_time.lower() == "true":
print "++++ Strict-time: {}".format(str(entry.title)) print("++++ Strict-time: {}".format(str(entry.title)))
entry.end_time = self.get_end_time_from_duration( entry.end_time = self.get_end_time_from_duration(
self.translate_time(entry.start_time), self.translate_time(entry.start_time),
entry.duration entry.duration
@@ -728,9 +728,18 @@ class PseudoChannel():
previous_episode = entry previous_episode = entry
else: else:
try: try:
print "++++ NOT strict-time: {}".format(str(entry.title).encode(sys.stdout.encoding, errors='replace')) print("++++ NOT strict-time: {}".format(str(entry.title).encode(sys.stdout.encoding, errors='replace')))
except: except:
pass pass
if pseudo_channel.DEBUG:
new_starttime = self.calculate_start_time(
previous_episode.end_time,
entry.natural_start_time,
previous_episode.time_shift,
""
)
else:
try: try:
new_starttime = self.calculate_start_time( new_starttime = self.calculate_start_time(
previous_episode.end_time, previous_episode.end_time,
@@ -740,7 +749,7 @@ class PseudoChannel():
) )
except: except:
print("Error in calculate_start_time") print("Error in calculate_start_time")
print "++++ New start time:", new_starttime print("++++ New start time:", new_starttime)
entry.start_time = datetime.datetime.strptime(new_starttime, self.APP_TIME_FORMAT_STR).strftime('%I:%M:%S %p') entry.start_time = datetime.datetime.strptime(new_starttime, self.APP_TIME_FORMAT_STR).strftime('%I:%M:%S %p')
entry.end_time = self.get_end_time_from_duration(entry.start_time, entry.duration) entry.end_time = self.get_end_time_from_duration(entry.start_time, entry.duration)
"""Get List of Commercials to inject""" """Get List of Commercials to inject"""
@@ -769,16 +778,16 @@ class PseudoChannel():
def show_clients(self): def show_clients(self):
print "##### Connected Clients:" print("##### Connected Clients:")
for i, client in enumerate(self.PLEX.clients()): for i, client in enumerate(self.PLEX.clients()):
print "+++++", str(i + 1)+".", "Client:", client.title print("+++++", str(i + 1)+".", "Client:", client.title)
def show_schedule(self): def show_schedule(self):
print "##### Daily Pseudo Schedule:" print("##### Daily Pseudo Schedule:")
daily_schedule = self.db.get_daily_schedule() daily_schedule = self.db.get_daily_schedule()
for i , entry in enumerate(daily_schedule): for i , entry in enumerate(daily_schedule):
print str("+++++ {} {} {} {} {} {}".format(str(i + 1)+".", entry[8], entry[11], entry[6], " - ", entry[3])).encode(sys.stdout.encoding, errors='replace') print(str("+++++ {} {} {} {} {} {}".format(str(i + 1)+".", entry[8], entry[11], entry[6], " - ", entry[3])).encode(sys.stdout.encoding, errors='replace'))
def write_json_to_file(self, data, fileName): def write_json_to_file(self, data, fileName):
@@ -794,9 +803,9 @@ class PseudoChannel():
shows_table = self.db.get_shows_table() shows_table = self.db.get_shows_table()
json_string = json.dumps(shows_table) json_string = json.dumps(shows_table)
print "+++++ Exporting queue " print("+++++ Exporting queue ")
self.write_json_to_file(json_string, "pseudo-queue.json") self.write_json_to_file(json_string, "pseudo-queue.json")
print "+++++ Done." print("+++++ Done.")
self.export_daily_schedule() self.export_daily_schedule()
def import_queue(self): def import_queue(self):
@@ -807,7 +816,7 @@ class PseudoChannel():
data = json.load(data_file) data = json.load(data_file)
#print(data) #print(data)
for row in data: for row in data:
print "lastEpisodeTitle:", row[5] print("lastEpisodeTitle:", row[5])
self.db.import_shows_table_by_row( self.db.import_shows_table_by_row(
row[2], row[2],
row[3], row[3],
@@ -816,16 +825,16 @@ class PseudoChannel():
row[6], row[6],
row[7], row[7],
) )
print "+++++ Done. Imported queue." print("+++++ Done. Imported queue.")
self.import_daily_schedule() self.import_daily_schedule()
def export_daily_schedule(self): def export_daily_schedule(self):
daily_schedule_table = self.db.get_daily_schedule() daily_schedule_table = self.db.get_daily_schedule()
json_string = json.dumps(daily_schedule_table) json_string = json.dumps(daily_schedule_table)
print "+++++ Exporting Daily Schedule " print("+++++ Exporting Daily Schedule ")
self.write_json_to_file(json_string, "pseudo-daily_schedule.json") self.write_json_to_file(json_string, "pseudo-daily_schedule.json")
print "+++++ Done." print("+++++ Done.")
def import_daily_schedule(self): def import_daily_schedule(self):
@@ -833,7 +842,7 @@ class PseudoChannel():
self.db.remove_all_daily_scheduled_items() self.db.remove_all_daily_scheduled_items()
with open('pseudo-daily_schedule.json') as data_file: with open('pseudo-daily_schedule.json') as data_file:
data = json.load(data_file) data = json.load(data_file)
#pprint(data) #print(data)
for row in data: for row in data:
"""print row""" """print row"""
self.db.import_daily_schedule_table_by_row( self.db.import_daily_schedule_table_by_row(
@@ -850,7 +859,7 @@ class PseudoChannel():
row[12], row[12],
row[13], row[13],
) )
print "+++++ Done. Imported Daily Schedule." print("+++++ Done. Imported Daily Schedule.")
def get_daily_schedule_cache_as_json(self): def get_daily_schedule_cache_as_json(self):
@@ -867,7 +876,7 @@ class PseudoChannel():
daily_schedule_table = self.db.get_daily_schedule() daily_schedule_table = self.db.get_daily_schedule()
json_string = json.dumps(daily_schedule_table) json_string = json.dumps(daily_schedule_table)
print "+++++ Saving Daily Schedule Cache " print("+++++ Saving Daily Schedule Cache ")
self.save_file(json_string, 'daily-schedule.json', '../.pseudo-cache/') self.save_file(json_string, 'daily-schedule.json', '../.pseudo-cache/')
def save_file(self, data, filename, path="./"): def save_file(self, data, filename, path="./"):
@@ -1041,9 +1050,9 @@ if __name__ == '__main__':
if args.make_html: if args.make_html:
pseudo_channel.make_xml_schedule() pseudo_channel.make_xml_schedule()
if args.run: if args.run:
print banner print(banner)
print "+++++ To run this in the background:" print("+++++ To run this in the background:")
print "+++++", "screen -d -m bash -c 'python PseudoChannel.py -r; exec sh'" print("+++++", "screen -d -m bash -c 'python PseudoChannel.py -r; exec sh'")
"""Every minute on the minute check the DB startTimes of all media to """Every minute on the minute check the DB startTimes of all media to
determine whether or not to play. Also, check the now_time to determine whether or not to play. Also, check the now_time to
see if it's midnight (or 23.59), if so then generate a new daily_schedule see if it's midnight (or 23.59), if so then generate a new daily_schedule
@@ -1063,7 +1072,7 @@ if __name__ == '__main__':
now = datetime.datetime.now() now = datetime.datetime.now()
now = now.replace(year=1900, month=1, day=1) now = now.replace(year=1900, month=1, day=1)
closest_media = nearest(dates_list, now) closest_media = nearest(dates_list, now)
print closest_media print(closest_media)
prevItem = None prevItem = None
for item in daily_schedule: for item in daily_schedule:
@@ -1072,7 +1081,7 @@ if __name__ == '__main__':
if item_time == closest_media: if item_time == closest_media:
#print "Line 1088, Here", item #print "Line 1088, Here", item
elapsed_time = closest_media - now elapsed_time = closest_media - now
print elapsed_time.total_seconds() print(elapsed_time.total_seconds())
try: try:
endTime = datetime.datetime.strptime(item[9], '%Y-%m-%d %H:%M:%S.%f') endTime = datetime.datetime.strptime(item[9], '%Y-%m-%d %H:%M:%S.%f')
except ValueError: except ValueError:
@@ -1080,7 +1089,7 @@ if __name__ == '__main__':
# we need to play the content and add an offest # we need to play the content and add an offest
if elapsed_time.total_seconds() < 0 and \ if elapsed_time.total_seconds() < 0 and \
endTime > now: endTime > now:
print str("+++++ Queueing up {} to play right away.".format(item[3])).encode('UTF-8') print(str("+++++ Queueing up {} to play right away.".format(item[3])).encode('UTF-8'))
offset = int(abs(elapsed_time.total_seconds() * 1000)) offset = int(abs(elapsed_time.total_seconds() * 1000))
pseudo_channel.controller.play(item, daily_schedule, offset) pseudo_channel.controller.play(item, daily_schedule, offset)
break break
@@ -1097,43 +1106,43 @@ if __name__ == '__main__':
elapsed_timeTwo = prevItem_time - now elapsed_timeTwo = prevItem_time - now
offsetTwo = int(abs(elapsed_timeTwo.total_seconds() * 1000)) offsetTwo = int(abs(elapsed_timeTwo.total_seconds() * 1000))
if prevItem_time.hour > now.hour: if prevItem_time.hour > now.hour:
print "we have a day skip" print("we have a day skip")
now = now.replace(hour=23,minute=59,second=59) now = now.replace(hour=23,minute=59,second=59)
elapsed_timeTwo = prevItem_time-now elapsed_timeTwo = prevItem_time-now
mnight = now.replace(hour=0,minute=0,second=0) mnight = now.replace(hour=0,minute=0,second=0)
now = datetime.datetime.now() now = datetime.datetime.now()
now = now.replace(year=1900, month=1, day=1) now = now.replace(year=1900, month=1, day=1)
elapsed_timeTwo = elapsed_timeTwo + (mnight-now) elapsed_timeTwo = elapsed_timeTwo + (mnight-now)
print elapsed_timeTwo.total_seconds() print(elapsed_timeTwo.total_seconds())
offsetTwo = int(abs(elapsed_timeTwo.total_seconds() * 1000)) offsetTwo = int(abs(elapsed_timeTwo.total_seconds() * 1000))
if pseudo_channel.DEBUG: if pseudo_channel.DEBUG:
print "+++++ Closest media was the next media " \ print("+++++ Closest media was the next media " \
"but we were in the middle of something so triggering that instead." "but we were in the middle of something so triggering that instead.")
print str("+++++ Queueing up '{}' to play right away.".format(prevItem[3])).encode('UTF-8') print(str("+++++ Queueing up '{}' to play right away.".format(prevItem[3])).encode('UTF-8'))
pseudo_channel.controller.play(prevItem, daily_schedule, offsetTwo) pseudo_channel.controller.play(prevItem, daily_schedule, offsetTwo)
break break
prevItem = itemTwo prevItem = itemTwo
def job_that_executes_once(item, schedulelist): def job_that_executes_once(item, schedulelist):
print str("##### Readying media: '{}'".format(item[3])).encode('UTF-8') print(str("##### Readying media: '{}'".format(item[3])).encode('UTF-8'))
next_start_time = datetime.datetime.strptime(item[8], "%I:%M:%S %p") next_start_time = datetime.datetime.strptime(item[8], "%I:%M:%S %p")
now = datetime.datetime.now() now = datetime.datetime.now()
now = now.replace(year=1900, month=1, day=1) now = now.replace(year=1900, month=1, day=1)
time_diff = next_start_time - now time_diff = next_start_time - now
if time_diff.total_seconds() > 0: if time_diff.total_seconds() > 0:
print "+++++ Sleeping for {} seconds before playing: '{}'".format(time_diff.total_seconds(), item[3]) print("+++++ Sleeping for {} seconds before playing: '{}'".format(time_diff.total_seconds(), item[3]))
sleep(int(time_diff.total_seconds())) sleep(int(time_diff.total_seconds()))
if pseudo_channel.DEBUG: if pseudo_channel.DEBUG:
print "+++++ Woke up!" print("+++++ Woke up!")
pseudo_channel.controller.play(item, schedulelist) pseudo_channel.controller.play(item, schedulelist)
else: else:
pseudo_channel.controller.play(item, schedulelist) pseudo_channel.controller.play(item, schedulelist)
return schedule.CancelJob return schedule.CancelJob
def generate_memory_schedule(schedulelist, isforupdate=False): def generate_memory_schedule(schedulelist, isforupdate=False):
print "##### Generating Memory Schedule." print("##### Generating Memory Schedule.")
now = datetime.datetime.now() now = datetime.datetime.now()
now = now.replace(year=1900, month=1, day=1) now = now.replace(year=1900, month=1, day=1)
pseudo_cache = pseudo_channel.get_daily_schedule_cache_as_json() pseudo_cache = pseudo_channel.get_daily_schedule_cache_as_json()
@@ -1148,7 +1157,7 @@ if __name__ == '__main__':
"""If update time is in between the prev media start / stop then there is overlap""" """If update time is in between the prev media start / stop then there is overlap"""
if prev_start_time < now and prev_end_time > now: if prev_start_time < now and prev_end_time > now:
try: try:
print "+++++ It looks like there is update schedule overlap", cached_item[3] print("+++++ It looks like there is update schedule overlap", cached_item[3])
except: except:
pass pass
prev_end_time_to_watch_for = prev_end_time prev_end_time_to_watch_for = prev_end_time
@@ -1161,13 +1170,13 @@ if __name__ == '__main__':
"""If prev end time is more then the start time of this media, skip it""" """If prev end time is more then the start time of this media, skip it"""
if prev_end_time_to_watch_for > new_start_time: if prev_end_time_to_watch_for > new_start_time:
try: try:
print "Skipping scheduling item do to cached overlap.", item[3] print("Skipping scheduling item do to cached overlap.", item[3])
except: except:
pass pass
continue continue
else: else:
schedule.every().day.at(trans_time).do(job_that_executes_once, item, schedulelist).tag('daily-tasks') schedule.every().day.at(trans_time).do(job_that_executes_once, item, schedulelist).tag('daily-tasks')
print "+++++ Done." print("+++++ Done.")
generate_memory_schedule(pseudo_channel.db.get_daily_schedule()) generate_memory_schedule(pseudo_channel.db.get_daily_schedule())
daily_update_time = datetime.datetime.strptime( daily_update_time = datetime.datetime.strptime(
pseudo_channel.translate_time( pseudo_channel.translate_time(

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
from Media import Media from .Media import Media
class Commercial(Media): class Commercial(Media):

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
from Media import Media from .Media import Media
class Episode(Media): class Episode(Media):

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
from Media import Media from .Media import Media
class Movie(Media): class Movie(Media):

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
from Media import Media from .Media import Media
class Music(Media): class Music(Media):

View File

@@ -58,17 +58,17 @@ class PseudoChannelCommercial():
if prev_item_end_time.replace(second=0,microsecond=0) > curr_item_start_time and strict_time == "false": if prev_item_end_time.replace(second=0,microsecond=0) > curr_item_start_time and strict_time == "false":
# NOTE: This is just for the logic of this function, I have noticed that this # NOTE: This is just for the logic of this function, I have noticed that this
# may cause other issues in other functions, since now the day is off. # may cause other issues in other functions, since now the day is off.
print "WE MUST BE SKIPPING A DAY, ADDING A DAY TO THE START TIME" print("WE MUST BE SKIPPING A DAY, ADDING A DAY TO THE START TIME")
curr_item_start_time = curr_item_start_time.replace(day=2) curr_item_start_time = curr_item_start_time.replace(day=2)
print "##############################################" print("##############################################")
print "get_commercials_to_place_between_media DEBUG" print("get_commercials_to_place_between_media DEBUG")
print "NOW: %s" % now print("NOW: %s" % now)
print "prev_item_end_time: %s" % prev_item_end_time.replace(second=0,microsecond=0) print("prev_item_end_time: %s" % prev_item_end_time.replace(second=0,microsecond=0) )
print "curr_item_start_time: %s" % curr_item_start_time print("curr_item_start_time: %s" % curr_item_start_time)
print "time_diff: %s" % time_diff print("time_diff: %s" % time_diff)
print "##############################################" print("##############################################")
count = 0 count = 0
commercial_list = [] commercial_list = []
@@ -124,7 +124,7 @@ class PseudoChannelCommercial():
break break
else: else:
print "===== Finding correct FINAL commercial to add to List." print("===== Finding correct FINAL commercial to add to List.")
last_comm = None last_comm = None
for comm in self.commercials: for comm in self.commercials:

View File

@@ -221,7 +221,7 @@ class PseudoChannelDatabase():
self.conn.commit() self.conn.commit()
# Catch the exception # Catch the exception
except Exception as e: except Exception as e:
print plexMediaID print(plexMediaID)
# Roll back any change if something goes wrong # Roll back any change if something goes wrong
self.conn.rollback() self.conn.rollback()
raise e raise e
@@ -268,8 +268,8 @@ class PseudoChannelDatabase():
customSectionName customSectionName
): ):
print "sectionType", sectionType print("sectionType", sectionType)
print "customSectionName", customSectionName print("customSectionName", customSectionName)
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 "
@@ -301,11 +301,11 @@ class PseudoChannelDatabase():
def add_media_to_daily_schedule(self, media): def add_media_to_daily_schedule(self, media):
try: try:
print str("#### Adding media to db: {} {}".format(media.title, media.start_time)).encode('UTF-8') print(str("#### Adding media to db: {} {}".format(media.title, media.start_time)).encode('UTF-8'))
except: except:
print "----- Not outputting media info due to ascii code issues." print("----- Not outputting media info due to ascii code issues.")
print "media.custom_section_name", media.custom_section_name print("media.custom_section_name", media.custom_section_name)
self.add_daily_schedule_to_db( self.add_daily_schedule_to_db(
0, 0,
media.title, media.title,
@@ -420,7 +420,7 @@ class PseudoChannelDatabase():
def get_media(self, title, mediaType): def get_media(self, title, mediaType):
print "+++++ title:", title print("+++++ title:", title)
if(title is not None): if(title is not None):
media = mediaType media = mediaType
sql = "SELECT * FROM "+media+" WHERE (title LIKE ?) COLLATE NOCASE" sql = "SELECT * FROM "+media+" WHERE (title LIKE ?) COLLATE NOCASE"
@@ -438,10 +438,10 @@ class PseudoChannelDatabase():
def get_daily_schedule(self): def get_daily_schedule(self):
print "##### Getting Daily Schedule from DB." print("##### Getting Daily Schedule from DB.")
self.cursor.execute("SELECT * FROM daily_schedule ORDER BY datetime(startTime) ASC") self.cursor.execute("SELECT * FROM daily_schedule ORDER BY datetime(startTime) ASC")
datalist = list(self.cursor.fetchall()) datalist = list(self.cursor.fetchall())
print "+++++ Done." print("+++++ Done.")
return datalist return datalist
def get_movie(self, title): def get_movie(self, title):

View File

@@ -43,7 +43,7 @@ class PseudoChannelRandomMovie():
if(movie[5] is not None): #lastPlayedDate is recorded if(movie[5] is not None): #lastPlayedDate is recorded
print movie[5] print(movie[5])
now = datetime.datetime.now() now = datetime.datetime.now()
lastPlayedDate = datetime.datetime.strptime(movie[5], '%Y-%m-%d') lastPlayedDate = datetime.datetime.strptime(movie[5], '%Y-%m-%d')

View File

@@ -6,7 +6,9 @@ import logging
import logging.handlers import logging.handlers
from datetime import datetime from datetime import datetime
import sqlite3 import sqlite3
import thread,SocketServer,SimpleHTTPServer import _thread
import socketserver
import http.server
from plexapi.server import PlexServer from plexapi.server import PlexServer
from yattag import Doc from yattag import Doc
from yattag import indent from yattag import indent
@@ -83,7 +85,7 @@ class PseudoDailyScheduleController():
web_dir = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'schedules')) web_dir = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'schedules'))
os.chdir(web_dir) os.chdir(web_dir)
PORT = int(self.CONTROLLER_SERVER_PORT) PORT = int(self.CONTROLLER_SERVER_PORT)
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): class MyHandler(http.server.SimpleHTTPRequestHandler):
def log_message(self, format, *args): def log_message(self, format, *args):
return return
@@ -91,7 +93,7 @@ class PseudoDailyScheduleController():
global httpd global httpd
try: try:
#print "Starting webserver at port: ", PORT #print "Starting webserver at port: ", PORT
# create the httpd handler for the simplehttpserver # create the httpd handler for the http.server
# we set the allow_reuse_address incase something hangs can still bind to port # we set the allow_reuse_address incase something hangs can still bind to port
class ReusableTCPServer(SocketServer.TCPServer): allow_reuse_address=True class ReusableTCPServer(SocketServer.TCPServer): allow_reuse_address=True
# specify the httpd service on 0.0.0.0 (all interfaces) on port 80 # specify the httpd service on 0.0.0.0 (all interfaces) on port 80
@@ -102,8 +104,8 @@ class PseudoDailyScheduleController():
except KeyboardInterrupt: except KeyboardInterrupt:
core.print_info("Exiting the SET web server...") core.print_info("Exiting the SET web server...")
httpd.socket.close() httpd.socket.close()
except socket.error, exc: except(socket.error, exc):
print "Caught exception socket.error : %s" % exc print("Caught exception socket.error : %s" % exc )
# handle the rest # handle the rest
#except Exception: #except Exception:
# print "[*] Exiting the SET web server...\n" # print "[*] Exiting the SET web server...\n"
@@ -322,7 +324,7 @@ class PseudoDailyScheduleController():
((currentTime-timeBStart).total_seconds() >= 0 and \ ((currentTime-timeBStart).total_seconds() >= 0 and \
(midnight-currentTime).total_seconds() >= 0))): (midnight-currentTime).total_seconds() >= 0))):
print "+++++ Currently Playing:", row[3] print("+++++ Currently Playing:", row[3])
with tag('tr', klass='bg-info'): with tag('tr', klass='bg-info'):
with tag('th', scope='row'): with tag('th', scope='row'):
@@ -405,13 +407,13 @@ class PseudoDailyScheduleController():
if not os.path.exists(writepath): if not os.path.exists(writepath):
os.makedirs(writepath) os.makedirs(writepath)
if not os.path.exists(writepath+fileName): if not os.path.exists(writepath+fileName):
file(writepath+fileName, 'w').close() open(writepath+fileName, 'w').close()
mode = 'r+' mode = 'r+'
with open(writepath+fileName, mode) as f: with open(writepath+fileName, mode) as f:
f.seek(0) f.seek(0)
first_line = f.read() first_line = f.read()
if self.DEBUG: if self.DEBUG:
print "+++++ Html refresh flag: {}".format(first_line) print("+++++ Html refresh flag: {}".format(first_line))
if first_line == '' or first_line == "0": if first_line == '' or first_line == "0":
f.seek(0) f.seek(0)
f.truncate() f.truncate()
@@ -437,28 +439,28 @@ class PseudoDailyScheduleController():
head,sep,tail = cwd.partition('channels_') head,sep,tail = cwd.partition('channels_')
head,sep,tail = tail.partition('/') head,sep,tail = tail.partition('/')
self.PLEX_CLIENTS = [head] self.PLEX_CLIENTS = [head]
print "CLIENT OVERRIDE: %s" % self.PLEX_CLIENTS print("CLIENT OVERRIDE: %s" % self.PLEX_CLIENTS)
try: try:
if mediaType == "TV Shows": if mediaType == "TV Shows":
# print "Here, Trying to play custom type: ", customSectionName # print "Here, Trying to play custom type: ", customSectionName
print "+++++ Checking Duration for a Match: " print("+++++ Checking Duration for a Match: ")
mediaItems = self.PLEX.library.section(customSectionName).get(mediaParentTitle).episodes() mediaItems = self.PLEX.library.section(customSectionName).get(mediaParentTitle).episodes()
for item in mediaItems: for item in mediaItems:
# print item.duration # print item.duration
if item.title == mediaTitle and item.duration == durationAmount: if item.title == mediaTitle and item.duration == durationAmount:
print "+++++ MATCH FOUND in %s" % item print("+++++ MATCH FOUND in %s" % item)
for client in self.PLEX_CLIENTS: for client in self.PLEX_CLIENTS:
clientItem = self.PLEX.client(client) clientItem = self.PLEX.client(client)
clientItem.playMedia(item, offset=offset) clientItem.playMedia(item, offset=offset)
break break
elif mediaType == "Movies": elif mediaType == "Movies":
movies = self.PLEX.library.section(customSectionName).search(title=mediaTitle) movies = self.PLEX.library.section(customSectionName).search(title=mediaTitle)
print "+++++ Checking Duration for a Match: " print("+++++ Checking Duration for a Match: ")
for item in movies: for item in movies:
# print item.duration # print item.duration
if item.duration == durationAmount: if item.duration == durationAmount:
print "+++++ MATCH FOUND in %s" % item print("+++++ MATCH FOUND in %s" % item)
movie = item movie = item
break break
for client in self.PLEX_CLIENTS: for client in self.PLEX_CLIENTS:
@@ -470,18 +472,18 @@ class PseudoDailyScheduleController():
# We will just play the first value # We will just play the first value
COMMERCIAL_PADDING = config.commercialPadding COMMERCIAL_PADDING = config.commercialPadding
movies = self.PLEX.library.section(customSectionName).search(title=mediaTitle) movies = self.PLEX.library.section(customSectionName).search(title=mediaTitle)
print "+++++ Checking Duration for a Match: " print("+++++ Checking Duration for a Match: ")
for item in movies: for item in movies:
#print item #print item
#print item.duration #print item.duration
if (item.duration+1000*COMMERCIAL_PADDING) == durationAmount or item.duration == durationAmount: if (item.duration+1000*COMMERCIAL_PADDING) == durationAmount or item.duration == durationAmount:
print "+++++ MATCH FOUND in %s" % item print("+++++ MATCH FOUND in %s" % item)
movie = item movie = item
break break
try: try:
movie movie
except: except:
print "+++++ Commercial is NOT FOUND, my guess is this is the dirty gap. Picking first one" print("+++++ Commercial is NOT FOUND, my guess is this is the dirty gap. Picking first one")
movie = movies[0] movie = movies[0]
for client in self.PLEX_CLIENTS: for client in self.PLEX_CLIENTS:
@@ -489,11 +491,11 @@ class PseudoDailyScheduleController():
clientItem.playMedia(movie, offset=offset) clientItem.playMedia(movie, offset=offset)
else: else:
print("##### Not sure how to play {}".format(customSectionName)) print("##### Not sure how to play {}".format(customSectionName))
print "+++++ Done." print("+++++ Done.")
except Exception as e: except Exception as e:
print e.__doc__ print(e.__doc__)
print e.message print(e.message)
print "##### There was an error trying to play the media." print("##### There was an error trying to play the media.")
pass pass
def stop_media(self): def stop_media(self):
@@ -538,13 +540,13 @@ class PseudoDailyScheduleController():
def play(self, row, datalist, offset=0): def play(self, row, datalist, offset=0):
print str("##### Starting Media: '{}'".format(row[3])).encode('UTF-8') print(str("##### Starting Media: '{}'".format(row[3])).encode('UTF-8'))
print str("##### Media Offset: '{}' seconds.".format(int(offset / 1000))).encode('UTF-8') print(str("##### Media Offset: '{}' seconds.".format(int(offset / 1000))).encode('UTF-8'))
if self.DEBUG: if self.DEBUG:
print str(row).encode('UTF-8') print(str(row).encode('UTF-8'))
timeB = datetime.strptime(row[8], '%I:%M:%S %p') timeB = datetime.strptime(row[8], '%I:%M:%S %p')
print "Here, row[13]", row[13] print("Here, row[13]", row[13])
self.play_media(row[11], row[6], row[3], offset, row[13], row[7]) self.play_media(row[11], row[6], row[3], offset, row[13], row[7])
self.write_schedule_to_file( self.write_schedule_to_file(
@@ -668,7 +670,7 @@ class PseudoDailyScheduleController():
((currentTime-timeBStart).total_seconds() >= 0 and \ ((currentTime-timeBStart).total_seconds() >= 0 and \
(midnight-currentTime).total_seconds() >= 0))): (midnight-currentTime).total_seconds() >= 0))):
print "+++++ Made the conditional & found item: {}".format(row[6]) print("+++++ Made the conditional & found item: {}".format(row[6]))
return self.get_show_photo( return self.get_show_photo(
row[13], row[13],
@@ -720,7 +722,7 @@ class PseudoDailyScheduleController():
((currentTime-timeBStart).total_seconds() >= 0 and \ ((currentTime-timeBStart).total_seconds() >= 0 and \
(midnight-currentTime).total_seconds() >= 0))): (midnight-currentTime).total_seconds() >= 0))):
print "+++++ Made the conditional & found item: {}".format(row[6]) print("+++++ Made the conditional & found item: {}".format(row[6]))
return row[6] + " - " + row[3] if row[11] == "TV Shows" else row[3] return row[6] + " - " + row[3] if row[11] == "TV Shows" else row[3]
@@ -737,7 +739,7 @@ class PseudoDailyScheduleController():
def make_xml_schedule(self, datalist): def make_xml_schedule(self, datalist):
print "##### ", "Writing XML / HTML to file." print("##### ", "Writing XML / HTML to file.")
now = datetime.now() now = datetime.now()
now = now.replace(year=1900, month=1, day=1) now = now.replace(year=1900, month=1, day=1)
@@ -745,7 +747,7 @@ class PseudoDailyScheduleController():
itemTitle = self.manually_get_now_playing_title(now, datalist) itemTitle = self.manually_get_now_playing_title(now, datalist)
print "+++++ The path to the bgImage: {}".format(bgImage) print("+++++ The path to the bgImage: {}".format(bgImage))
self.write_refresh_bool_to_file() self.write_refresh_bool_to_file()
self.write_schedule_to_file(self.get_html_from_daily_schedule(now, bgImage, datalist, itemTitle)) self.write_schedule_to_file(self.get_html_from_daily_schedule(now, bgImage, datalist, itemTitle))

View File

@@ -1,6 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
from Media import Media from .Media import Media
class Video(Media): class Video(Media):

View File

@@ -1,10 +1,10 @@
from PseudoChannelDatabase import PseudoChannelDatabase from .PseudoChannelDatabase import PseudoChannelDatabase
from Commercial import Commercial from .Commercial import Commercial
from Episode import Episode from .Episode import Episode
from Movie import Movie from .Movie import Movie
from Media import Media from .Media import Media
from Music import Music from .Music import Music
from Video import Video from .Video import Video
from PseudoDailyScheduleController import PseudoDailyScheduleController from .PseudoDailyScheduleController import PseudoDailyScheduleController
from PseudoChannelCommercial import PseudoChannelCommercial from .PseudoChannelCommercial import PseudoChannelCommercial
from PseudoChannelRandomMovie import PseudoChannelRandomMovie from .PseudoChannelRandomMovie import PseudoChannelRandomMovie