1
0
mirror of https://github.com/b4tman/sync_ics2gcal synced 2024-11-10 23:36:52 +00:00
sync_ics2gcal/gcal_sync/gcal.py

285 lines
9.0 KiB
Python
Raw Normal View History

2018-04-05 08:16:20 +00:00
from apiclient import discovery
import httplib2
import logging
from oauth2client import service_account
from pytz import utc
import sys
class GoogleCalendarService():
2018-04-05 17:25:17 +00:00
"""class for make google calendar service Resource
Returns:
service Resource
"""
2018-04-05 08:16:20 +00:00
@staticmethod
def from_srv_acc_file(service_account_file):
2018-04-05 17:25:17 +00:00
"""make service Resource from service account filename (authorize)
Returns:
service Resource
"""
2018-04-05 08:16:20 +00:00
scopes = 'https://www.googleapis.com/auth/calendar'
credentials = service_account.ServiceAccountCredentials.from_json_keyfile_name(
service_account_file, scopes=scopes)
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)
return service
2018-04-11 12:41:08 +00:00
def select_event_key(event):
"""select event key for logging
Arguments:
event -- event resource
Returns:
key name or None if no key found
"""
key = None
if 'iCalUID' in event:
key = 'iCalUID'
elif 'id' in event:
key = 'id'
return key
2018-04-05 08:16:20 +00:00
class GoogleCalendar():
2018-04-05 17:25:17 +00:00
"""class to interact with calendar on google
"""
2018-04-05 08:16:20 +00:00
logger = logging.getLogger('GoogleCalendar')
def __init__(self, service, calendarId):
self.service = service
self.calendarId = calendarId
2018-04-11 12:41:08 +00:00
def _make_request_callback(self, action, events_by_req):
"""make callback for log result of batch request
Arguments:
action -- action name
events_by_req -- list of events ordered by request id
Returns:
callback function
"""
def callback(request_id, response, exception):
event = events_by_req[int(request_id)]
key = select_event_key(event)
if exception is not None:
self.logger.error('failed to %s event with %s: %s, exception: %s',
action, key, event.get(key), str(exception))
else:
resp_key = select_event_key(response)
if resp_key is not None:
event = response
key = resp_key
self.logger.info('event %s ok, %s: %s',
action, key, event.get(key))
return callback
2018-04-05 08:16:20 +00:00
def list_events_from(self, start):
2018-04-05 17:25:17 +00:00
""" list events from calendar, where start date >= start
"""
fields = 'nextPageToken,items(id,iCalUID,updated)'
2018-04-05 08:16:20 +00:00
events = []
page_token = None
timeMin = utc.normalize(start.astimezone(utc)).replace(
tzinfo=None).isoformat() + 'Z'
while True:
response = self.service.events().list(calendarId=self.calendarId, pageToken=page_token,
2018-04-05 11:25:31 +00:00
singleEvents=True, timeMin=timeMin, fields=fields).execute()
2018-04-05 08:16:20 +00:00
if 'items' in response:
events.extend(response['items'])
page_token = response.get('nextPageToken')
if not page_token:
break
self.logger.info('%d events listed', len(events))
return events
def find_exists(self, events):
2018-04-05 17:25:17 +00:00
""" find existing events from list, by 'iCalUID' field
2018-04-05 08:16:20 +00:00
Arguments:
events {list} -- list of events
Returns:
tuple -- (events_exist, events_not_found)
events_exist - list of tuples: (new_event, exists_event)
"""
2018-04-05 17:25:17 +00:00
fields = 'items(id,iCalUID,updated)'
2018-04-05 08:16:20 +00:00
events_by_req = []
exists = []
not_found = []
def list_callback(request_id, response, exception):
found = False
event = events_by_req[int(request_id)]
if exception is None:
found = ([] != response['items'])
else:
self.logger.error('exception %s, while listing event with UID: %s', str(
exception), event['iCalUID'])
if found:
exists.append(
(event, response['items'][0]))
else:
not_found.append(events_by_req[int(request_id)])
batch = self.service.new_batch_http_request(callback=list_callback)
i = 0
for event in events:
events_by_req.append(event)
batch.add(self.service.events().list(calendarId=self.calendarId,
2018-04-05 11:25:31 +00:00
iCalUID=event['iCalUID'], showDeleted=True, fields=fields), request_id=str(i))
2018-04-05 08:16:20 +00:00
i += 1
batch.execute()
self.logger.info('%d events exists, %d not found',
len(exists), len(not_found))
return exists, not_found
def insert_events(self, events):
2018-04-05 17:25:17 +00:00
""" insert list of events
2018-04-05 08:16:20 +00:00
Arguments:
2018-04-05 17:25:17 +00:00
events - events list
2018-04-05 08:16:20 +00:00
"""
2018-04-05 17:25:17 +00:00
fields = 'id'
2018-04-05 08:16:20 +00:00
events_by_req = []
2018-04-11 12:41:08 +00:00
insert_callback = self._make_request_callback('insert', events_by_req)
2018-04-05 08:16:20 +00:00
batch = self.service.new_batch_http_request(callback=insert_callback)
i = 0
for event in events:
events_by_req.append(event)
batch.add(self.service.events().insert(
2018-04-05 11:25:31 +00:00
calendarId=self.calendarId, body=event, fields=fields), request_id=str(i))
2018-04-05 08:16:20 +00:00
i += 1
batch.execute()
def patch_events(self, event_tuples):
2018-04-05 17:25:17 +00:00
""" patch (update) events
2018-04-05 08:16:20 +00:00
Arguments:
2018-04-05 17:25:17 +00:00
event_tuples -- list of tuples: (new_event, exists_event)
2018-04-05 08:16:20 +00:00
"""
2018-04-05 17:25:17 +00:00
fields = 'id'
2018-04-05 08:16:20 +00:00
events_by_req = []
2018-04-11 12:41:08 +00:00
patch_callback = self._make_request_callback('patch', events_by_req)
2018-04-05 08:16:20 +00:00
batch = self.service.new_batch_http_request(callback=patch_callback)
i = 0
for event_new, event_old in event_tuples:
if 'id' not in event_old:
continue
events_by_req.append(event_new)
batch.add(self.service.events().patch(
2018-04-05 11:25:31 +00:00
calendarId=self.calendarId, eventId=event_old['id'], body=event_new), fields=fields, request_id=str(i))
2018-04-05 08:16:20 +00:00
i += 1
batch.execute()
def update_events(self, event_tuples):
2018-04-05 17:25:17 +00:00
""" update events
2018-04-05 08:16:20 +00:00
Arguments:
2018-04-05 17:25:17 +00:00
event_tuples -- list of tuples: (new_event, exists_event)
2018-04-05 08:16:20 +00:00
"""
2018-04-05 17:25:17 +00:00
fields = 'id'
2018-04-05 08:16:20 +00:00
events_by_req = []
2018-04-11 12:41:08 +00:00
update_callback = self._make_request_callback('update', events_by_req)
2018-04-05 08:16:20 +00:00
batch = self.service.new_batch_http_request(callback=update_callback)
i = 0
for event_new, event_old in event_tuples:
if 'id' not in event_old:
continue
events_by_req.append(event_new)
batch.add(self.service.events().update(
2018-04-05 11:25:31 +00:00
calendarId=self.calendarId, eventId=event_old['id'], body=event_new, fields=fields), request_id=str(i))
2018-04-05 08:16:20 +00:00
i += 1
batch.execute()
def delete_events(self, events):
2018-04-05 17:25:17 +00:00
""" delete events
2018-04-05 08:16:20 +00:00
Arguments:
2018-04-05 17:25:17 +00:00
events -- list of events
2018-04-05 08:16:20 +00:00
"""
events_by_req = []
2018-04-11 12:41:08 +00:00
delete_callback = self._make_request_callback('delete', events_by_req)
2018-04-05 08:16:20 +00:00
batch = self.service.new_batch_http_request(callback=delete_callback)
i = 0
for event in events:
events_by_req.append(event)
batch.add(self.service.events().delete(
calendarId=self.calendarId, eventId=event['id']), request_id=str(i))
i += 1
batch.execute()
2018-04-05 17:37:09 +00:00
def create(self, summary, timeZone=None):
"""create calendar
2018-04-11 12:41:08 +00:00
2018-04-05 17:37:09 +00:00
Arguments:
summary -- new calendar summary
2018-04-11 12:41:08 +00:00
2018-04-05 17:37:09 +00:00
Keyword Arguments:
timeZone -- new calendar timezone as string (optional)
Returns:
calendar Resource
"""
calendar = {'summary': summary}
if timeZone is not None:
calendar['timeZone'] = timeZone
created_calendar = self.service.calendars().insert(body=calendar).execute()
self.calendarId = created_calendar['id']
return created_calendar
def delete(self):
"""delete calendar
"""
self.service.calendars().delete(calendarId=self.calendarId).execute()
2018-04-05 08:16:20 +00:00
def make_public(self):
2018-04-05 17:25:17 +00:00
"""make calendar puplic
"""
2018-04-05 08:16:20 +00:00
rule_public = {
'scope': {
'type': 'default',
},
'role': 'reader'
}
return self.service.acl().insert(calendarId=self.calendarId, body=rule_public).execute()
def add_owner(self, email):
2018-04-05 17:25:17 +00:00
"""add calendar owner by email
Arguments:
email -- email to add
"""
2018-04-05 08:16:20 +00:00
rule_owner = {
'scope': {
'type': 'user',
'value': email,
},
'role': 'owner'
}
return self.service.acl().insert(calendarId=self.calendarId, body=rule_owner).execute()