Added google calendar integration... Create a calendar event with a comma dilineated title like, 'Show, Seinfeld, false' where the third value is for strict-time.

This commit is contained in:
Justin Emter
2017-07-24 16:08:38 -07:00
parent 1641602ed8
commit 64e4485718
5 changed files with 255 additions and 1 deletions

View File

@@ -8,6 +8,7 @@ from src import Episode
from src import Music from src import Music
from src import Video from src import Video
from src import PseudoDailyScheduleController from src import PseudoDailyScheduleController
from src import GoogleCalendar
from plexapi.server import PlexServer from plexapi.server import PlexServer
@@ -32,6 +33,8 @@ class PseudoChannel():
PLEX = PlexServer(config.baseurl, config.token) PLEX = PlexServer(config.baseurl, config.token)
MEDIA = [] MEDIA = []
USING_GCALENDAR = config.useGoogleCalendar
GKEY = config.gkey
def __init__(self): def __init__(self):
@@ -179,6 +182,107 @@ class PseudoChannel():
bar_length = 40 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): def update_schedule(self):
self.db.create_tables() self.db.create_tables()
@@ -647,6 +751,37 @@ class PseudoChannel():
previous_episode = entry 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): def show_clients(self):
print "##### Connected Clients:" print "##### Connected Clients:"
@@ -743,6 +878,15 @@ if __name__ == '__main__':
action='store_true', action='store_true',
help='Show scheduled media for today.') 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())) globals().update(vars(parser.parse_args()))
args = parser.parse_args() args = parser.parse_args()
@@ -757,6 +901,10 @@ if __name__ == '__main__':
pseudo_channel.update_schedule() pseudo_channel.update_schedule()
if args.gc:
pseudo_channel.update_schedule_from_google_calendar()
if args.g: if args.g:
pseudo_channel.generate_daily_schedule() pseudo_channel.generate_daily_schedule()

View File

@@ -19,6 +19,11 @@
"Movies" : ["Films"], "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"
""" """
import os, sys import os, sys
@@ -28,6 +33,7 @@ import plex_token as plex_token
baseurl = 'http://media.home:32400' baseurl = 'http://media.home:32400'
token = plex_token.token token = plex_token.token
gkey = plex_token.gkey
''' '''
* *
@@ -42,3 +48,5 @@ plexLibraries = {
"Music" : ["Music"], "Music" : ["Music"],
"Commercials" : ["Commercials"], "Commercials" : ["Commercials"],
} }
useGoogleCalendar = True

97
src/GoogleCalendar.py Normal file
View File

@@ -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

View File

View File

@@ -6,3 +6,4 @@ 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 GoogleCalendar import GoogleCalendar