Aller au contenu

Views

SithFile

Bases: Model

clean()

Cleans up the file.

Source code in core/models.py
def clean(self):
    """Cleans up the file."""
    super().clean()
    if "/" in self.name:
        raise ValidationError(_("Character '/' not authorized in name"))
    if self == self.parent:
        raise ValidationError(_("Loop in folder tree"), code="loop")
    if self == self.parent or (
        self.parent is not None and self in self.get_parent_list()
    ):
        raise ValidationError(_("Loop in folder tree"), code="loop")
    if self.parent and self.parent.is_file:
        raise ValidationError(
            _("You can not make a file be a children of a non folder file")
        )
    if (
        self.parent is None
        and SithFile.objects.exclude(id=self.id)
        .filter(parent=None, name=self.name)
        .exists()
    ) or (
        self.parent
        and self.parent.children.exclude(id=self.id).filter(name=self.name).exists()
    ):
        raise ValidationError(_("Duplicate file"), code="duplicate")
    if self.is_folder:
        if self.file:
            try:
                import imghdr

                if imghdr.what(None, self.file.read()) not in [
                    "gif",
                    "png",
                    "jpeg",
                ]:
                    self.file.delete()
                    self.file = None
            except:  # noqa E722 I don't know the exception that can be raised
                self.file = None
        self.mime_type = "inode/directory"
    if self.is_file and (self.file is None or self.file == ""):
        raise ValidationError(_("You must provide a file"))

apply_rights_recursively(*, only_folders=False)

Apply the rights of this file to all children recursively.

Parameters:

Name Type Description Default
only_folders bool

If True, only apply the rights to SithFiles that are folders.

False
Source code in core/models.py
def apply_rights_recursively(self, *, only_folders: bool = False) -> None:
    """Apply the rights of this file to all children recursively.

    Args:
        only_folders: If True, only apply the rights to SithFiles that are folders.
    """
    file_ids = []
    explored_ids = [self.id]
    while len(explored_ids) > 0:  # find all children recursively
        file_ids.extend(explored_ids)
        next_level = SithFile.objects.filter(parent_id__in=explored_ids)
        if only_folders:
            next_level = next_level.filter(is_folder=True)
        explored_ids = list(next_level.values_list("id", flat=True))
    for through in (SithFile.view_groups.through, SithFile.edit_groups.through):
        # force evaluation. Without this, the iterator yields nothing
        groups = list(
            through.objects.filter(sithfile_id=self.id).values_list(
                "group_id", flat=True
            )
        )
        # delete previous rights
        through.objects.filter(sithfile_id__in=file_ids).delete()
        through.objects.bulk_create(  # create new rights
            [through(sithfile_id=f, group_id=g) for f in file_ids for g in groups]
        )

copy_rights()

Copy, if possible, the rights of the parent folder.

Source code in core/models.py
def copy_rights(self):
    """Copy, if possible, the rights of the parent folder."""
    if self.parent is not None:
        self.edit_groups.set(self.parent.edit_groups.all())
        self.view_groups.set(self.parent.view_groups.all())

move_to(parent)

Move a file to a new parent. parent must be a SithFile with the is_folder=True property. Otherwise, this function doesn't change anything. This is done only at the DB level, so that it's very fast for the user. Indeed, this function doesn't modify SithFiles recursively, so it stays efficient even with top-level folders.

Source code in core/models.py
def move_to(self, parent):
    """Move a file to a new parent.
    `parent` must be a SithFile with the `is_folder=True` property. Otherwise, this function doesn't change
    anything.
    This is done only at the DB level, so that it's very fast for the user. Indeed, this function doesn't modify
    SithFiles recursively, so it stays efficient even with top-level folders.
    """
    if not parent.is_folder:
        return
    self.parent = parent
    self.clean()
    self.save()

User

Bases: AbstractBaseUser

Defines the base user class, useable in every app.

This is almost the same as the auth module AbstractUser since it inherits from it, but some fields are required, and the username is generated automatically with the name of the user (see generate_username()).

Added field: nick_name, date_of_birth Required fields: email, first_name, last_name, date_of_birth

cached_groups: list[Group] property

Get the list of groups this user is in.

The result is cached for the default duration (should be 5 minutes)

Returns: A list of all the groups this user is in.

is_in_group(*, pk=None, name=None)

Check if this user is in the given group. Either a group id or a group name must be provided. If both are passed, only the id will be considered.

The group will be fetched using the given parameter. If no group is found, return False. If a group is found, check if this user is in the latter.

Returns:

Type Description
bool

True if the user is the group, else False

Source code in core/models.py
def is_in_group(self, *, pk: int | None = None, name: str | None = None) -> bool:
    """Check if this user is in the given group.
    Either a group id or a group name must be provided.
    If both are passed, only the id will be considered.

    The group will be fetched using the given parameter.
    If no group is found, return False.
    If a group is found, check if this user is in the latter.

    Returns:
         True if the user is the group, else False
    """
    if pk is not None:
        group: Optional[Group] = get_group(pk=pk)
    elif name is not None:
        group: Optional[Group] = get_group(name=name)
    else:
        raise ValueError("You must either provide the id or the name of the group")
    if group is None:
        return False
    if group.id == settings.SITH_GROUP_PUBLIC_ID:
        return True
    if group.id == settings.SITH_GROUP_SUBSCRIBERS_ID:
        return self.is_subscribed
    if group.id == settings.SITH_GROUP_OLD_SUBSCRIBERS_ID:
        return self.was_subscribed
    if group.id == settings.SITH_GROUP_ROOT_ID:
        return self.is_root
    if group.is_meta:
        # check if this group is associated with a club
        group.__class__ = MetaGroup
        club = group.associated_club
        if club is None:
            return False
        membership = club.get_membership_for(self)
        if membership is None:
            return False
        if group.name.endswith(settings.SITH_MEMBER_SUFFIX):
            return True
        return membership.role > settings.SITH_MAXIMUM_FREE_ROLE
    return group in self.cached_groups

age()

Return the age this user has the day the method is called. If the user has not filled his age, return 0.

Source code in core/models.py
@cached_property
def age(self) -> int:
    """Return the age this user has the day the method is called.
    If the user has not filled his age, return 0.
    """
    if self.date_of_birth is None:
        return 0
    today = timezone.now()
    age = today.year - self.date_of_birth.year
    # remove a year if this year's birthday is yet to come
    age -= (today.month, today.day) < (
        self.date_of_birth.month,
        self.date_of_birth.day,
    )
    return age

get_full_name()

Returns the first_name plus the last_name, with a space in between.

Source code in core/models.py
def get_full_name(self):
    """Returns the first_name plus the last_name, with a space in between."""
    full_name = "%s %s" % (self.first_name, self.last_name)
    return full_name.strip()

get_short_name()

Returns the short name for the user.

Source code in core/models.py
def get_short_name(self):
    """Returns the short name for the user."""
    if self.nick_name:
        return self.nick_name
    return self.first_name + " " + self.last_name

get_display_name()

Returns the display name of the user.

A nickname if possible, otherwise, the full name.

Source code in core/models.py
def get_display_name(self) -> str:
    """Returns the display name of the user.

    A nickname if possible, otherwise, the full name.
    """
    if self.nick_name:
        return "%s (%s)" % (self.get_full_name(), self.nick_name)
    return self.get_full_name()

get_age()

Returns the age.

Source code in core/models.py
def get_age(self):
    """Returns the age."""
    today = timezone.now()
    born = self.date_of_birth
    return (
        today.year - born.year - ((today.month, today.day) < (born.month, born.day))
    )

get_family(godfathers_depth=4, godchildren_depth=4)

Get the family of the user, with the given depth.

Parameters:

Name Type Description Default
godfathers_depth NonNegativeInt

The number of generations of godfathers to fetch

4
godchildren_depth NonNegativeInt

The number of generations of godchildren to fetch

4

Returns:

Type Description
set[through]

A list of family relationships in this user's family

Source code in core/models.py
def get_family(
    self,
    godfathers_depth: NonNegativeInt = 4,
    godchildren_depth: NonNegativeInt = 4,
) -> set[User.godfathers.through]:
    """Get the family of the user, with the given depth.

    Args:
        godfathers_depth: The number of generations of godfathers to fetch
        godchildren_depth: The number of generations of godchildren to fetch

    Returns:
        A list of family relationships in this user's family
    """
    res = []
    for depth, key, reverse_key in [
        (godfathers_depth, "from_user_id", "to_user_id"),
        (godchildren_depth, "to_user_id", "from_user_id"),
    ]:
        if depth == 0:
            continue
        links = list(User.godfathers.through.objects.filter(**{key: self.id}))
        res.extend(links)
        for _ in range(1, depth):  # noqa: F402 we don't care about gettext here
            ids = [getattr(c, reverse_key) for c in links]
            links = list(
                User.godfathers.through.objects.filter(
                    **{f"{key}__in": ids}
                ).exclude(id__in=[r.id for r in res])
            )
            if not links:
                break
            res.extend(links)
    return set(res)

email_user(subject, message, from_email=None, **kwargs)

Sends an email to this User.

Source code in core/models.py
def email_user(self, subject, message, from_email=None, **kwargs):
    """Sends an email to this User."""
    if from_email is None:
        from_email = settings.DEFAULT_FROM_EMAIL
    send_mail(subject, message, from_email, [self.email], **kwargs)

generate_username()

Generates a unique username based on the first and last names.

For example: Guy Carlier gives gcarlier, and gcarlier1 if the first one exists.

Returns:

Type Description
str

The generated username.

Source code in core/models.py
def generate_username(self) -> str:
    """Generates a unique username based on the first and last names.

    For example: Guy Carlier gives gcarlier, and gcarlier1 if the first one exists.

    Returns:
        The generated username.
    """

    def remove_accents(data):
        return "".join(
            x
            for x in unicodedata.normalize("NFKD", data)
            if unicodedata.category(x)[0] == "L"
        ).lower()

    user_name = (
        remove_accents(self.first_name[0] + self.last_name)
        .encode("ascii", "ignore")
        .decode("utf-8")
    )
    un_set = [u.username for u in User.objects.all()]
    if user_name in un_set:
        i = 1
        while user_name + str(i) in un_set:
            i += 1
        user_name += str(i)
    self.username = user_name
    return user_name

is_owner(obj)

Determine if the object is owned by the user.

Source code in core/models.py
def is_owner(self, obj):
    """Determine if the object is owned by the user."""
    if hasattr(obj, "is_owned_by") and obj.is_owned_by(self):
        return True
    if hasattr(obj, "owner_group") and self.is_in_group(pk=obj.owner_group.id):
        return True
    return self.is_root

can_edit(obj)

Determine if the object can be edited by the user.

Source code in core/models.py
def can_edit(self, obj):
    """Determine if the object can be edited by the user."""
    if hasattr(obj, "can_be_edited_by") and obj.can_be_edited_by(self):
        return True
    if hasattr(obj, "edit_groups"):
        for pk in obj.edit_groups.values_list("pk", flat=True):
            if self.is_in_group(pk=pk):
                return True
    if isinstance(obj, User) and obj == self:
        return True
    return self.is_owner(obj)

can_view(obj)

Determine if the object can be viewed by the user.

Source code in core/models.py
def can_view(self, obj):
    """Determine if the object can be viewed by the user."""
    if hasattr(obj, "can_be_viewed_by") and obj.can_be_viewed_by(self):
        return True
    if hasattr(obj, "view_groups"):
        for pk in obj.view_groups.values_list("pk", flat=True):
            if self.is_in_group(pk=pk):
                return True
    return self.can_edit(obj)

clubs_with_rights()

The list of clubs where the user has rights

Source code in core/models.py
@cached_property
def clubs_with_rights(self) -> list[Club]:
    """The list of clubs where the user has rights"""
    memberships = self.memberships.ongoing().board().select_related("club")
    return [m.club for m in memberships]

CanEditMixin

Bases: GenericContentPermissionMixinBuilder

Ensure the user has permission to edit this view's object.

Raises:

Type Description
PermissionDenied

if the user cannot edit this view's object.

CanViewMixin

Bases: GenericContentPermissionMixinBuilder

Ensure the user has permission to view this view's object.

Raises:

Type Description
PermissionDenied

if the user cannot edit this view's object.

FileView

Bases: CanViewMixin, DetailView, FormMixin

Handle the upload of new files into a folder.

handle_clipboard(request, obj) staticmethod

Handle the clipboard in the view.

This method can fail, since it does not catch the exceptions coming from below, allowing proper handling in the calling view. Use this method like this:

FileView.handle_clipboard(request, self.object)

request is usually the self.request obj in your view obj is the SithFile object you want to put in the clipboard, or where you want to paste the clipboard

Source code in core/views/files.py
@staticmethod
def handle_clipboard(request, obj):
    """Handle the clipboard in the view.

    This method can fail, since it does not catch the exceptions coming from
    below, allowing proper handling in the calling view.
    Use this method like this:

        FileView.handle_clipboard(request, self.object)

    `request` is usually the self.request obj in your view
    `obj` is the SithFile object you want to put in the clipboard, or
             where you want to paste the clipboard
    """
    if "delete" in request.POST:
        for f_id in request.POST.getlist("file_list"):
            file = SithFile.objects.filter(id=f_id).first()
            if file:
                file.delete()
    if "clear" in request.POST:
        request.session["clipboard"] = []
    if "cut" in request.POST:
        for f_id_str in request.POST.getlist("file_list"):
            f_id = int(f_id_str)
            if (
                f_id in [c.id for c in obj.children.all()]
                and f_id not in request.session["clipboard"]
            ):
                request.session["clipboard"].append(f_id)
    if "paste" in request.POST:
        for f_id in request.session["clipboard"]:
            file = SithFile.objects.filter(id=f_id).first()
            if file:
                file.move_to(obj)
        request.session["clipboard"] = []
    request.session.modified = True

AlbumEditForm

Bases: ModelForm

PictureEditForm

Bases: ModelForm

PictureModerationRequestForm(*args, user, picture, **kwargs)

Bases: ModelForm

Form to create a PictureModerationRequest.

The form only manages the reason field, because the author and the picture are set in the view.

Source code in sas/forms.py
def __init__(self, *args, user: User, picture: Picture, **kwargs):
    super().__init__(*args, **kwargs)
    self.user = user
    self.picture = picture

SASForm

Bases: Form

Album

Bases: SasFile

NAME_MAX_LENGTH: int = 50 class-attribute

Maximum length of an album's name.

SithFile have a maximum length of 256 characters. However, this limit is too high for albums. Names longer than 50 characters are harder to read and harder to display on the SAS page.

It is to be noted, though, that this does not add or modify any db behaviour. It's just a constant to be used in views and forms.

Picture

Bases: SasFile

SASMainView

Bases: FormView

PictureView

Bases: CanViewMixin, DetailView

AlbumUploadView

Bases: CanViewMixin, DetailView, FormMixin

AlbumView

Bases: CanViewMixin, DetailView, FormMixin

ModerationView

Bases: TemplateView

PictureEditView

Bases: CanEditMixin, UpdateView

PictureAskRemovalView

Bases: CanViewMixin, DetailView, FormView

View to allow users to ask pictures to be removed.

get_form_kwargs()

Add the user and picture to the form kwargs.

Those are required to create the PictureModerationRequest, and aren't part of the form itself (picture is a path parameter, and user is the request user).

Source code in sas/views.py
def get_form_kwargs(self) -> dict[str, Any]:
    """Add the user and picture to the form kwargs.

    Those are required to create the PictureModerationRequest,
    and aren't part of the form itself
    (picture is a path parameter, and user is the request user).
    """
    return super().get_form_kwargs() | {
        "user": self.request.user,
        "picture": self.object,
    }

get_success_url()

Return the URL to the album containing the picture.

Source code in sas/views.py
def get_success_url(self) -> str:
    """Return the URL to the album containing the picture."""
    album = Album.objects.filter(pk=self.object.parent_id).first()
    if not album:
        return reverse("sas:main")
    return album.get_absolute_url()

AlbumEditView

Bases: CanEditMixin, UpdateView

send_file(request, file_id, file_class=SithFile, file_attr='file')

Send a protected file, if the user can see it.

In prod, the server won't handle the download itself, but set the appropriate headers in the response to make the reverse-proxy deal with it. In debug mode, the server will directly send the file.

Source code in core/views/files.py
def send_file(
    request: HttpRequest,
    file_id: int,
    file_class: type[SithFile] = SithFile,
    file_attr: str = "file",
) -> HttpResponse:
    """Send a protected file, if the user can see it.

    In prod, the server won't handle the download itself,
    but set the appropriate headers in the response to make the reverse-proxy
    deal with it.
    In debug mode, the server will directly send the file.
    """
    f = get_object_or_404(file_class, id=file_id)
    if not can_view(f, request.user) and not is_logged_in_counter(request):
        raise PermissionDenied
    name = getattr(f, file_attr).name

    response = HttpResponse(
        headers={"Content-Disposition": f'inline; filename="{quote(name)}"'}
    )
    if not settings.DEBUG:
        # When receiving a response with the Accel-Redirect header,
        # the reverse proxy will automatically handle the file sending.
        # This is really hard to test (thus isn't tested)
        # so please do not mess with this.
        response["Content-Type"] = ""  # automatically set by nginx
        response["X-Accel-Redirect"] = quote(urljoin(settings.MEDIA_URL, name))
        return response

    filepath = settings.MEDIA_ROOT / name
    # check if file exists on disk
    if not filepath.exists():
        raise Http404
    with open(filepath, "rb") as filename:
        response.content = FileWrapper(filename)
        response["Content-Type"] = mimetypes.guess_type(filepath)[0]
        response["Last-Modified"] = http_date(f.date.timestamp())
        response["Content-Length"] = filepath.stat().st_size
        return response

send_album(request, album_id)

Source code in sas/views.py
def send_album(request, album_id):
    return send_file(request, album_id, Album)

send_pict(request, picture_id)

Source code in sas/views.py
def send_pict(request, picture_id):
    return send_file(request, picture_id, Picture)

send_compressed(request, picture_id)

Source code in sas/views.py
def send_compressed(request, picture_id):
    return send_file(request, picture_id, Picture, "compressed")

send_thumb(request, picture_id)

Source code in sas/views.py
def send_thumb(request, picture_id):
    return send_file(request, picture_id, Picture, "thumbnail")