예제 #1
0
class Guild(BaseModel):
    guild_id = BigIntegerField(primary_key=True)
    owner_id = BigIntegerField(null=False)
    prefix = TextField(default="+", null=False)
    dj_roles = ArrayField(BigIntegerField, null=True, index=False)
    mod_role = BigIntegerField(null=True)
    commands_disabled_channels = ArrayField(BigIntegerField,
                                            null=True,
                                            index=False)
    logs_enabled = BooleanField(default=True)
    log_channel = BigIntegerField(null=True)

    class Meta:
        db_table = 'guilds'

    @classmethod
    def get_settings(cls, guild_id):
        try:
            return Guild.get(guild_id=guild_id)
        except Guild.DoesNotExist:
            return

    @classmethod
    def using_id(cls, guild_id):
        return Guild.get(guild_id=guild_id)
예제 #2
0
class Group(BaseModel):
    DEFAULT_PERMISSIONS = [
        'create_dashboard', 'create_query', 'edit_dashboard', 'edit_query',
        'view_query', 'view_source', 'execute_query'
    ]

    id = peewee.PrimaryKeyField()
    name = peewee.CharField(max_length=100)
    permissions = ArrayField(peewee.CharField, default=DEFAULT_PERMISSIONS)
    tables = ArrayField(peewee.CharField)
    created_at = DateTimeTZField(default=datetime.datetime.now)

    class Meta:
        db_table = 'groups'

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'permissions': self.permissions,
            'tables': self.tables,
            'created_at': self.created_at
        }

    def __unicode__(self):
        return unicode(self.id)
예제 #3
0
class Recipe(Model):
    url = CharField()
    title = CharField()
    ingredients = ArrayField(CharField)
    instructions = ArrayField(TextField)
    avg_rating = FloatField(default=0)

    class Meta:
        database = DATABASE
예제 #4
0
class THN(peewee.Model):
    class Meta:
        database = database
        ordering = ("thn_id", )
        table_name = "vulnerabilities_thn"

    id = peewee.PrimaryKeyField(null=False)
    index = peewee.TextField(default="")
    thn_id = peewee.TextField(default="")
    score = peewee.TextField(default="")
    sort = peewee.TextField(default="")
    lastseen = peewee.TextField(default="")
    object_type = peewee.TextField(default="")
    object_types = ArrayField(peewee.TextField, default=[])
    description = peewee.TextField(default="")
    published = peewee.TextField(default="")
    reporter = peewee.TextField(default="")
    type = peewee.TextField(default="")
    title = peewee.TextField(default="")
    enchantments_score_vector = peewee.TextField(default="")
    enchantments_score_value = peewee.TextField(default="")
    bulletin_family = peewee.TextField(default="")
    cvelist = ArrayField(peewee.TextField, default=[])
    modified = peewee.TextField(default="")
    href = peewee.TextField(default="")
    cvss_score = peewee.TextField(default="")
    cvss_vector = peewee.TextField(default="")

    def __unicode__(self):
        return "thn"

    def __str__(self):
        return str(self.thn_id)

    @property
    def to_json(self):
        return dict(id=self.id,
                    index=self.index,
                    thn_id=self.thn_id,
                    score=self.score,
                    lastseen=self.lastseen,
                    object_type=self.object_type,
                    object_types=self.object_types,
                    description=self.description,
                    published=self.published,
                    reporter=self.reporter,
                    type=self.type,
                    title=self.title,
                    enchantments_score_vector=self.enchantments_score_vector,
                    enchantments_score_value=self.enchantments_score_value,
                    bulletin_family=self.bulletin_family,
                    cvelist=self.cvelist,
                    modified=self.modified,
                    href=self.href,
                    cvss_score=self.cvss_score,
                    cvss_vector=self.cvss_vector)
예제 #5
0
class Flux_surface(BaseModel):
    ids_properties = ForeignKeyField(Ids_properties,
                                     related_name='flux_surface')
    r_minor_norm = FloatField(
        help_text='Minor radius of the flux surface of interest')
    q = FloatField(help_text='Safety factor')
    magnetic_shear_r_minor = FloatField(help_text='Magnetic shear')
    pressure_gradient_norm = FloatField(
        help_text=
        'Total pressure gradient (with respect to r_minor) used to characterise the local magnetic equilibrium'
    )
    ip_sign = SmallIntegerField(
        help_text=
        'Direction of the toroidal plasma current, positive when anticlockwise from above'
    )
    b_field_tor_sign = SmallIntegerField(
        help_text=
        'Direction of the toroidal magnetic field, positive when anticlockwise from above'
    )
    # Original shape
    shape_coefficients_c = ArrayField(
        FloatField,
        help_text=
        'Array containing the c_n coefficients parametrising the flux surface of interest. '
    )
    shape_coefficients_s = ArrayField(
        FloatField,
        help_text=
        'Array containing the s_n coefficients parametrising the flux surface of interest. The first element is always zero.'
    )
    dc_dr_minor_norm = ArrayField(
        FloatField,
        help_text=
        'Radial derivative (with respect to r_minor) of the c_n coefficients')
    ds_dr_minor_norm = ArrayField(
        FloatField,
        help_text=
        'Radial derivative (with respect to r_minor) of the s_n coefficients. The first element is always zero.'
    )
    # Derived from original shape
    elongation = FloatField(
        null=True,
        help_text=
        'Elongation of the flux surface of interest. Computed internally from the shape parameters (c_n,s_n)'
    )
    triangularity_upper = FloatField(
        null=True,
        help_text=
        'Upper triangularity of the flux surface of interest. Computed internally from the shape parameters (c_n,s_n)'
    )
    triangularity_lower = FloatField(
        null=True,
        help_text=
        'Lower triangularity of the flux surface of interest. Computed internally from the shape parameters (c_n,s_n)'
    )
예제 #6
0
파일: models.py 프로젝트: rayandas/tuesday
class Member(CommonModel):
    id = IntegerField(index=True, unique=True)
    username = TextField(unique=True)
    name = TextField()
    email = TextField(null=True)
    enabled = BooleanField(default=True)
    badges = ArrayField(default=[])
    groups = ArrayField(CharField, default=[])
    bio = TextField(null=True)
    web = TextField(null=True)
    verified = BooleanField(default=False)
예제 #7
0
class Cadence(TargetdbBase):
    delta = ArrayField(field_class=FloatField, null=True)
    delta_max = ArrayField(field_class=FloatField, null=True)
    delta_min = ArrayField(field_class=FloatField, null=True)
    instrument_pk = ArrayField(field_class=IntegerField, null=True)
    label = TextField(null=False)
    nexposures = SmallIntegerField(null=True)
    pk = AutoField()
    skybrightness = ArrayField(field_class=FloatField, null=True)

    class Meta:
        table_name = 'cadence'
예제 #8
0
class Relayer(PwModel):
    owner = pw.CharField(max_length=200)
    name = pw.CharField(unique=True, max_length=200)
    coinbase = pw.CharField(unique=True, max_length=200)
    deposit = pw.IntegerField()
    trade_fee = pw.IntegerField(default=1)
    from_tokens = ArrayField(pw.CharField, default=[])
    to_tokens = ArrayField(pw.CharField, default=[])
    logo = pw.CharField(max_length=200, null=True)
    link = pw.CharField(max_length=255, null=True)
    resigning = pw.BooleanField(default=False)
    lock_time = pw.IntegerField(null=True)
예제 #9
0
class InstALModel(BaseModel):
    institutions = ArrayField(TextField, index=False)
    bridges = ArrayField(TextField, index=False)
    logic_programming = ArrayField(TextField, index=False)
    facts = ArrayField(TextField, index=False)

    @classmethod
    def get_marshelled_dict(cls, data):
        return cls.ModelSchema().load(data)

    @classmethod
    def new_from_form_data(cls, data) -> "InstALModel":
        marshelled = cls.get_marshelled_dict(data)
        di = marshelled.data
        new_model = cls(institutions=di.get("institutions", []),
                        bridges=di.get("bridges", []),
                        logic_programming=di.get("logic_programs", []),
                        facts=di.get("facts", []))
        new_model.save()
        return new_model

    class ModelSchema(schema.Schema):
        institutions = fields.List(fields.String(), required=True)
        bridges = fields.List(fields.String())
        logic_programs = fields.List(fields.String())
        facts = fields.List(fields.String())

        @post_load
        def make_model(self, data):
            pass

    def to_dict(self):
        return model_to_dict(self, recurse=True)

    def to_json(self):
        return json.dumps(self.to_dict())

    def get_inspect(self):
        ial_files = [StringIO(s) for s in self.institutions]
        bridge_files = [StringIO(s) for s in self.bridges]
        logic_programs = [StringIO(s) for s in self.logic_programming]
        inspect = instal.instalinspect.instal_inspect_files(
            ial_files=ial_files,
            bridge_files=bridge_files,
            lp_files=logic_programs,
            domain_files=[],
            query_file=[],
            fact_files=[])
        return inspect
예제 #10
0
class User(ModelTimestampsMixin, BaseModel, UserMixin, PermissionsCheckMixin):
    DEFAULT_GROUPS = ['default']

    id = peewee.PrimaryKeyField()
    name = peewee.CharField(max_length=320)
    email = peewee.CharField(max_length=320, index=True, unique=True)
    password_hash = peewee.CharField(max_length=128, null=True)
    groups = ArrayField(peewee.CharField, default=DEFAULT_GROUPS)

    class Meta:
        db_table = 'users'

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'email': self.email,
            'updated_at': self.updated_at,
            'created_at': self.created_at
        }

    def __init__(self, *args, **kwargs):
        super(User, self).__init__(*args, **kwargs)
        self._allowed_tables = None

    @property
    def permissions(self):
        # TODO: this should be cached.
        return list(
            itertools.chain(*[
                g.permissions
                for g in Group.select().where(Group.name << self.groups)
            ]))

    @property
    def allowed_tables(self):
        # TODO: cache this as weel
        if self._allowed_tables is None:
            self._allowed_tables = set([
                t.lower() for t in itertools.chain(*[
                    g.tables
                    for g in Group.select().where(Group.name << self.groups)
                ])
            ])

        return self._allowed_tables

    @classmethod
    def get_by_email(cls, email):
        return cls.get(cls.email == email)

    def __unicode__(self):
        return '%r, %r' % (self.name, self.email)

    def hash_password(self, password):
        self.password_hash = pwd_context.encrypt(password)

    def verify_password(self, password):
        return self.password_hash and pwd_context.verify(
            password, self.password_hash)
예제 #11
0
class PostModel(Model):
    """Model for posts."""

    class Meta:
        """TODO document this."""

        database = db
        table_name = POSTS_TABLE

    id = UUIDField(unique=True, null=False, column_name="id", primary_key=True)
    user_id = ForeignKeyField(
        UserModel,
        on_delete="CASCADE",
        on_update="CASCADE",
        column_name="user_id",
    )
    image_id = ForeignKeyField(
        ImageModel,
        on_delete="CASCADE",
        on_update="CASCADE",
        column_name="image_id",
        null=True,
    )
    content = CharField(null=True)
    create_time = TimestampField(default=None, resolution=0, utc=False)
    edited = BooleanField(null=False, default=False)
    edit_time = TimestampField(default=None, resolution=0, utc=False)
    visibility = CharField(null=False, default="public")
    likes = ArrayField(null=True, field_class=TextField)
예제 #12
0
class Video(BaseModel):
    id = CharField(max_length=32, unique=True, primary_key=True)
    etag = CharField(max_length=64)

    published = DateTimeField()
    # channel_id = CharField(max_length=32)
    title = CharField(max_length=128)

    thumbnails = JSONField(default={})
    topic_details = JSONField(default={})
    meta = JSONField(default={})

    description = CharField(max_length=6000)
    '''
        search_description=fn.to_tsvector(description))
    '''
    # search_description = TSVectorField()
    tags = ArrayField(CharField)
    category_id = IntegerField(default=0)
    duration = IntervalField()  # timedelta
    caption = BooleanField(default=False)
    license_content = BooleanField(default=False)
    defintion = CharField(max_length=8)
    projection = CharField(max_length=15)
    dimension = CharField(max_length=3)

    localization = JSONField(default={})

    channel = ForeignKeyField(Channel, backref='videos')
class Order(BaseModel):
    volunteer = peewee.ForeignKeyField(Volunteer, backref='volunteers')
    user = peewee.ForeignKeyField(Isolated, backref='isolated')
    address = peewee.CharField(null=False, index=True)
    order = ArrayField(peewee.CharField, index=False)
    status = peewee.CharField(null=False, index=False)
    updated = peewee.DateTimeField(default=datetime.utcnow, index=True)
예제 #14
0
class CAPEC(peewee.Model):
    class Meta:
        database = database
        ordering = ("capec_id", )
        table_name = "capec"

    id = peewee.PrimaryKeyField(null=False, )
    capec_id = peewee.TextField(default="", )
    name = peewee.TextField(default="", )
    summary = peewee.TextField(default="", )
    prerequisites = peewee.TextField(default="", )
    solutions = peewee.TextField(default="", )
    related_weakness = ArrayField(peewee.TextField,
                                  default=[],
                                  verbose_name='related_weakness')

    def __unicode__(self):
        return "capec"

    def __str__(self):
        return self.capec_id

    @property
    def to_json(self):
        return dict(id=self.id,
                    capec_id=self.capec_id,
                    name=self.name,
                    summary=self.summary,
                    prerequisites=self.prerequisites,
                    solutions=self.solutions,
                    related_weakness=self.related_weakness)
예제 #15
0
class CPE_VULNERS(peewee.Model):
    class Meta:
        database = database
        table_name = "cpe_vulners"

    id = peewee.PrimaryKeyField(null=False)
    item = peewee.TextField(default="", verbose_name="CPE ID")
    title = peewee.TextField(default="", verbose_name="CPE Title")
    refs = ArrayField(peewee.TextField,
                      default=[],
                      verbose_name="CPE references array")
    cpe22 = peewee.TextField(default="", verbose_name="CPE 2.2 Metrics")
    cpe23 = peewee.TextField(default="", verbose_name="CPE 2.3 Metrics")

    def __unicode__(self):
        return "CPE"

    def __str__(self):
        return self.item

    @property
    def data(self):
        cpe_data = {}
        cpe_data["id"] = self.id
        cpe_data["item"] = self.item
        cpe_data["title"] = self.title
        cpe_data["references"] = self.refs
        cpe_data["cpe22"] = self.cpe22
        cpe_data["cpe23"] = self.cpe23
        return cpe_data
예제 #16
0
class Image(BaseModel):
    feed_id = CharField(unique=True)
    images = ArrayField(TextField)

    class Meta:
        db_table = 'images'
        order_by = ('feed_id', )
예제 #17
0
class Citation(BaseModel):

    text = ForeignKeyField(Text)
    document = ForeignKeyField(Document)
    tokens = ArrayField(CharField)

    class Meta:
        database = config.get_table_db('citation')
        indexes = ((('document', 'text'), True), )

    @property
    def subfield(self):
        """
        Get the document's subfield, if any.

        Returns: Subfield
        """

        return (Subfield.select().join(Subfield_Document).join(Document).where(
            Document.id == self.document).order_by(
                Subfield_Document.offset.asc()).first())

    @property
    def institution(self):
        """
        Get the document's institution, if any.

        Returns: Institution
        """

        return (Institution.select().join(Institution_Document).join(
            Document).where(Document.id == self.document).first())
예제 #18
0
class Dataset(BaseModel):
    """ORM model of the Dataset table"""
    project = pw.ForeignKeyField(Project, on_delete='CASCADE',
                                 related_name='datasets')
    name = pw.CharField()
    created = pw.DateTimeField(default=datetime.datetime.now)
    meta_features = ArrayField(pw.CharField)

    @staticmethod
    def add(name, project, file_uris=[], meta_features=[]):
        with db.atomic():
            d = Dataset.create(name=name, project=project,
                               meta_features=meta_features)
            files, created = zip(*(
                File.create_or_get(uri=uri) for uri in file_uris)
            )
            for f in files:
                DatasetFile.create(dataset=d, file=f)
        return d

    @property
    def uris(self):
        query = File.select().join(DatasetFile).join(Dataset).where(Dataset.id
                                                                    == self.id)
        return [f.uri for f in query]

    def is_owned_by(self, username):
        return self.project.is_owned_by(username)

    def display_info(self):
        info = self.__dict__()
        info['files'] = [os.path.basename(uri).split('.nc')[0]
                         for uri in self.uris]

        return info
예제 #19
0
class User(BaseModel, UserMixin):
    DEFAULT_PERMISSIONS = ['create_dashboard', 'create_query', 'edit_dashboard', 'edit_query',
                           'view_query', 'view_source', 'execute_query']

    id = peewee.PrimaryKeyField()
    name = peewee.CharField(max_length=320)
    email = peewee.CharField(max_length=320, index=True, unique=True)
    password_hash = peewee.CharField(max_length=128, null=True)
    is_admin = peewee.BooleanField(default=False)
    permissions = ArrayField(peewee.CharField, default=DEFAULT_PERMISSIONS)

    class Meta:
        db_table = 'users'

    def to_dict(self):
        return {
            'id': self.id,
            'name': self.name,
            'email': self.email,
            'is_admin': self.is_admin
        }

    def __unicode__(self):
        return '%r, %r' % (self.name, self.email)

    def hash_password(self, password):
        self.password_hash = pwd_context.encrypt(password)

    def verify_password(self, password):
        return self.password_hash and pwd_context.verify(password, self.password_hash)
예제 #20
0
class Link(BaseModel):
    feed_id = CharField(unique=True)
    links = ArrayField(TextField)

    class Meta:
        db_table = 'links'
        order_by = ('feed_id', )
예제 #21
0
class Event(Model):
    id: int = PrimaryKeyField()
    received: datetime = DateTimeField(default=fn.now)

    received_from: Server = ForeignKeyField(Server,
                                            null=True,
                                            on_update='cascade')
    """
    Server that we got this Event from.
    In general, this has nothing to do with which server produced the event originally.
    """

    server: str = TextField()
    """Name of the server on which the post affected by this event is published."""

    authors: List[str] = ArrayField(TextField)
    """Name of the user who should be the «owner» of the post."""

    parent: str = TextField(null=True)
    """Full identifier of parent post."""

    path: str = TextField(null=True)
    """
    Identification of the post affected by this event.
    This is the same path as in :data:`Post.path`.
    """

    diff: Dict[str, Any] = BinaryJSONField(
        default={}, constraints=[Check("jsonb_typeof(diff) = 'object'")])
    """Changes which should be applied to the post."""

    signatures: Dict[str, str] = BinaryJSONField(
        default={}, constraints=[Check("jsonb_typeof(signatures) = 'object'")])
    """
예제 #22
0
class Quickred(OperationsDBModel):
    bscale = FloatField(null=True)
    bzero = FloatField(null=True)
    data = ArrayField(field_class=IntegerField, null=True)
    dither_pixpos = DecimalField(null=True)
    exposure_pk = IntegerField(index=True, null=True)
    last_quicklook_pk = IntegerField(index=True)
    logsnr_hmag_coef = UnknownField(null=True)  # ARRAY
    pk = IntegerField(
        constraints=[SQL('DEFAULT nextval(\'quickred_pk_seq\'::regclass)')],
        primary_key=True,
        unique=True)
    snr_goals_version = IntegerField(null=True)
    snr_standard = DecimalField(null=True)
    zscale1 = DecimalField(null=True)
    zscale2 = DecimalField(null=True)

    exposure = ForeignKeyField(column_name='exposure_pk',
                               model=platedb.Exposure,
                               backref='apogeeqldb_quickreds',
                               field='pk')
    last_quicklook = ForeignKeyField(column_name='last_quicklook_pk',
                                     model=Quicklook,
                                     backref='quickreds',
                                     field='pk')

    class Meta:
        table_name = 'quickred'
        schema = 'apogeeqldb'
        primary_key = False
예제 #23
0
class Games(BaseModel):
    Types = GamesTypes

    guild_id = BigIntegerField(null=False)
    game_channel = BigIntegerField(null=True, default=None)
    players = ArrayField(BigIntegerField, null=True, index=False)
    type_ = IntegerField(db_column='type')
    turn_count = IntegerField(null=True, default=0)
    ended = BooleanField(default=False)
    winner = BigIntegerField(null=True)
    cards_played = IntegerField(default=0)
    cards_drawn = IntegerField(default=0)
    phrase = TextField(null=True)
    guesses_correct = IntegerField(default=0)
    guesses_incorrect = IntegerField(default=0)
    questions_answered = IntegerField(default=0)
    trivia_category = TextField(null=True)

    class Meta:
        db_table = 'games'
    
    @classmethod
    def with_id(cls, game_id):
        return Games.get(id=game_id)
    
    @classmethod
    def start(cls, event, game_channel, players, game_type):
        return cls.create(
            guild_id = event.guild.id,
            game_channel = game_channel,
            players = [x.id for x in players],
            type_= game_type,
        )
예제 #24
0
class PostgresStorage(BaseModel, PrintStorage):
    """Storage container for Postgresql database."""

    date = DateTimeTZField()
    url = TextField(null=True)
    scheme = TextField(null=True)
    host = TextField(null=True)
    path = TextField(null=True)
    method = CharField(null=True)
    referrer = TextField(null=True)
    remote_addr = TextField(null=True)
    real_ip = CharField(null=True)
    forwarded_proto = CharField(null=True)
    connecting_ip = CharField(null=True)
    ip_country = CharField(null=True)
    visitor = TextField(null=True)
    status = IntegerField(null=True)
    args = PickleField(null=True)
    user_agent = PickleField(null=True)
    access_route = ArrayField(CharField, null=True)
    headers = PickleField(null=True)
    cookies = PickleField(null=True)
    speed = FloatField(null=True)

    class Meta:
        table_name = 'tracking'
예제 #25
0
class GuildEmoji(BaseModel):
    emoji_id = BigIntegerField(primary_key=True)
    guild_id = BigIntegerField()
    name = CharField(index=True)

    require_colons = BooleanField()
    managed = BooleanField()
    roles = ArrayField(BigIntegerField, default=[], null=True)

    deleted = BooleanField(default=False)

    class Meta:
        db_table = 'guild_emojis'

    @classmethod
    def from_disco_guild_emoji(cls, emoji, guild_id=None):
        try:
            ge = cls.get(emoji_id=emoji.id)
            new = False
        except cls.DoesNotExist:
            ge = cls(emoji_id=emoji.id)
            new = True

        ge.guild_id = guild_id or emoji.guild_id
        ge.name = emoji.name
        ge.require_colons = emoji.require_colons
        ge.managed = emoji.managed
        ge.roles = emoji.roles
        ge.save(force_insert=new)
        return ge
예제 #26
0
class Combinations(BaseModel):

    user = ForeignKeyField(Users, backref='combinations')
    name = CharField()
    items = ArrayField()
    info = JSONField(null=True)
    is_private = BooleanField(default=False)
    is_buyable = BooleanField(default=False)
예제 #27
0
 class Object(pw.Model):
     array_field = ArrayField()
     binary_json_field = BinaryJSONField()
     dattime_tz_field = DateTimeTZField()
     hstore_field = HStoreField()
     interval_field = IntervalField()
     json_field = JSONField()
     ts_vector_field = TSVectorField()
예제 #28
0
class Heading(peewee.Model):
    line = peewee.CharField()
    way = peewee.IntegerField()
    stops = ArrayField(field_class=peewee.BooleanField)
    timestamp = peewee.DateTimeField()

    class Meta:
        database = db
예제 #29
0
class ImageVectorBaseModel(Model):
    id = AutoField()
    url = TextField(unique=True)
    vector = ArrayField(DoubleField)

    class Meta:
        database = db
        table_function = get_table_name
예제 #30
0
class Notification(BaseModel):
    id = BlobField(primary_key=True)
    sender_ids = ArrayField(BlobField)
    receiver_id = BlobField(index=True)
    type = IntegerField(index=True)
    time = MyTimestampField(index=True)  # 发布时间
    data = BinaryJSONField(dumps=json_ex_dumps)
    is_read = BooleanField(default=False)

    @classmethod
    def count(cls, user_id):
        return cls.select().where(cls.receiver_id == user_id,
                                  cls.is_read == False).count()

    @classmethod
    def set_read(cls, user_id):
        cur = db.execute_sql(
            '''
        WITH updated_rows as (
          UPDATE notif SET is_read = TRUE WHERE "receiver_id" = %s AND "is_read" = FALSE
          RETURNING is_read
        ) SELECT count(is_read) FROM updated_rows;
        ''', (user_id, ))
        return cur.fetchone()[0]

    @classmethod
    def refresh(cls, user_id, cooldown=config.NOTIF_FETCH_COOLDOWN):
        new = []
        r: UserNotifRecord = UserNotifRecord.get_by_pk(user_id)
        if not r: return
        if cooldown and (time.time() - r.update_time < cooldown):
            return
        for i in r.get_notifications(True):
            if i['type'] == NOTIF_TYPE.BE_COMMENTED:
                new.append({
                    'id': config.LONG_ID_GENERATOR().to_bin(),
                    'sender_ids': (i['comment']['user']['id'], ),
                    'receiver_id': user_id,
                    'type': NOTIF_TYPE.BE_COMMENTED,
                    'time': i['time'],
                    'data': i,
                })
            elif i['type'] == NOTIF_TYPE.BE_REPLIED:
                new.append({
                    'id': config.LONG_ID_GENERATOR().to_bin(),
                    'sender_ids': (i['comment']['user']['id'], ),
                    'receiver_id': user_id,
                    'type': NOTIF_TYPE.BE_REPLIED,
                    'time': i['time'],
                    'data': i,
                })

        if new:
            cls.insert_many(new).execute()
        return len(new)

    class Meta:
        db_table = 'notif'