Skip to content

Commit

Permalink
Adds typing to site model file
Browse files Browse the repository at this point in the history
Did I do this right?
  • Loading branch information
mouse-reeve committed Aug 27, 2024
1 parent 2bd5a11 commit ebc60ab
Showing 1 changed file with 21 additions and 20 deletions.
41 changes: 21 additions & 20 deletions bookwyrm/models/site.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
""" the particulars for this instance of BookWyrm """
from __future__ import annotations
import datetime
from typing import Optional, Iterable
from typing import Any, Optional, Iterable
from urllib.parse import urljoin
import uuid

Expand Down Expand Up @@ -31,7 +32,7 @@ class Meta:
abstract = True

# pylint: disable=no-self-use
def raise_not_editable(self, viewer):
def raise_not_editable(self, viewer: User) -> None:
"""Check if the user has the right permissions"""
if viewer.has_perm("bookwyrm.edit_instance_settings"):
return
Expand Down Expand Up @@ -109,7 +110,7 @@ class SiteSettings(SiteModel):
field_tracker = FieldTracker(fields=["name", "instance_tagline", "logo"])

@classmethod
def get(cls):
def get(cls) -> SiteSettings:
"""gets the site settings db entry or defaults"""
try:
return cls.objects.get(id=1)
Expand All @@ -119,33 +120,33 @@ def get(cls):
return default_settings

@property
def logo_url(self):
def logo_url(self) -> Any:
"""helper to build the logo url"""
return self.get_url("logo", "images/logo.png")

@property
def logo_small_url(self):
def logo_small_url(self) -> Any:
"""helper to build the logo url"""
return self.get_url("logo_small", "images/logo-small.png")

@property
def favicon_url(self):
def favicon_url(self) -> Any:
"""helper to build the logo url"""
return self.get_url("favicon", "images/favicon.png")

def raise_federation_disabled(self):
def raise_federation_disabled(self) -> None:
"""Don't connect to the outside world"""
if self.disable_federation:
raise PermissionDenied("Federation is disabled")

def get_url(self, field, default_path):
def get_url(self, field: str, default_path: str) -> Any:
"""get a media url or a default static path"""
uploaded = getattr(self, field, None)
if uploaded:
return get_absolute_url(uploaded)
return urljoin(STATIC_FULL_URL, default_path)

def save(self, *args, update_fields: Optional[Iterable[str]] = None, **kwargs):
def save(self, *args, update_fields: Optional[Iterable[str]] = None, **kwargs) -> None:
"""if require_confirm_email is disabled, make sure no users are pending,
if enabled, make sure invite_question_text is not empty"""
if not self.invite_question_text:
Expand All @@ -168,7 +169,7 @@ class Theme(SiteModel):
path = models.CharField(max_length=50, unique=True)
loads = models.BooleanField(null=True, blank=True)

def __str__(self):
def __str__(self) -> str:
# pylint: disable=invalid-str-returned
return self.name

Expand All @@ -185,20 +186,20 @@ class SiteInvite(models.Model):
invitees = models.ManyToManyField(User, related_name="invitees")

# pylint: disable=no-self-use
def raise_not_editable(self, viewer):
def raise_not_editable(self, viewer: User) -> None:
"""Admins only"""
if viewer.has_perm("bookwyrm.create_invites"):
return
raise PermissionDenied()

def valid(self):
def valid(self) -> bool:
"""make sure it hasn't expired or been used"""
return (self.expiry is None or self.expiry > timezone.now()) and (
self.use_limit is None or self.times_used < self.use_limit
)

@property
def link(self):
def link(self) -> str:
"""formats the invite link"""
return f"{BASE_URL}/invite/{self.code}"

Expand All @@ -214,20 +215,20 @@ class InviteRequest(BookWyrmModel):
invite_sent = models.BooleanField(default=False)
ignored = models.BooleanField(default=False)

def raise_not_editable(self, viewer):
def raise_not_editable(self, viewer: User) -> None:
"""Only check perms on edit, not create"""
if not self.id or viewer.has_perm("bookwyrm.create_invites"):
return
raise PermissionDenied()

def save(self, *args, **kwargs):
def save(self, *args, **kwargs) -> None:
"""don't create a request for a registered email"""
if not self.id and User.objects.filter(email=self.email).exists():
raise IntegrityError()
super().save(*args, **kwargs)


def get_password_reset_expiry():
def get_password_reset_expiry() -> datetime.datetime:
"""give people a limited time to use the link"""
now = timezone.now()
return now + datetime.timedelta(days=1)
Expand All @@ -240,19 +241,19 @@ class PasswordReset(models.Model):
expiry = models.DateTimeField(default=get_password_reset_expiry)
user = models.OneToOneField(User, on_delete=models.CASCADE)

def valid(self):
def valid(self) -> bool:
"""make sure it hasn't expired or been used"""
return self.expiry > timezone.now()

@property
def link(self):
def link(self) -> str:
"""formats the invite link"""
return f"{BASE_URL}/password-reset/{self.code}"


# pylint: disable=unused-argument
@receiver(models.signals.post_save, sender=SiteSettings)
def preview_image(instance, *args, **kwargs):
def preview_image(instance:SiteSettings, *args, **kwargs) -> None:
"""Update image preview for the default site image"""
if not ENABLE_PREVIEW_IMAGES:
return
Expand All @@ -263,7 +264,7 @@ def preview_image(instance, *args, **kwargs):


@app.task(queue=MISC)
def check_for_updates_task():
def check_for_updates_task() -> None:
"""See if git remote knows about a new version"""
site = SiteSettings.objects.get()
release = get_data(RELEASE_API, timeout=3, is_activitypub=False)
Expand Down

0 comments on commit ebc60ab

Please sign in to comment.