From 3e277aad4f0b2158f9b744336c996a7fabbcea03 Mon Sep 17 00:00:00 2001
From: Eliot Berriot <contact@eliotberriot.com>
Date: Sun, 18 Mar 2018 21:30:53 +0100
Subject: [PATCH] Added helper to filter queryset by privacy level

---
 api/funkwhale_api/common/fields.py | 13 +++++++++++++
 api/tests/common/test_fields.py    | 17 +++++++++++++++++
 2 files changed, 30 insertions(+)
 create mode 100644 api/tests/common/test_fields.py

diff --git a/api/funkwhale_api/common/fields.py b/api/funkwhale_api/common/fields.py
index ab8f6e77..ef9f840d 100644
--- a/api/funkwhale_api/common/fields.py
+++ b/api/funkwhale_api/common/fields.py
@@ -12,3 +12,16 @@ PRIVACY_LEVEL_CHOICES = [
 def get_privacy_field():
     return models.CharField(
         max_length=30, choices=PRIVACY_LEVEL_CHOICES, default='instance')
+
+
+def privacy_level_query(user, lookup_field='privacy_level'):
+    if user.is_anonymous:
+        return models.Q(**{
+            lookup_field: 'everyone',
+        })
+
+    return models.Q(**{
+        '{}__in'.format(lookup_field): [
+            'me', 'followers', 'instance', 'everyone'
+        ]
+    })
diff --git a/api/tests/common/test_fields.py b/api/tests/common/test_fields.py
new file mode 100644
index 00000000..7c63431a
--- /dev/null
+++ b/api/tests/common/test_fields.py
@@ -0,0 +1,17 @@
+import pytest
+
+from django.contrib.auth.models import AnonymousUser
+from django.db.models import Q
+
+from funkwhale_api.common import fields
+from funkwhale_api.users.factories import UserFactory
+
+
+@pytest.mark.parametrize('user,expected', [
+    (AnonymousUser(), Q(privacy_level='everyone')),
+    (UserFactory.build(pk=1),
+     Q(privacy_level__in=['me', 'followers', 'instance', 'everyone'])),
+])
+def test_privacy_level_query(user,expected):
+    query = fields.privacy_level_query(user)
+    assert query == expected
-- 
GitLab