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 ) 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 ) 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 toGChannel( self ): return Channel( 'web_hook', self.id, self.token, self.address, self.expiration, resource_id = self.resource_id ) @staticmethod def fromGChannel( gChannel ): return GCalPushChannel( id = gChannel.id, address = gChannel.address, token = gChannel.token, expiration = gChannel.expiration, resource_id= gChannel.resource_id ) @staticmethod def createNew( callbackUrl, service, ttl = None ): gChannel = Channel('web_hook', str(uuid.uuid4()), 'blechreizGcal', callbackUrl, params= { 'ttl' : int(ttl) } ) response = service.events().watch( calendarId='primary', body= gChannel.body() ).execute() gChannel.update( response ) dbChannel = GCalPushChannel.fromGChannel( gChannel ) dbChannel.save() @staticmethod def stop( service, gChannel ): channelService = service.channels() channelService.stop( body = gChannel.body() ).execute() GCalPushChannel.fromGChannel( gChannel ).delete()