Example #1
0
class SampleModelGroups(Model):
    name = fields.TextField(max_lenght=400)
    sample_models = fields.ManyToManyField('tests.SampleModel', related_name='groups')
Example #2
0
class Student(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField()
    school: fields.ForeignKeyRelation[School] = fields.ForeignKeyField(
        "models.School", related_name="students", to_field="id"
    )
Example #3
0
class App(BaseModel):
    aid = fields.IntField(unique=True)
    label = fields.CharField(max_length=20)
    pay_key = fields.CharField(max_length=50, description="pay key")
    announcement = fields.TextField(verbose_name='公告')
    service = fields.TextField(verbose_name='服务条款')
Example #4
0
class UUIDM2MRelatedModel(Model):
    id = fields.UUIDField(pk=True)
    value = fields.TextField(default="test")
    models: fields.ManyToManyRelation[UUIDPkModel] = fields.ManyToManyField(
        "models.UUIDPkModel", related_name="peers"
    )
Example #5
0
class DefaultOrderedDesc(Model):
    one = fields.TextField()
    second = fields.IntField()

    class Meta:
        ordering = ["-one"]
Example #6
0
class DiscordChannel(Model):
    discord_id = fields.BigIntField(pk=True)
    first_seen = fields.DatetimeField(auto_now_add=True)

    guild = fields.ForeignKeyField('models.DiscordGuild')
    name = fields.TextField()

    webhook_urls = fields.JSONField(default=[])
    api_key = fields.UUIDField(null=True)

    # Generic settings
    use_webhooks = fields.BooleanField(default=True)
    use_emojis = fields.BooleanField(default=True)
    enabled = fields.BooleanField(default=False)

    allow_global_items = fields.BooleanField(default=True)

    tax_on_user_send = PercentageField(default=5)
    mentions_when_killed = fields.BooleanField(default=True)
    show_duck_lives = fields.BooleanField(default=True)

    # Luck percentages
    kill_on_miss_chance = PercentageField(default=3)
    duck_frighten_chance = PercentageField(default=7)

    # Shop items
    clover_min_experience = fields.SmallIntField(default=1)
    clover_max_experience = fields.SmallIntField(default=10)

    # Experience
    base_duck_exp = fields.SmallIntField(default=10)
    per_life_exp = fields.SmallIntField(default=7)

    # Spawn rates
    ducks_per_day = fields.SmallIntField(default=96)

    night_start_at = fields.IntField(default=0)  # Seconds from midnight UTC
    night_end_at = fields.IntField(default=0)  # Seconds from midnight UTC

    spawn_weight_normal_ducks = fields.SmallIntField(default=100)
    spawn_weight_super_ducks = fields.SmallIntField(default=15)
    spawn_weight_baby_ducks = fields.SmallIntField(default=7)
    spawn_weight_prof_ducks = fields.SmallIntField(default=10)
    spawn_weight_ghost_ducks = fields.SmallIntField(default=1)
    spawn_weight_moad_ducks = fields.SmallIntField(default=5)
    spawn_weight_mechanical_ducks = fields.SmallIntField(default=1)
    spawn_weight_armored_ducks = fields.SmallIntField(default=3)
    spawn_weight_golden_ducks = fields.SmallIntField(default=1)
    spawn_weight_plastic_ducks = fields.SmallIntField(default=6)
    spawn_weight_kamikaze_ducks = fields.SmallIntField(default=6)
    spawn_weight_night_ducks = fields.SmallIntField(default=100)
    spawn_weight_sleeping_ducks = fields.SmallIntField(default=5)

    # Duck settings
    ducks_time_to_live = fields.SmallIntField(default=660)  # Seconds
    super_ducks_min_life = fields.SmallIntField(default=2)
    super_ducks_max_life = fields.SmallIntField(default=7)

    def serialize(self, serialize_fields=None):
        DONT_SERIALIZE = {
            'guild', 'members', 'playerss', 'webhook_urls', 'api_key'
        }

        ser = {}

        if serialize_fields is None:
            serialize_fields = self._meta.fields.copy() - DONT_SERIALIZE

        for serialize_field in serialize_fields:
            if serialize_field == "discord_id":
                ser[serialize_field] = str(getattr(self, serialize_field))

            ser[serialize_field] = getattr(self, serialize_field)

        return ser

    class Meta:
        table = "channels"

    def __str__(self):
        return self.name

    def __repr__(self):
        return f"<Channel name={self.name}>"
Example #7
0
class NoID(Model):
    name = fields.CharField(max_length=255, null=True)
    desc = fields.TextField(null=True)
Example #8
0
class User(Model):
    id = fields.IntField(pk=True)
    login_key = fields.TextField()

    def __str__(self):
        return self.id
class Event(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField()
    timestamp = fields.DatetimeField(auto_now_add=True)
Example #10
0
class TextFields(Model):
    id = fields.IntegerField(primary_key=True)
    text = fields.TextField()
    text_null = fields.TextField(null=True)
Example #11
0
class Quote(models.Model):
    value = fields.TextField()
    created_at = fields.DatetimeField(auto_now_add=True)

    def __str__(self):
        return self.value
Example #12
0
class InheritedModel(AbstractModel, TwoMixin):
    name = fields.TextField()
Example #13
0
class Company(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField()
    uuid = fields.UUIDField(unique=True, default=uuid4)

    employees: fields.ReverseRelation["Employee"]
Example #14
0
class SampleModel(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField(max_length=400)
Example #15
0
class History(Model):
    id = fields.IntField(pk=True)
    time = fields.DatetimeField(auto_now_add=True)
    info = fields.TextField()
    catalog = fields.ForeignKeyField('models.Catalog', related_name='history')
Example #16
0
class Page(SluggableModel):
    name = fields.CharField(max_length=50, unique=True)
    content = fields.TextField()
    image_url = fields.CharField(max_length=250, null=True)
Example #17
0
class User(models.Model):
    _id = fields.TextField()
    osuId = fields.IntField(pk=True)
    username = fields.TextField()
    modesInfo = fields.JSONField()
    isNat = fields.BooleanField()
    isBn = fields.BooleanField()
    modes = fields.JSONField()
    last_updated = fields.DatetimeField(null=True)
    genre_favor = fields.JSONField(null=True)
    lang_favor = fields.JSONField(null=True)
    topdiff_favor = fields.JSONField(null=True)
    size_favor = fields.CharField(20, null=True)
    length_favor = fields.CharField(20, null=True)
    avg_length = fields.IntField(null=True)
    avg_diffs = fields.IntField(null=True)
    nominations: fields.ManyToManyRelation[Nomination]
    resets: fields.ManyToManyRelation[Reset]

    def __repr__(self):
        return f"User(osuId={self.osuId}, username={self.username})"

    @classmethod
    async def get_users(cls) -> List["User"]:
        """Get all users from database, sorted by username.

        Returns:
            List[User]: All users from database.
        """
        users = await cls.all().order_by("username")
        return users

    async def get_nomination_activity(
        self,
        date: datetime = None,
        mode: Union[Mode, str, int] = None,
    ) -> List[Nomination]:
        """Fetch user's nomination activities.

        Args:
            date (datetime, optional): Minimum date to fetch from. Defaults to None.
            mode (Union[Mode, str, int], optional): The game mode to fetch from. Defaults to all game mode.

        Returns:
            List[Nomination]: Nominations from user from minimum date to current for specified game mode.
        """
        filters = {"userId": self.osuId}
        if date:
            filters["timestamp__gte"] = date

        if mode:
            if type(mode) == Mode:
                filters["as_modes__contains"] = Mode.value
            elif type(mode) == str:
                filters["as_modes__contains"] = MODE_CONVERTER[mode]
            else:
                filters["as_modes__contains"] = mode

        logger.info("Fetching events.")
        events = await Nomination.filter(**filters).all().order_by("timestamp")
        return events

    def get_score(
        self,
        system: "CalculatorABC",
        days: int = 90,
        mode: Mode = None,
    ) -> float:
        """Get user's score using specified system.

        Args:
            system (CalculatorABC): Scoring system that will be used to calculate.
            days (int, optional): Number of days from now to fetch nomination from. Defaults to 90.
            mode (Mode, optional): Game mode to be calculated. Defaults to None.

        Returns:
            float: The user's score.
        """
        return system.get_user_score(self, days, mode)

    def total_nominations(self, days: int = 0) -> Awaitable[int]:
        """Fetch total nominations of the user.

        Args:
            days (int, optional): Number of days of nominations to count from. Defaults to 0.

        Returns:
            Awaitable[int]: Total nominations done.
        """
        # As we only redirect the function, we can just use def instead async def.
        if days:
            d = datetime.now() - timedelta(days)
            return Nomination.filter(userId=self.osuId,
                                     timestamp__gte=d).count()
        return Nomination.filter(userId=self.osuId).count()  # type: ignore
Example #18
0
class Report(models.Model):
    name = fields.TextField()
    report = fields.TextField()

    def __str__(self):
        return self.name
Example #19
0
class TextFields(Model):
    id = fields.IntField(pk=True)
    text = fields.TextField()
    text_null = fields.TextField(null=True)
Example #20
0
class URLSummary(models.Model):
    url = fields.TextField()
    summary = fields.TextField()
Example #21
0
class ImplicitPkModel(Model):
    value = fields.TextField()
Example #22
0
class User(Model):
    id = fields.IntField(pk=True)
    username = fields.CharField(max_length=32)
    mail = fields.CharField(max_length=64)
    bio = fields.TextField()
Example #23
0
class CharM2MRelatedModel(Model):
    value = fields.TextField(default="test")
    models = fields.ManyToManyField("models.CharPkModel", related_name="peers")
Example #24
0
class WelcomeMessage(Model):
    guild_id = fields.BigIntField(pk=True)
    message = fields.TextField()

    def __str__(self):
        return f'Welcome Message for <{self.guild_id}>'
Example #25
0
class DefaultOrderedInvalid(Model):
    one = fields.TextField()
    second = fields.IntField()

    class Meta:
        ordering = ["one", "third"]
class User(AbstractUser):
    id = fields.BigIntField(pk=True)
    email = fields.CharField(unique=True, max_length=100)
    first_name = fields.CharField(max_length=100)
    last_name = fields.CharField(max_length=100)
    created_at = fields.DatetimeField(auto_now_add=True)
    updated_at = fields.DatetimeField(auto_now=True)
    profile_url = fields.TextField()
    description = fields.TextField(null=True)
    is_tutor = fields.BooleanField(default=False)
    password = fields.CharField(
        max_length=200,
        description="Will auto hash with raw password when change",
        null=True,
    )
    google_calendar_id = fields.CharField(max_length=255, null=True)

    creds: fields.OneToOneRelation["Credentials"]

    categories: fields.ManyToManyRelation["Category"] = fields.ManyToManyField(
        "models.Category",
        related_name="users",
        through="user_categories",
        backward_key="user_id",
    )

    reviews: fields.ReverseRelation["Review"]

    written_reviews: fields.ReverseRelation["Review"]

    def categories_ids(self) -> List[int]:
        try:
            return [category.id for category in self.categories]
        except NoValuesFetched:
            return []

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

    async def get_creds(self) -> Creds:
        await self.fetch_related("creds")
        creds = self.creds.json_field
        return Creds.from_authorized_user_info(creds)

    async def update_calendar(self):
        if self.is_tutor and self.google_calendar_id is None:
            service = await self.get_calendar_service()

            calendar = {
                "summary": "TutorApp Schedule",
                "timeZone": "America/Chicago"
            }

            created_calendar = service.calendars().insert(
                body=calendar).execute()

            self.google_calendar_id = created_calendar["id"]
            await self.save()

    async def get_calendar_service(self):
        creds = await self.get_creds()
        if creds.expired:
            creds.refresh(Request())
        self.creds.json_field = creds.to_json()
        await self.creds.save()

        return build("calendar", "v3", credentials=creds)

    async def get_events(self, time_min: datetime.datetime,
                         time_max: datetime.datetime):
        """
        Get the events between time_min and time_max of a tutor in a simplified dictionary format

        time_min : The start date of the events to look for
        time_max : The end date of the events to look for (inclusive)
        """

        # Don't move on if there is no calendar_id
        if self.google_calendar_id is None:
            raise HTTPException(404, "No Calendar found")

        # Get the service to call the calendar API
        service = await self.get_calendar_service()

        # See if the calendar exists
        calendar = service.calendars().get(
            calendarId=self.google_calendar_id).execute()

        # If the calendar does not exist for some reason, don't move on
        if "summary" not in calendar:
            raise HTTPException(404, "No Calendar found")

        # Format dates to something Google Calendar API understands
        time_min = time_min.astimezone().isoformat()
        time_max = time_max.astimezone().isoformat()

        # Store the formatted events in a list
        event_list = []
        # Used within loop to see if we can move
        page_token = None

        while True:
            # Get the events of the tutor as a list
            events = (service.events().list(
                calendarId=self.google_calendar_id,
                pageToken=page_token,
                timeMin=time_min,
                timeMax=time_max,
                singleEvents=True,
            ).execute())
            # Loop through each event and get the info we need
            for event in events["items"]:
                event_list.append({
                    "id": event["id"],
                    "start_time": event["start"]["dateTime"],
                    "end_time": event["end"]["dateTime"],
                    "summary": event["summary"],
                })
            # Get the page token
            page_token = events.get("nextPageToken")
            # If there is no page token found, then we have reached the end of the events
            if not page_token:
                break

        return event_list

    class PydanticMeta:
        exclude = [
            "password",
            "username",
            "creds",
            "usercategories",
            "studentsessions",
            "student_sessions",
            "tutor_sessions",
        ]
        extra = "ignore"
        computed = ("categories_ids", )
Example #27
0
class Principal(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField()
    school: fields.OneToOneRelation[School] = fields.OneToOneField(
        "models.School", on_delete=fields.CASCADE, related_name="principal", to_field="id"
    )
Example #28
0
class Meal(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField()
    kind = fields.TextField()
    recipe = fields.ManyToManyField('models.Recipe', related_name='recipes')
Example #29
0
class Team(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField()

    def __str__(self):
        return self.name
Example #30
0
class Team(Model):
    id = fields.IntField(pk=True)
    name = fields.TextField(source_field='title')

    def __str__(self):
        return self.name