File: //home/arjun/projects/buyercall_forms/buyercall/buyercall/blueprints/webhooks/models.py
from datetime import datetime
from sqlalchemy import and_
from buyercall.lib.util_sqlalchemy import ResourceMixin
from buyercall.extensions import db
class Webhook(ResourceMixin, db.Model):
__tablename__ = 'webhooks'
id = db.Column(db.Integer, primary_key=True)
webhook_url = db.Column(db.String(64), nullable=False, server_default='')
security_token = db.Column(db.String(256), nullable=False, server_default='')
partnership_id = db.Column(db.Integer, db.ForeignKey(
'partnerships.id', name='fk_webhooks_partnership_id', onupdate='CASCADE', ondelete='CASCADE'),
index=True, nullable=False)
deactivated_on = db.Column(db.DateTime(), nullable=True)
is_deactivated = db.Column(db.Boolean(), nullable=False, server_default='0', default=False)
@classmethod
def create(cls, webhook_url, token, partnership_id, is_deactivated):
"""
Create new webhook.
:return: int - webhook id
"""
webhook_id = -1
if is_deactivated:
deactivated_on = datetime.now()
else:
deactivated_on = None
webhook = Webhook.query \
.filter(and_(Webhook.partnership_id == partnership_id, Webhook.is_deactivated == False)) \
.first()
if webhook is None:
new_webhook = Webhook(
webhook_url=webhook_url,
security_token=token,
partnership_id=partnership_id,
deactivated_on=deactivated_on,
is_deactivated=is_deactivated
)
db.session.add(new_webhook)
db.session.flush()
webhook_id = new_webhook.id
db.session.commit()
else:
webhook_id = -2
return webhook_id
@classmethod
def deactivate(cls, id, partnership_id):
"""
Deactivate webhook. The is_deactivated flag will be set.
:return: bool
"""
webhook = Webhook.query\
.filter(and_(Webhook.id == id,
Webhook.partnership_id == partnership_id))\
.first()
if webhook:
webhook.is_deactivated = True
webhook.deactivated_on = datetime.now()
db.session.commit()
return True
else:
return False
@classmethod
def update(cls, id, partnership_id, webhook_url, token):
"""
Update the webhook details.
:return: bool
"""
webhook = Webhook.query\
.filter(and_(Webhook.id == id, Webhook.partnership_id == partnership_id))\
.first()
if webhook:
if webhook_url:
webhook.webhook_url = webhook_url
if token:
webhook.security_token = token
db.session.commit()
return True
return False
@property
def deactivated_on_datetime(self):
""" Return the date/time this webhook was deactivated on
"""
if self.deactivated_on is not None and self.deactivated_on is not '':
return self.deactivated_on.strftime('%Y-%m-%d %H:%M:%S')
return ''
@property
def date_created(self):
""" Return the date the webhook was created
"""
return self.created_on.strftime('%Y-%m-%d %H:%M:%S')
@property
def date_updated(self):
""" Return the date the webhook was updated
"""
return self.updated_on.strftime('%Y-%m-%d %H:%M:%S')