-
Notifications
You must be signed in to change notification settings - Fork 12
/
push.py
68 lines (50 loc) · 2.19 KB
/
push.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import time
import rfc3339
from tzlocal import get_localzone
from celery.task import task
from gcalsync.connect import Connection
from gcalsync.models import SyncedEvent, SyncedCalendar
from django.contrib.contenttypes.models import ContentType
from django.utils.timezone import localtime, make_aware
class Pusher(object):
def __init__(self, model):
self.model = model
def get_event_data(self):
event_data = self.set_dates(self.model.to_gcal())
event_data['status'] = 'confirmed'
return event_data
def set_dates(self, event_data):
tz = get_localzone()
start_dt_aware = tz.localize(event_data['start']['dateTime'])
end_dt_aware = tz.localize(event_data['end']['dateTime'])
event_data['start']['dateTime'] = rfc3339.datetimetostr(start_dt_aware)
event_data['end']['dateTime'] = rfc3339.datetimetostr(end_dt_aware)
return event_data
def create_or_update(self):
service = Connection().get_service()
content_type = ContentType.objects.get_for_model(self.model)
event_data = self.get_event_data()
calendar_id = event_data.pop('calendarId')
try:
synced_event = SyncedEvent.objects.get(content_type=content_type,
object_id=self.model.id)
if synced_event.origin == 'google':
return False
g_event = service.events().patch(calendarId=calendar_id,
eventId=synced_event.gcal_event_id, body=event_data).execute()
return g_event
except SyncedEvent.DoesNotExist:
g_event = service.events().insert(calendarId=calendar_id,
body=event_data).execute()
synced_calendar, created = SyncedCalendar.objects.get_or_create(calendar_id=calendar_id)
synced_event = SyncedEvent.objects.create(
content_object=self.model,
gcal_event_id=g_event['id'],
gcal_event_url=g_event['htmlLink'],
synced_calendar=synced_calendar,
origin='app'
)
return g_event
@task
def async_push_to_gcal(instance):
Pusher(instance).create_or_update()