2019-01-11 19:16:01 +00:00
|
|
|
from django.conf import settings
|
|
|
|
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
|
|
|
|
from django.contrib.contenttypes.models import ContentType
|
2019-11-24 14:07:19 +00:00
|
|
|
from django.core.cache import cache
|
2019-01-11 19:16:01 +00:00
|
|
|
from django.db import models
|
|
|
|
from django.utils import timezone
|
|
|
|
from telebot import TeleBot
|
2019-01-19 06:52:00 +00:00
|
|
|
from yamlfield.fields import YAMLField
|
2019-01-11 19:16:01 +00:00
|
|
|
|
|
|
|
from feeds.tasks import execute_feed
|
|
|
|
|
|
|
|
|
|
|
|
class Feed(models.Model):
|
|
|
|
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
|
|
|
|
title = models.CharField(max_length=32)
|
|
|
|
chat_id = models.CharField(max_length=33)
|
|
|
|
check_interval = models.DurationField(help_text='in seconds')
|
|
|
|
last_check = models.DateTimeField(null=True, blank=True)
|
2021-03-11 23:11:45 +00:00
|
|
|
last_id = models.JSONField(null=True, blank=True)
|
2019-01-11 19:16:01 +00:00
|
|
|
|
|
|
|
config_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
|
|
|
|
config_id = models.PositiveIntegerField()
|
|
|
|
config = GenericForeignKey('config_type', 'config_id')
|
|
|
|
|
2019-11-24 14:07:19 +00:00
|
|
|
@property
|
|
|
|
def lock_key(self):
|
|
|
|
return 'feed-{}-lock'.format(self.pk)
|
|
|
|
|
|
|
|
@property
|
|
|
|
def locked(self):
|
|
|
|
return bool(cache.get(self.lock_key))
|
|
|
|
|
2019-01-11 19:16:01 +00:00
|
|
|
def run_check(self):
|
2019-11-24 14:07:19 +00:00
|
|
|
if self.locked:
|
2019-03-14 06:53:06 +00:00
|
|
|
return False
|
2019-01-11 19:16:01 +00:00
|
|
|
if self.last_check and timezone.now() < self.last_check + self.check_interval:
|
2019-03-14 06:53:06 +00:00
|
|
|
return False
|
2019-01-11 19:16:01 +00:00
|
|
|
|
2019-11-24 14:07:19 +00:00
|
|
|
cache.set(self.lock_key, 1, timeout=60)
|
2019-03-10 07:20:53 +00:00
|
|
|
execute_feed.apply_async(args=(self.pk,), shadow=str(self))
|
2019-03-14 06:53:06 +00:00
|
|
|
return True
|
2019-01-11 19:16:01 +00:00
|
|
|
|
2019-01-26 06:36:56 +00:00
|
|
|
def __str__(self):
|
2019-03-10 07:11:59 +00:00
|
|
|
return f'#{self.pk} {self.title}'
|
2019-01-26 06:36:56 +00:00
|
|
|
|
2019-01-11 19:16:01 +00:00
|
|
|
class Meta:
|
|
|
|
unique_together = ('config_type', 'config_id')
|
|
|
|
|
|
|
|
|
|
|
|
class FeedModuleConfig(models.Model):
|
|
|
|
_feeds = GenericRelation(Feed, content_type_field='config_type', object_id_field='config_id')
|
|
|
|
|
|
|
|
MODULE_NAME = '<Not set>'
|
|
|
|
|
|
|
|
@property
|
|
|
|
def feed(self):
|
|
|
|
return self._feeds.get()
|
|
|
|
|
|
|
|
@property
|
|
|
|
def content_type(self):
|
|
|
|
return ContentType.objects.get_for_model(self.__class__)
|
|
|
|
|
|
|
|
def execute(self, bot: TeleBot, chat_id, last_id):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
abstract = True
|