60 lines
2.2 KiB
Python
60 lines
2.2 KiB
Python
import logging
|
|
import uuid
|
|
from eventplanner.models import Event
|
|
from django.contrib.auth.models import User
|
|
|
|
from apiclient.channel import Channel
|
|
from django.db import models
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class UserGCalCoupling(models.Model):
|
|
# For every user in this table the gcal coupling is activated
|
|
user = models.OneToOneField(User, on_delete=models.CASCADE)
|
|
email = models.CharField(max_length=1024)
|
|
|
|
|
|
class GCalMapping(models.Model):
|
|
"""Mapping between event id at google and local event id"""
|
|
gcal_id = models.CharField(max_length=64)
|
|
event = models.OneToOneField(Event, primary_key=True, on_delete=models.CASCADE)
|
|
|
|
|
|
class GCalPushChannel(models.Model):
|
|
"""This table has either zero or one entry. Required to store if a channel already exists,
|
|
when it expires and how to stop (renew) the channel
|
|
"""
|
|
|
|
id = models.CharField(max_length=128, primary_key=True)
|
|
address = models.CharField(max_length=256)
|
|
token = models.CharField(max_length=128)
|
|
resource_id = models.CharField(max_length=128)
|
|
expiration = models.IntegerField()
|
|
|
|
def to_google_channel(self):
|
|
return Channel('web_hook', self.id, self.token, self.address, self.expiration, resource_id=self.resource_id)
|
|
|
|
@staticmethod
|
|
def from_google_channel(google_channel):
|
|
return GCalPushChannel(id=google_channel.id,
|
|
address=google_channel.address,
|
|
token=google_channel.token,
|
|
expiration=google_channel.expiration,
|
|
resource_id=google_channel.resource_id)
|
|
|
|
@staticmethod
|
|
def create_new(callback_url, service, ttl=None):
|
|
gChannel = Channel('web_hook', str(uuid.uuid4()), 'blechreizGcal', callback_url, params={'ttl': int(ttl)})
|
|
response = service.events().watch(calendarId='primary', body=gChannel.body()).execute()
|
|
gChannel.update(response)
|
|
|
|
dbChannel = GCalPushChannel.from_google_channel(gChannel)
|
|
dbChannel.save()
|
|
|
|
@staticmethod
|
|
def stop(service, google_channel):
|
|
channel_service = service.channels()
|
|
channel_service.stop(body=google_channel.body()).execute()
|
|
GCalPushChannel.from_google_channel(google_channel).delete()
|