diff --git a/PseudoChannel.py b/PseudoChannel.py index f2e1258..26f79b3 100644 --- a/PseudoChannel.py +++ b/PseudoChannel.py @@ -8,6 +8,7 @@ from src import Episode from src import Music from src import Video from src import PseudoDailyScheduleController +from src import GoogleCalendar from plexapi.server import PlexServer @@ -32,6 +33,8 @@ class PseudoChannel(): PLEX = PlexServer(config.baseurl, config.token) MEDIA = [] + USING_GCALENDAR = config.useGoogleCalendar + GKEY = config.gkey def __init__(self): @@ -179,6 +182,107 @@ class PseudoChannel(): bar_length = 40 ) + def update_schedule_from_google_calendar(self): + + self.gcal = GoogleCalendar(self.GKEY) + + events = self.gcal.get_entries() + + self.db.create_tables() + + self.db.remove_all_scheduled_items() + + scheduled_days_list = [ + "mondays", + "tuesdays", + "wednesdays", + "thursdays", + "fridays", + "saturdays", + "sundays", + "weekdays", + "weekends", + "everyday" + ] + + section_dict = { + "TV Shows" : ["series", "shows", "tv", "episodes", "tv shows", "show"], + "Movies" : ["movie", "movies", "films", "film"], + "Videos" : ["video", "videos", "vid"], + "Music" : ["music", "songs", "song", "tune", "tunes"] + } + + weekday_dict = { + "0" : ["mondays", "weekdays", "everyday"], + "1" : ["tuesdays", "weekdays", "everyday"], + "2" : ["wednesdays", "weekdays", "everyday"], + "3" : ["thursdays", "weekdays", "everyday"], + "4" : ["fridays", "weekdays", "everyday"], + "5" : ["saturdays", "weekends", "everyday"], + "6" : ["sundays", "weekends", "everyday"], + } + + for event in events: + + titlelist = [x.strip() for x in event['summary'].split(',')] + + start = event['start'].get('dateTime', event['start'].get('date')) + + s = datetime.datetime.strptime(start,"%Y-%m-%dT%H:%M:%S-07:00") + + weekno = s.weekday() + + for key, value in section_dict.items(): + + if str(titlelist[0]).lower() == key or str(titlelist[0]).lower() in value: + + print "Adding {} to schedule.".format(titlelist[1]) + + title = titlelist[1] + + # s.strftime('%I:%M'), event["summary"] + natural_start_time = self.translate_time(s.strftime('%I:%M %p')) + + natural_end_time = 0 + + section = key + + for dnum, daylist in weekday_dict.items(): + + #print int(weekno), int(dnum) + + if int(weekno) == int(dnum): + + day_of_week = daylist[0] + + strict_time = titlelist[2] if len(titlelist) > 2 else "true" + + time_shift = "5" + + overlap_max = "" + + print natural_start_time + + start_time_unix = datetime.datetime.strptime( + self.translate_time(natural_start_time), + '%I:%M %p').strftime('%Y-%m-%d %H:%M:%S') + + #print "Adding: ", time.tag, section, time.text, time.attrib['title'] + + self.db.add_schedule_to_db( + 0, # mediaID + title, # title + 0, # duration + natural_start_time, # startTime + natural_end_time, # endTime + day_of_week, # dayOfWeek + start_time_unix, # startTimeUnix + section, # section + strict_time, # strictTime + time_shift, # timeShift + overlap_max, # overlapMax + ) + def update_schedule(self): self.db.create_tables() @@ -647,6 +751,37 @@ class PseudoChannel(): previous_episode = entry + def get_daily_schedule_as_media_object_list(self): + + for i, item in enumerate(self.db.get_daily_schedule(), start=0): + + if item[11] == "TV Shows": + + """episode = Episode( + + )""" + pass + + elif item[11] == "Movies": + + pass + + elif item[11] == "Music": + + pass + + elif item[11] == "Commercials": + + pass + + elif item[11] == "Videos": + + pass + + else: + + pass + def show_clients(self): print "##### Connected Clients:" @@ -743,6 +878,15 @@ if __name__ == '__main__': action='store_true', help='Show scheduled media for today.') + ''' + * + * Update Schedule based on Google Cal: "python PseudoChannel.py -gc" + * + ''' + parser.add_argument('-gc', + action='store_true', + help='Updates the schedule based on entries in the google calendar.') + globals().update(vars(parser.parse_args())) args = parser.parse_args() @@ -757,6 +901,10 @@ if __name__ == '__main__': pseudo_channel.update_schedule() + if args.gc: + + pseudo_channel.update_schedule_from_google_calendar() + if args.g: pseudo_channel.generate_daily_schedule() diff --git a/pseudo_config.py b/pseudo_config.py index 07f3c50..ab0435b 100644 --- a/pseudo_config.py +++ b/pseudo_config.py @@ -18,6 +18,11 @@ line so it looks like: "Movies" : ["Films"], + + 6) For Google Calendar integration add you "gkey" to the "plex_token.py" file + ...(https://docs.simplecalendar.io/find-google-calendar-id/): + + gkey = "the key" """ @@ -28,6 +33,7 @@ import plex_token as plex_token baseurl = 'http://media.home:32400' token = plex_token.token +gkey = plex_token.gkey ''' * @@ -42,3 +48,5 @@ plexLibraries = { "Music" : ["Music"], "Commercials" : ["Commercials"], } + +useGoogleCalendar = True diff --git a/src/GoogleCalendar.py b/src/GoogleCalendar.py new file mode 100644 index 0000000..216ebaa --- /dev/null +++ b/src/GoogleCalendar.py @@ -0,0 +1,97 @@ +from __future__ import print_function +import httplib2 +import os + +from apiclient import discovery +from oauth2client import client +from oauth2client import tools +from oauth2client.file import Storage + +import datetime + +"""try: + import argparse + flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() +except ImportError: + flags = None""" + + +class GoogleCalendar(): + + # If modifying these scopes, delete your previously saved credentials + # at ~/.credentials/calendar-python-quickstart.json + SCOPES = 'https://www.googleapis.com/auth/calendar.readonly' + CLIENT_SECRET_FILE = 'client_secret.json' + APPLICATION_NAME = 'Google Calendar API Python Quickstart' + + KEY = '' + + def __init__(self, key): + + self.KEY = key + + def get_credentials(self): + """Gets valid user credentials from storage. + + If nothing has been stored, or if the stored credentials are invalid, + the OAuth2 flow is completed to obtain the new credentials. + + Returns: + Credentials, the obtained credential. + """ + home_dir = os.path.expanduser('~') + credential_dir = os.path.join(home_dir, '.credentials') + if not os.path.exists(credential_dir): + os.makedirs(credential_dir) + credential_path = os.path.join(credential_dir, + 'calendar-python-quickstart.json') + + store = Storage(credential_path) + credentials = store.get() + if not credentials or credentials.invalid: + flow = client.flow_from_clientsecrets(self.CLIENT_SECRET_FILE, self.SCOPES) + flow.user_agent = self.APPLICATION_NAME + if flags: + credentials = tools.run_flow(flow, store, flags) + else: # Needed only for compatibility with Python 2.6 + credentials = tools.run(flow, store) + print('Storing credentials to ' + credential_path) + return credentials + + def get_entries(self): + """Shows basic usage of the Google Calendar API. + + Creates a Google Calendar API service object and outputs a list of the next + 10 events on the user's calendar. + """ + credentials = self.get_credentials() + http = credentials.authorize(httplib2.Http()) + service = discovery.build('calendar', 'v3', http=http) + + now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time + + end = (datetime.datetime.now() + datetime.timedelta(days=1)) + + end = end.isoformat() + 'Z' # 'Z' indicates UTC time + + #print(now) + + #print(end) + + print('Getting the upcoming 10 events') + eventsResult = service.events().list( + calendarId=self.KEY, timeMin=now, timeMax=end, maxResults=250, singleEvents=True, + orderBy='startTime').execute() + events = eventsResult.get('items', []) + + if not events: + print('No upcoming events found.') + for event in events: + #start = event['start'].get('dateTime', event['start'].get('date')) + #print(start, event['summary']) + pass + return events + + +if __name__ == '__main__': + pass \ No newline at end of file diff --git a/src/PseudoChannelCommercial.py b/src/PseudoChannelCommercial.py new file mode 100644 index 0000000..e69de29 diff --git a/src/__init__.py b/src/__init__.py index 21d061f..2c68fd8 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -5,4 +5,5 @@ from Movie import Movie from Media import Media from Music import Music from Video import Video -from PseudoDailyScheduleController import PseudoDailyScheduleController \ No newline at end of file +from PseudoDailyScheduleController import PseudoDailyScheduleController +from GoogleCalendar import GoogleCalendar \ No newline at end of file