from django.db import models from django.utils import timezone from django.conf import settings import datetime from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.db.models.signals import post_save from django.dispatch import receiver from .syndicators import post_to_medium, build_facebook_feed, post_to_twitter, post_photo_to_flickr, post_to_facebook class FBOAuthToken(models.Model): short_token = models.TextField() long_token = models.TextField(null=True, blank=True) expires = models.DateTimeField(blank=True) created = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.expires) def long_token_link(self): token_url = "https://graph.facebook.com/oauth/access_token?client_id=%s&client_secret=%s&grant_type=fb_exchange_token&fb_exchange_token=%s" % (settings.FACEBOOK_APP_ID, settings.FACEBOOK_APP_SECRET, self.short_token) return token_url class Meta: ordering = ('-expires',) get_latest_by = 'expires' def save(self, *args, **kwargs): self.expires = self.created + datetime.timedelta(60) super(FBOAuthToken, self).save() class Syndicate(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class SyndicatedItem(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') syndicate = models.ManyToManyField(Syndicate) publish_date = models.DateTimeField() STATUS = ( ('1', "Unsent"), ('2', "Sent"), ) status = models.CharField(max_length=1, choices=STATUS, null=True) rel_link = models.CharField(max_length=300, null=True, blank=True) def __str__(self): return str(self.content_object) def syndicated_to(self): return ','.join(str(synd) for synd in self.syndicate.all()) @receiver(post_save, sender=SyndicatedItem) def post_save_events(sender, update_fields, created, instance, **kwargs): print(instance.status) if instance.status == "1": print("---------calling-----------") for item in instance.syndicate.all(): print(item.name) if item.name == "Medium": instance.rel_link = post_to_medium(instance.content_object) instance.status = 2 if item.name == "Facebook Instant Articles": build_facebook_feed() instance.status = 2 if item.name == "Twitter": print("calling function") post_to_twitter(instance.content_object, instance.content_type.name) if item.name == "Flickr": if instance.content_type.name == "lux image": post_photo_to_flickr(instance.content_object) if item.name == "Facebook": post_to_facebook(instance.content_object, instance.content_type.name) post_save.disconnect(post_save_events, sender=SyndicatedItem) instance.status = "2" instance.save() post_save.connect(post_save_events, sender=SyndicatedItem)