fields.py 1.52 KB
Newer Older
Agate's avatar
Agate committed
1
import django_filters
2
from django import forms
Agate's avatar
Agate committed
3 4
from django.db import models

Agate's avatar
Agate committed
5
from . import search
Agate's avatar
Agate committed
6

Agate's avatar
Agate committed
7
PRIVACY_LEVEL_CHOICES = [
Agate's avatar
Agate committed
8 9 10 11
    ("me", "Only me"),
    ("followers", "Me and my followers"),
    ("instance", "Everyone on my instance, and my followers"),
    ("everyone", "Everyone, including people on other instances"),
Agate's avatar
Agate committed
12 13 14 15 16
]


def get_privacy_field():
    return models.CharField(
Agate's avatar
Agate committed
17 18
        max_length=30, choices=PRIVACY_LEVEL_CHOICES, default="instance"
    )
19 20


21
def privacy_level_query(user, lookup_field="privacy_level", user_field="user"):
22
    if user.is_anonymous:
Agate's avatar
Agate committed
23
        return models.Q(**{lookup_field: "everyone"})
24

Agate's avatar
Agate committed
25
    return models.Q(
26 27
        **{"{}__in".format(lookup_field): ["instance", "everyone"]}
    ) | models.Q(**{lookup_field: "me", user_field: user})
Agate's avatar
Agate committed
28 29 30 31


class SearchFilter(django_filters.CharFilter):
    def __init__(self, *args, **kwargs):
Agate's avatar
Agate committed
32
        self.search_fields = kwargs.pop("search_fields")
Agate's avatar
Agate committed
33 34 35 36 37
        super().__init__(*args, **kwargs)

    def filter(self, qs, value):
        if not value:
            return qs
Agate's avatar
Agate committed
38
        query = search.get_query(value, self.search_fields)
Agate's avatar
Agate committed
39
        return qs.filter(query)
Agate's avatar
Agate committed
40 41 42 43 44 45 46 47 48 49


class SmartSearchFilter(django_filters.CharFilter):
    def __init__(self, *args, **kwargs):
        self.config = kwargs.pop("config")
        super().__init__(*args, **kwargs)

    def filter(self, qs, value):
        if not value:
            return qs
50 51 52 53
        try:
            cleaned = self.config.clean(value)
        except forms.ValidationError:
            return qs.none()
Agate's avatar
Agate committed
54
        return search.apply(qs, cleaned)