blechreiz-website/eventplanner_gcal/models.py

60 lines
2.2 KiB
Python
Raw Permalink Normal View History

2014-03-08 22:36:25 +01:00
import logging
import uuid
2014-04-26 11:17:10 +02:00
from eventplanner.models import Event
from django.contrib.auth.models import User
2014-04-26 11:17:10 +02:00
from apiclient.channel import Channel
from django.db import models
2014-03-08 22:36:25 +01:00
2014-04-26 11:17:10 +02:00
logger = logging.getLogger(__name__)
2014-03-08 22:36:25 +01:00
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):
2014-04-26 11:17:10 +02:00
"""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)
2014-03-08 22:36:25 +01:00
class GCalPushChannel(models.Model):
"""This table has either zero or one entry. Required to store if a channel already exists,
2014-04-26 11:17:10 +02:00
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()
2019-01-05 13:04:20 +01:00
def to_google_channel(self):
return Channel('web_hook', self.id, self.token, self.address, self.expiration, resource_id=self.resource_id)
@staticmethod
2019-01-05 13:04:20 +01:00
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
2019-01-05 13:04:20 +01:00
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)
2019-01-05 13:04:20 +01:00
dbChannel = GCalPushChannel.from_google_channel(gChannel)
dbChannel.save()
@staticmethod
2019-01-05 13:04:20 +01:00
def stop(service, google_channel):
channel_service = service.channels()
channel_service.stop(body=google_channel.body()).execute()
GCalPushChannel.from_google_channel(google_channel).delete()