You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

128 lines
4.4 KiB

# from __future__ import print_function
from apiclient import discovery
import datetime
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from oauth2client.service_account import ServiceAccountCredentials
import httplib2
import os
import pytz
import sys
import argparse
import tzlocal
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
dt_fmt = '%Y-%m-%dT%H:%M:%S'
APPLICATION_NAME = 'Google Calendar API Python'
def dateTime(datetime):
if not datetime.tzinfo:
datetime = datetime.astimezone()
zone = tzlocal.get_localzone().zone
datetime = datetime.isoformat(timespec='seconds')
return {
"timeZone":zone,
"dateTime":datetime,
}
class api:
def __init__(self,client_secret_file,credentials_dir,scopes = 'https://www.googleapis.com/auth/calendar'):
self.client_secret_file = client_secret_file
self.credentials_dir = credentials_dir
self.scopes = scopes
self._service = None
self._service_settime = None
self.calendars=self.get_calendars()
self.ids = dict((calendar['summary'].lower(),calendar['id']) for calendar in self.calendars)
def get_credentials(self):
credential_path = os.path.join(self.credentials_dir,
'token.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 = 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 build_service(self):
credentials = self.get_credentials()
http = credentials.authorize(httplib2.Http())
service = build('calendar', 'v3', http=http, cache_discovery=False)
return service
def _needs_renewal(self):
now = datetime.datetime.today()
if self._service_settime:
return (now - self._service_settime) > datetime.timedelta(seconds = 60**2)
else:
return True
# elif
@property
def service(self):
if self._needs_renewal():
service = self.build_service()
self._service = service
self._service_settime = datetime.datetime.today()
return service
else:
return self._service
def create_event(self, calendar_id, body):
service = self.service
event = service.events().insert(calendarId=calendar_id, body=body).execute()
return event['id']
def update_event(self,calendar_id, event_id, body):
service = self.service
try:
event = service.events().get(calendarId=calendar_id, eventId=event_id).execute()
except HttpError as e:
if e.resp.status==404:
return self.create_event(calendar_id, body)
updated_event = service.events().update(calendarId=calendar_id, eventId=event['id'], body=body).execute()
return updated_event["id"]
def get_calendars(self):
page_token = None
cl = []
while True:
calendar_list = self.service.calendarList().list(pageToken=page_token).execute()
cl += list(calendar_list_entry for calendar_list_entry in calendar_list['items'])
page_token = calendar_list.get('nextPageToken')
if not page_token:
break
return cl
def get_events(self,id):
service = self.service
try:
id = self.ids[id]
except KeyError:
pass
page_token = None
ret = []
while True:
events = service.events().list(calendarId='primary', pageToken=page_token).execute()
ret += events['items']
page_token = events.get('nextPageToken')
if not page_token:
break
return ret
# if __name__ == "__main__":
# test = api(r"X:\Users\Ralphie\Downloads\client_secret.json",r"X:\Users\Ralphie\Downloads")