id
int64 0
458k
| file_name
stringlengths 4
119
| file_path
stringlengths 14
227
| content
stringlengths 24
9.96M
| size
int64 24
9.96M
| language
stringclasses 1
value | extension
stringclasses 14
values | total_lines
int64 1
219k
| avg_line_length
float64 2.52
4.63M
| max_line_length
int64 5
9.91M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 7
101
| repo_stars
int64 100
139k
| repo_forks
int64 0
26.4k
| repo_open_issues
int64 0
2.27k
| repo_license
stringclasses 12
values | repo_extraction_date
stringclasses 433
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18,400
|
filter_queryset.py
|
rafalp_Misago/misago/search/filter_queryset.py
|
EQUAL = 0
CONTAINS = 1
STARTS_WITH = 2
ENDS_WITH = 3
def filter_queryset(queryset, attr, search, *, case_sensitive=False):
mode = get_mode(search)
search = search.strip("*")
if not search:
return queryset
queryset_filter = get_queryset_filter(
attr, mode, search, case_sensitive=case_sensitive
)
return queryset.filter(**queryset_filter)
def get_mode(search):
if search.startswith("*") and search.endswith("*"):
return CONTAINS
if search.endswith("*"):
return STARTS_WITH
if search.startswith("*"):
return ENDS_WITH
return EQUAL
def get_queryset_filter(attr, mode, search, *, case_sensitive=False):
if mode is STARTS_WITH:
if case_sensitive:
return {"%s__startswith" % attr: search}
return {"%s__istartswith" % attr: search}
if mode is ENDS_WITH:
if case_sensitive:
return {"%s__endswith" % attr: search}
return {"%s__iendswith" % attr: search}
if mode is CONTAINS:
if case_sensitive:
return {"%s__contains" % attr: search}
return {"%s__icontains" % attr: search}
if case_sensitive:
return {attr: search}
return {"%s__iexact" % attr: search}
| 1,246
|
Python
|
.py
| 37
| 27.162162
| 69
| 0.626566
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,401
|
apps.py
|
rafalp_Misago/misago/search/apps.py
|
from django.apps import AppConfig
class MisagoSearchConfig(AppConfig):
name = "misago.search"
label = "misago_search"
verbose_name = "Misago Search"
| 163
|
Python
|
.py
| 5
| 28.8
| 36
| 0.75
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,402
|
api.py
|
rafalp_Misago/misago/search/api.py
|
from time import time
from django.core.exceptions import PermissionDenied
from django.urls import reverse
from django.utils.translation import pgettext
from rest_framework.decorators import api_view
from rest_framework.response import Response
from ..core.shortcuts import get_int_or_404
from .searchproviders import searchproviders
@api_view()
def search(request, search_provider=None):
allowed_providers = searchproviders.get_allowed_providers(request)
if not request.user_acl["can_search"] or not allowed_providers:
raise PermissionDenied(
pgettext("search api", "You don't have permission to search site.")
)
search_query = get_search_query(request)
response = []
for provider in allowed_providers:
provider_data = {
"id": provider.url,
"name": str(provider.name),
"icon": provider.icon,
"url": reverse("misago:search", kwargs={"search_provider": provider.url}),
"api": reverse(
"misago:api:search", kwargs={"search_provider": provider.url}
),
"results": None,
"time": None,
}
if not search_provider or search_provider == provider.url:
start_time = time()
if search_provider == provider.url:
page = get_int_or_404(request.query_params.get("page", 1))
else:
page = 1
provider_data["results"] = provider.search(search_query, page)
provider_data["time"] = float("%.2f" % (time() - start_time))
response.append(provider_data)
return Response(response)
def get_search_query(request):
return request.query_params.get("q", "").strip()
| 1,735
|
Python
|
.py
| 41
| 33.926829
| 86
| 0.644088
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,403
|
context_processors.py
|
rafalp_Misago/misago/search/context_processors.py
|
from django.urls import reverse
from .searchproviders import searchproviders
def search_providers(request):
allowed_providers = []
try:
if request.user_acl["can_search"]:
allowed_providers = searchproviders.get_allowed_providers(request)
except AttributeError:
# is user has no acl_cache attribute, cease entire middleware
# this is edge case that occurs when debug toolbar intercepts
# the redirect response from logout page and runs context providers
# with non-misago's anonymous user model that has no acl support
return {}
request.frontend_context["SEARCH_URL"] = reverse("misago:search")
request.frontend_context["SEARCH_API"] = reverse("misago:api:search")
request.frontend_context["SEARCH_PROVIDERS"] = []
for provider in allowed_providers:
request.frontend_context["SEARCH_PROVIDERS"].append(
{
"id": provider.url,
"name": str(provider.name),
"icon": provider.icon,
"url": reverse(
"misago:search", kwargs={"search_provider": provider.url}
),
"api": reverse(
"misago:api:search", kwargs={"search_provider": provider.url}
),
"results": None,
"time": None,
}
)
return {}
| 1,401
|
Python
|
.py
| 33
| 31.666667
| 81
| 0.601763
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,404
|
searchprovider.py
|
rafalp_Misago/misago/search/searchprovider.py
|
class SearchProvider:
def __init__(self, request):
self.request = request
def allow_search(self):
pass
def search(self, query, page=1):
raise NotImplementedError(
"%s has to define search(query, page=1) method" % self.__class__.__name__
)
| 297
|
Python
|
.py
| 9
| 25.555556
| 85
| 0.597902
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,405
|
searchproviders.py
|
rafalp_Misago/misago/search/searchproviders.py
|
from django.core.exceptions import PermissionDenied
from django.utils.module_loading import import_string
from ..conf import settings
class SearchProviders:
def __init__(self, search_providers):
self._initialized = False
self._providers = []
self.providers = search_providers
def initialize_providers(self):
if self._initialized:
return
self._initialized = True
self._providers = list(map(import_string, self.providers))
def get_providers(self, request):
if not self._initialized:
self.initialize_providers()
providers = []
for provider in self._providers:
providers.append(provider(request))
return providers
def get_allowed_providers(self, request):
allowed_providers = []
for provider in self.get_providers(request):
try:
provider.allow_search()
allowed_providers.append(provider)
except PermissionDenied:
pass
return allowed_providers
searchproviders = SearchProviders(settings.MISAGO_SEARCH_EXTENSIONS)
| 1,147
|
Python
|
.py
| 30
| 29.266667
| 68
| 0.658228
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,406
|
permissions.py
|
rafalp_Misago/misago/search/permissions.py
|
from django import forms
from django.utils.translation import pgettext_lazy
from ..acl import algebra
from ..acl.models import Role
from ..admin.forms import YesNoSwitch
class PermissionsForm(forms.Form):
legend = pgettext_lazy("search permission", "Search")
can_search = YesNoSwitch(
label=pgettext_lazy("search permission", "Can search site"), initial=1
)
def change_permissions_form(role):
if isinstance(role, Role):
return PermissionsForm
def build_acl(acl, roles, key_name):
new_acl = {"can_search": 0}
new_acl.update(acl)
return algebra.sum_acls(
new_acl, roles=roles, key=key_name, can_search=algebra.greater
)
| 683
|
Python
|
.py
| 19
| 31.526316
| 78
| 0.728244
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,407
|
views.py
|
rafalp_Misago/misago/search/views.py
|
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.shortcuts import redirect, render
from django.utils.translation import pgettext
from .searchproviders import searchproviders
def landing(request):
allowed_providers = searchproviders.get_allowed_providers(request)
if not request.user_acl["can_search"] or not allowed_providers:
raise PermissionDenied(
pgettext("search view", "You don't have permission to search site.")
)
default_provider = allowed_providers[0]
return redirect("misago:search", search_provider=default_provider.url)
def search(request, search_provider):
all_providers = searchproviders.get_providers(request)
if not request.user_acl["can_search"] or not all_providers:
raise PermissionDenied(
pgettext("search view", "You don't have permission to search site.")
)
for provider in all_providers:
if provider.url == search_provider:
provider.allow_search()
break
else:
raise Http404()
if "q" in request.GET:
search_query = request.GET.get("q").strip()
request.frontend_context["SEARCH_QUERY"] = search_query
else:
search_query = ""
return render(request, "misago/search.html", {"search_query": search_query})
| 1,344
|
Python
|
.py
| 31
| 36.774194
| 80
| 0.707822
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,408
|
api.py
|
rafalp_Misago/misago/search/urls/api.py
|
from django.urls import path
from .. import api
urlpatterns = [
path("search/", api.search, name="search"),
path("search/<slug:search_provider>/", api.search, name="search"),
]
| 187
|
Python
|
.py
| 6
| 28.5
| 70
| 0.692737
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,409
|
__init__.py
|
rafalp_Misago/misago/search/urls/__init__.py
|
from django.urls import path
from ..views import landing, search
urlpatterns = [
path("search/", landing, name="search"),
path("search/<slug:search_provider>/", search, name="search"),
]
| 197
|
Python
|
.py
| 6
| 30.166667
| 66
| 0.708995
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,410
|
test_searchproviders.py
|
rafalp_Misago/misago/search/tests/test_searchproviders.py
|
from django.core.exceptions import PermissionDenied
from django.test import TestCase
from ...conf import settings
from ..searchprovider import SearchProvider
from ..searchproviders import SearchProviders
class MockProvider(SearchProvider):
pass
class DisallowedProvider(SearchProvider):
def allow_search(self):
raise PermissionDenied()
class SearchProvidersTests(TestCase):
def test_initialize_providers(self):
"""initialize_providers initializes providers"""
searchproviders = SearchProviders(settings.MISAGO_SEARCH_EXTENSIONS)
searchproviders.initialize_providers()
self.assertTrue(searchproviders._initialized)
self.assertEqual(
len(searchproviders._providers), len(settings.MISAGO_SEARCH_EXTENSIONS)
)
for i, provider in enumerate(searchproviders._providers):
classname = settings.MISAGO_SEARCH_EXTENSIONS[i].split(".")[-1]
self.assertEqual(provider.__name__, classname)
def test_get_providers(self):
"""get_providers returns initialized providers"""
searchproviders = SearchProviders([])
searchproviders._initialized = True
searchproviders._providers = [MockProvider, MockProvider, MockProvider]
self.assertEqual(
[m.__class__ for m in searchproviders.get_providers(True)],
searchproviders._providers,
)
def test_providers_are_init_with_request(self):
"""providers constructor is provided with request"""
searchproviders = SearchProviders([])
searchproviders._initialized = True
searchproviders._providers = [MockProvider]
self.assertEqual(searchproviders.get_providers("REQUEST")[0].request, "REQUEST")
def test_get_allowed_providers(self):
"""
allowed providers getter returns only providers that didn't raise an exception
in allow_search
"""
searchproviders = SearchProviders([])
searchproviders._initialized = True
searchproviders._providers = [MockProvider, DisallowedProvider, MockProvider]
self.assertEqual(
[m.__class__ for m in searchproviders.get_allowed_providers(True)],
[MockProvider, MockProvider],
)
| 2,271
|
Python
|
.py
| 49
| 38.183673
| 88
| 0.704948
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,411
|
test_api.py
|
rafalp_Misago/misago/search/tests/test_api.py
|
from django.urls import reverse
from ...acl.test import patch_user_acl
from ...users.test import AuthenticatedUserTestCase
from ..searchproviders import searchproviders
class SearchApiTests(AuthenticatedUserTestCase):
def setUp(self):
super().setUp()
self.test_link = reverse("misago:api:search")
@patch_user_acl({"can_search": False})
def test_no_permission(self):
"""api validates permission to search"""
response = self.client.get(self.test_link)
self.assertEqual(response.status_code, 403)
self.assertEqual(
response.json(), {"detail": "You don't have permission to search site."}
)
def test_no_phrase(self):
"""api handles no search query"""
response = self.client.get(self.test_link)
self.assertEqual(response.status_code, 200)
providers = searchproviders.get_providers(True)
for i, provider in enumerate(response.json()):
provider_api = reverse(
"misago:api:search", kwargs={"search_provider": providers[i].url}
)
self.assertEqual(provider_api, provider["api"])
self.assertEqual(str(providers[i].name), provider["name"])
self.assertEqual(provider["results"]["results"], [])
self.assertEqual(int(provider["time"]), 0)
def test_empty_search(self):
"""api handles empty search query"""
response = self.client.get("%s?q=" % self.test_link)
self.assertEqual(response.status_code, 200)
providers = searchproviders.get_providers(True)
for i, provider in enumerate(response.json()):
provider_api = reverse(
"misago:api:search", kwargs={"search_provider": providers[i].url}
)
self.assertEqual(provider_api, provider["api"])
self.assertEqual(str(providers[i].name), provider["name"])
self.assertEqual(provider["results"]["results"], [])
self.assertEqual(int(provider["time"]), 0)
| 2,032
|
Python
|
.py
| 42
| 38.928571
| 84
| 0.638706
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,412
|
test_views.py
|
rafalp_Misago/misago/search/tests/test_views.py
|
from django.urls import reverse
from ...acl.test import patch_user_acl
from ...threads.search import SearchThreads
from ...users.test import AuthenticatedUserTestCase
class LandingTests(AuthenticatedUserTestCase):
def setUp(self):
super().setUp()
self.test_link = reverse("misago:search")
@patch_user_acl({"can_search": False})
def test_no_permission(self):
"""view validates permission to search forum"""
response = self.client.get(self.test_link)
self.assertContains(response, "have permission to search site", status_code=403)
@patch_user_acl({"can_search": True})
def test_redirect_to_provider(self):
"""view validates permission to search forum"""
response = self.client.get(self.test_link)
self.assertEqual(response.status_code, 302)
self.assertIn(SearchThreads.url, response["location"])
class SearchTests(AuthenticatedUserTestCase):
@patch_user_acl({"can_search": False})
def test_no_permission(self):
"""view validates permission to search forum"""
response = self.client.get(
reverse("misago:search", kwargs={"search_provider": "users"})
)
self.assertContains(response, "have permission to search site", status_code=403)
def test_not_found(self):
"""view raises 404 for not found provider"""
response = self.client.get(
reverse("misago:search", kwargs={"search_provider": "nada"})
)
self.assertEqual(response.status_code, 404)
@patch_user_acl({"can_search": True, "can_search_users": False})
def test_provider_no_permission(self):
"""provider raises 403 without permission"""
response = self.client.get(
reverse("misago:search", kwargs={"search_provider": "users"})
)
self.assertContains(
response, "have permission to search users", status_code=403
)
def test_provider(self):
"""provider displays no script page"""
response = self.client.get(
reverse("misago:search", kwargs={"search_provider": "users"})
)
self.assertContains(response, "Loading search...")
| 2,196
|
Python
|
.py
| 48
| 37.9375
| 88
| 0.663385
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,413
|
users.py
|
rafalp_Misago/misago/notifications/users.py
|
from typing import TYPE_CHECKING, Optional
from django.db.models import F
from ..categories.models import Category
from ..threads.models import Post, Thread
from .models import Notification
if TYPE_CHECKING:
from ..users.models import User
def notify_user(
user: "User",
verb: str,
actor: Optional["User"] = None,
category: Optional[Category] = None,
thread: Optional[Thread] = None,
post: Optional[Post] = None,
) -> Notification:
notification = Notification.objects.create(
user=user,
verb=verb,
actor=actor,
actor_name=actor.username if actor else None,
category=category,
thread=thread,
thread_title=thread.title if thread else None,
post=post,
)
user.unread_notifications = F("unread_notifications") + 1
user.save(update_fields=["unread_notifications"])
return notification
| 898
|
Python
|
.py
| 28
| 26.821429
| 61
| 0.698725
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,414
|
signals.py
|
rafalp_Misago/misago/notifications/signals.py
|
from django.contrib.auth import get_user_model
from django.dispatch import receiver
from django.db.models import Q
from django.db.models.signals import pre_delete
from ..users.signals import (
anonymize_user_data,
archive_user_data,
delete_user_content,
username_changed,
)
from .registry import registry
from .models import Notification, WatchedThread
@receiver(archive_user_data)
def archive_user_notifications(sender, archive=None, **kwargs):
queryset = Notification.objects.filter(Q(user=sender) | Q(actor=sender)).order_by(
"id"
)
for notification in queryset.iterator(chunk_size=50):
item_name = notification.created_at.strftime("%H%M%S-notification")
archive.add_text(
item_name,
registry.get_message(notification),
date=notification.created_at,
)
@receiver([anonymize_user_data, username_changed])
def update_actor_name(sender, **kwargs):
Notification.objects.filter(actor=sender).update(actor_name=sender.username)
@receiver(delete_user_content)
def delete_user_data(sender, **kwargs):
Notification.objects.filter(Q(user=sender) | Q(actor=sender)).delete()
WatchedThread.objects.filter(user=sender).delete()
@receiver(pre_delete, sender=get_user_model())
def delete_user_account(sender, *, instance, **kwargs):
Notification.objects.filter(actor=instance).update(actor=None)
Notification.objects.filter(user=instance).delete()
WatchedThread.objects.filter(user=instance).delete()
| 1,518
|
Python
|
.py
| 36
| 37.555556
| 86
| 0.747283
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,415
|
models.py
|
rafalp_Misago/misago/notifications/models.py
|
from django.conf import settings
from django.db import models
from django.utils.crypto import get_random_string
from django.utils import timezone
from django.urls import reverse
WATCHED_THREAD_SECRET = 32
def get_watched_thread_secret() -> str:
return get_random_string(WATCHED_THREAD_SECRET)
class Notification(models.Model):
id = models.BigAutoField(primary_key=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
verb = models.CharField(max_length=32)
is_read = models.BooleanField(default=False)
actor = models.ForeignKey(
settings.AUTH_USER_MODEL,
blank=True,
null=True,
on_delete=models.SET_NULL,
related_name="+",
)
actor_name = models.CharField(max_length=255, blank=True, null=True)
category = models.ForeignKey(
"misago_categories.Category", blank=True, null=True, on_delete=models.CASCADE
)
thread = models.ForeignKey(
"misago_threads.Thread", blank=True, null=True, on_delete=models.CASCADE
)
thread_title = models.CharField(max_length=255, blank=True, null=True)
post = models.ForeignKey(
"misago_threads.Post", blank=True, null=True, on_delete=models.CASCADE
)
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
def get_absolute_url(self) -> str:
return reverse("misago:notification", kwargs={"notification_id": self.id})
class Meta:
indexes = [
models.Index(fields=["-id", "user"]),
models.Index(fields=["-id", "user", "is_read"]),
models.Index(
name="misago_noti_user_unread",
fields=["user", "is_read"],
condition=models.Q(is_read=False),
),
models.Index(fields=["user", "post", "is_read"]),
]
class WatchedThread(models.Model):
id = models.BigAutoField(primary_key=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
category = models.ForeignKey("misago_categories.Category", on_delete=models.CASCADE)
thread = models.ForeignKey("misago_threads.Thread", on_delete=models.CASCADE)
send_emails = models.BooleanField(default=True)
secret = models.CharField(
max_length=WATCHED_THREAD_SECRET, default=get_watched_thread_secret
)
created_at = models.DateTimeField(auto_now_add=True)
read_time = models.DateTimeField(default=timezone.now)
class Meta:
indexes = [
models.Index(fields=["user", "-thread"]),
]
def get_disable_emails_url(self):
return reverse(
"misago:notifications-disable-email",
kwargs={
"watched_thread_id": self.id,
"secret": self.secret,
},
)
| 2,802
|
Python
|
.py
| 68
| 33.602941
| 88
| 0.660655
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,416
|
urls.py
|
rafalp_Misago/misago/notifications/urls.py
|
from django.urls import path
from .views import disable_email_notifications, notification, notifications
urlpatterns = [
path(
"notifications/disable-email/<int:watched_thread_id>/<str:secret>/",
disable_email_notifications,
name="notifications-disable-email",
),
path("notification/<int:notification_id>/", notification, name="notification"),
path("notifications/", notifications, name="notifications"),
path("notifications/unread/", notifications, name="notifications-unread"),
path("notifications/read/", notifications, name="notifications-read"),
]
| 603
|
Python
|
.py
| 13
| 41.538462
| 83
| 0.734694
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,417
|
tasks.py
|
rafalp_Misago/misago/notifications/tasks.py
|
from logging import getLogger
from celery import shared_task
from django.conf import settings
from django.contrib.auth import get_user_model
from ..cache.versions import get_cache_versions
from ..conf.dynamicsettings import DynamicSettings
from ..users.bans import get_user_ban
from ..threads.models import Post, Thread
from .models import WatchedThread
from .threads import (
notify_participant_on_new_private_thread,
notify_watcher_on_new_thread_reply,
)
NOTIFY_CHUNK_SIZE = 32
User = get_user_model()
logger = getLogger("misago.notifications")
@shared_task(
name="notifications.new-thread-reply",
autoretry_for=(Post.DoesNotExist,),
default_retry_delay=settings.MISAGO_NOTIFICATIONS_RETRY_DELAY,
serializer="json",
)
def notify_on_new_thread_reply(reply_id: int):
post = Post.objects.select_related("poster", "thread", "category").get(id=reply_id)
post.thread.category = post.category
if not WatchedThread.objects.filter(thread=post.thread).exists():
return # Nobody is watching this thread, stop
cache_versions = get_cache_versions()
dynamic_settings = DynamicSettings(cache_versions)
queryset = WatchedThread.objects.filter(thread=post.thread).select_related("user")
for watched_thread in queryset.iterator(chunk_size=NOTIFY_CHUNK_SIZE):
if (
watched_thread.user == post.poster
or not watched_thread.user.is_active
or get_user_ban(watched_thread.user, cache_versions)
):
continue # Skip poster and banned or inactive watchers
try:
notify_watcher_on_new_thread_reply(
watched_thread, post, cache_versions, dynamic_settings
)
except Exception:
logger.exception("Unexpected error in 'notify_watcher_on_new_thread_reply'")
@shared_task(
name="notifications.new-private-thread",
autoretry_for=(Thread.DoesNotExist,),
default_retry_delay=settings.MISAGO_NOTIFICATIONS_RETRY_DELAY,
serializer="json",
)
def notify_on_new_private_thread(
actor_id: int,
thread_id: int,
participants: list[int],
):
actor = User.objects.filter(id=actor_id).first()
if not actor:
return
thread = Thread.objects.select_related("category", "first_post").get(id=thread_id)
cache_versions = get_cache_versions()
dynamic_settings = DynamicSettings(cache_versions)
queryset = User.objects.filter(id__in=participants)
for participant in queryset.iterator(chunk_size=NOTIFY_CHUNK_SIZE):
if not participant.is_active or get_user_ban(participant, cache_versions):
continue # Skip inactive or banned participants
try:
notify_participant_on_new_private_thread(
participant, actor, thread, cache_versions, dynamic_settings
)
except Exception:
logger.exception(
"Unexpected error in 'notify_participant_on_new_private_thread'"
)
@shared_task(serializer="json")
def delete_duplicate_watched_threads(thread_id: int):
# Merge send emails preference for watched threads
email_notifications_users_ids = WatchedThread.objects.filter(
thread_id=thread_id,
send_emails=True,
).values("user_id")
WatchedThread.objects.filter(
thread_id=thread_id,
send_emails=False,
user_id__in=email_notifications_users_ids,
).update(send_emails=True)
# Delete duplicate watched threads
kept_watched_threads_ids = (
WatchedThread.objects.filter(
thread_id=thread_id,
)
.order_by("user_id", "-read_time")
.distinct("user_id")
.values("id")
)
WatchedThread.objects.filter(thread_id=thread_id).exclude(
id__in=kept_watched_threads_ids
).delete()
| 3,819
|
Python
|
.py
| 96
| 33.208333
| 88
| 0.696757
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,418
|
apps.py
|
rafalp_Misago/misago/notifications/apps.py
|
from django.apps import AppConfig
class MisagoNotificationsConfig(AppConfig):
name = "misago.notifications"
label = "misago_notifications"
verbose_name = "Misago Notifications"
def ready(self):
from . import signals as _ # noqa: F401
| 262
|
Python
|
.py
| 7
| 32.571429
| 48
| 0.730159
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,419
|
threads.py
|
rafalp_Misago/misago/notifications/threads.py
|
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Dict, Iterable, Optional
from django.db.models import IntegerChoices
from django.urls import reverse
from django.utils.translation import pgettext, pgettext_lazy
from ..acl.useracl import get_user_acl
from ..categories.enums import CategoryTree
from ..conf.dynamicsettings import DynamicSettings
from ..core.mail import build_mail
from ..threads.models import Post, Thread, ThreadParticipant
from ..threads.permissions.privatethreads import (
can_see_private_thread,
can_use_private_threads,
)
from ..threads.permissions.threads import (
can_see_post,
can_see_thread,
exclude_invisible_posts,
)
from ..threads.threadurl import get_thread_url
from .verbs import NotificationVerb
from .models import Notification, WatchedThread
from .users import notify_user
if TYPE_CHECKING:
from ..users.models import User
class ThreadNotifications(IntegerChoices):
NONE = 0, pgettext_lazy("notification type", "Don't notify")
SITE_ONLY = 1, pgettext_lazy("notification type", "Notify on site only")
SITE_AND_EMAIL = 2, pgettext_lazy(
"notification type", "Notify on site and with e-mail"
)
def get_watched_thread(user: "User", thread: Thread) -> Optional[WatchedThread]:
"""Returns watched thread entry for given user and thread combo.
If multiple entries are returned, it quietly heals this user's watching entry.
"""
watched_threads = WatchedThread.objects.filter(user=user, thread=thread).order_by(
"id"
)[:2]
if not watched_threads:
return None
watched_thread = watched_threads[0]
if len(watched_threads) > 1:
WatchedThread.objects.filter(user=user, thread=thread).exclude(
id=watched_thread.id
).delete()
return watched_thread
def get_watched_threads(
user: "User", threads: Iterable[Thread]
) -> Dict[int, ThreadNotifications]:
queryset = (
WatchedThread.objects.filter(user=user, thread__in=threads)
.order_by("-id")
.values_list("thread_id", "send_emails")
)
return {
thread_id: (
ThreadNotifications.SITE_AND_EMAIL
if send_emails
else ThreadNotifications.SITE_ONLY
)
for thread_id, send_emails in queryset
}
def watch_started_thread(user: "User", thread: Thread):
if user.watch_started_threads:
WatchedThread.objects.create(
user=user,
category=thread.category,
thread=thread,
send_emails=user.watch_started_threads
== ThreadNotifications.SITE_AND_EMAIL,
)
def watch_replied_thread(user: "User", thread: Thread) -> WatchedThread | None:
if not user.watch_replied_threads:
return
if WatchedThread.objects.filter(user=user, thread=thread).exists():
return None
send_emails = user.watch_replied_threads == ThreadNotifications.SITE_AND_EMAIL
return WatchedThread.objects.create(
user=user,
category=thread.category,
thread=thread,
send_emails=send_emails,
)
def update_watched_thread_read_time(user: "User", thread: Thread, read_time: datetime):
WatchedThread.objects.filter(user=user, thread=thread).update(read_time=read_time)
def notify_watcher_on_new_thread_reply(
watched_thread: WatchedThread,
post: Post,
cache_versions: Dict[str, str],
settings: DynamicSettings,
):
is_private = post.category.tree_id == CategoryTree.PRIVATE_THREADS
user_acl = get_user_acl(watched_thread.user, cache_versions)
if not user_can_see_post(watched_thread.user, user_acl, post, is_private):
return # Skip this watcher because they can't see the post
if user_has_other_unread_posts(watched_thread, user_acl, post, is_private):
return # We only notify on first unread post
notify_user(
watched_thread.user,
NotificationVerb.REPLIED,
post.poster,
post.category,
post.thread,
post,
)
if watched_thread.send_emails:
email_watcher_on_new_thread_reply(watched_thread, post, settings)
def email_watcher_on_new_thread_reply(
watched_thread: WatchedThread,
post: Post,
settings: DynamicSettings,
):
subject = pgettext(
"new thread reply email subject", "%(thread)s - new reply by %(user)s"
) % {
"user": post.poster.username,
"thread": post.thread.title,
}
message = build_mail(
watched_thread.user,
subject,
"misago/emails/thread/reply",
sender=post.poster,
context={
"settings": settings,
"watched_thread": watched_thread,
"thread": post.thread,
"thread_url": get_thread_url(post.thread),
"post": post,
},
)
message.send()
def user_has_other_unread_posts(
watched_thread: WatchedThread,
user_acl: dict,
post: Post,
is_private: bool,
) -> bool:
posts_queryset = Post.objects.filter(
id__lt=post.id,
thread=post.thread,
posted_on__gt=watched_thread.read_time,
).exclude(poster=watched_thread.user)
if not is_private:
posts_queryset = exclude_invisible_posts(
user_acl, post.category, posts_queryset
)
return posts_queryset.exists()
def user_can_see_post(
user: "User",
user_acl: dict,
post: Post,
is_private: bool,
) -> bool:
if is_private:
return user_can_see_post_in_private_thread(user, user_acl, post)
return can_see_thread(user_acl, post.thread) and can_see_post(user_acl, post)
def user_can_see_post_in_private_thread(
user: "User", user_acl: dict, post: Post
) -> bool:
if not can_use_private_threads(user_acl):
return False
is_participant = ThreadParticipant.objects.filter(
thread=post.thread, user=user
).exists()
if not can_see_private_thread(user_acl, post.thread, is_participant):
return False
return True
def notify_participant_on_new_private_thread(
user: "User",
actor: "User",
thread: Thread,
cache_versions: dict[str, str],
settings: DynamicSettings,
):
user_acl = get_user_acl(user, cache_versions)
if not user_can_see_private_thread(user, user_acl, thread):
return False # User can't see private thread
actor_is_followed = user.is_following(actor)
watched_thread = watch_new_private_thread(user, thread, actor_is_followed)
if actor_is_followed:
notification = user.notify_new_private_threads_by_followed
else:
notification = user.notify_new_private_threads_by_other_users
if notification == ThreadNotifications.NONE:
return # User has disabled notifications for new private threads
has_unread_notification = Notification.objects.filter(
user=user,
verb=NotificationVerb.INVITED,
post=thread.first_post,
is_read=False,
).exists()
if has_unread_notification:
return # Don't spam users with notifications
notify_user(
user,
NotificationVerb.INVITED,
actor,
thread.category,
thread,
thread.first_post,
)
if notification == ThreadNotifications.SITE_AND_EMAIL:
email_participant_on_new_private_thread(user, actor, watched_thread, settings)
def email_participant_on_new_private_thread(
user: "User",
actor: "User",
watched_thread: WatchedThread,
settings: DynamicSettings,
):
thread = watched_thread.thread
subject = pgettext(
"new private thread email subject",
'%(user)s has invited you to participate in private thread "%(thread)s"',
)
subject_formats = {"thread": thread.title, "user": actor.username}
message = build_mail(
user,
subject % subject_formats,
"misago/emails/privatethread/added",
sender=actor,
context={
"settings": settings,
"watched_thread": watched_thread,
"thread": thread,
"thread_url": reverse(
"misago:private-thread",
kwargs={"id": thread.id, "slug": thread.slug},
),
},
)
message.send()
def watch_new_private_thread(
user: "User", thread: Thread, from_followed: bool
) -> WatchedThread | None:
if from_followed:
notifications = user.watch_new_private_threads_by_followed
else:
notifications = user.watch_new_private_threads_by_other_users
if not notifications:
return None
send_emails = notifications == ThreadNotifications.SITE_AND_EMAIL
# Set thread read date in past to prevent first reply to thread
# From triggering extra notification
read_time = thread.started_on - timedelta(seconds=5)
if watched_thread := get_watched_thread(user, thread):
watched_thread.read_time = read_time
watched_thread.save(update_fields=["read_time"])
return watched_thread
return WatchedThread.objects.create(
user=user,
category=thread.category,
thread=thread,
send_emails=send_emails,
read_time=read_time,
)
def user_can_see_private_thread(user: "User", user_acl: dict, thread: Thread) -> bool:
if not can_use_private_threads(user_acl):
return False
is_participant = ThreadParticipant.objects.filter(thread=thread, user=user).exists()
if not can_see_private_thread(user_acl, thread, is_participant):
return False
return True
| 9,562
|
Python
|
.py
| 263
| 29.78327
| 88
| 0.676021
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,420
|
exceptions.py
|
rafalp_Misago/misago/notifications/exceptions.py
|
class NotificationVerbError(KeyError):
"""Raised by message and redirect factions for unknown notification types."""
pass
| 131
|
Python
|
.py
| 3
| 39.666667
| 81
| 0.779528
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,421
|
registry.py
|
rafalp_Misago/misago/notifications/registry.py
|
import html
from typing import TYPE_CHECKING, Callable, Dict, overload
from django.http import HttpRequest
from django.utils.translation import pgettext
from ..categories.enums import CategoryTree
from ..threads.views.redirect import get_redirect_to_post_response
from .verbs import NotificationVerb
from .exceptions import NotificationVerbError
if TYPE_CHECKING:
from .models import Notification
MessageFactory = Callable[["Notification"], str]
RedirectFactory = Callable[["HttpRequest", "Notification"], str]
class NotificationRegistry:
_messages: Dict[str, MessageFactory]
_redirects: Dict[str, RedirectFactory]
def __init__(self):
self._messages = {}
self._redirects = {}
@overload
def message(self, verb: str) -> Callable[[MessageFactory], MessageFactory]: ...
def message(self, verb: str, factory: MessageFactory | None = None) -> None:
"""Register `factory` function as message factory.
Can be called with two arguments or used as decorator:
```python
registry.message("replied", get_replied_message)
# ...or...
@registry.message("replied")
def get_replied_message(notification: Notification) -> str:
...
```
"""
if factory:
self._messages[verb] = factory
return
def register_factory(f: MessageFactory):
self._messages[verb] = f
return f
return register_factory
def get_message(self, notification: "Notification") -> str:
"""Returns `str` with message for given notification.
Raises `NotificationVerbError` when there's no message function for
given notification type.
```python
message = registry.get_message(notification)
```
"""
try:
return self._messages[notification.verb](notification)
except KeyError:
return get_unsupported_verb_notification_message(notification)
@overload
def redirect(self, verb: str) -> Callable[[RedirectFactory], RedirectFactory]: ...
def redirect(self, verb: str, factory: RedirectFactory | None = None) -> None:
"""Register `factory` function as redirect url factory.
Can be called with two arguments or used as decorator:
```python
registry.redirect("replied", get_replied_post_url)
# ...or...
@registry.redirect("replied")
def get_replied_post_url(notification: Notification) -> str:
...
```
"""
if factory:
self._redirects[verb] = factory
return
def register_factory(f: RedirectFactory):
self._redirects[verb] = f
return f
return register_factory
def get_redirect_url(
self, request: HttpRequest, notification: "Notification"
) -> str:
"""Returns `str` with redirect url to given notification's target.
Raises `NotificationVerbError` when there's no redirect function for
given notification type.
```python
message = registry.get_redirect_url(request, notification)
```
"""
try:
return self._redirects[notification.verb](request, notification)
except KeyError as exc:
raise NotificationVerbError(notification.verb) from exc
registry = NotificationRegistry()
# Fallback: used to produce messages for unsupported verbs
def get_unsupported_verb_notification_message(notification: "Notification") -> str:
message = notification.verb
if notification.actor_name:
message = f"{bold_escape(notification.actor_name)} {message}"
if notification.thread_title:
message = f"{message} {bold_escape(notification.thread_title)}"
return message
# TEST: used in tests only
@registry.message("TEST")
def get_test_notification_message(notification: "Notification") -> str:
return f"Test notification #{notification.id}"
@registry.redirect("TEST")
def get_test_notification_url(
request: HttpRequest, notification: "Notification"
) -> str:
return f"/#test-notification-{notification.id}"
# REPLIED: new reply in thread or private thread
@registry.message(NotificationVerb.REPLIED)
def get_replied_notification_message(notification: "Notification") -> str:
message = html.escape(
pgettext("notification replied", "%(actor)s replied to %(thread)s")
)
return message % {
"actor": bold_escape(notification.actor_name),
"thread": bold_escape(notification.thread_title),
}
@registry.redirect(NotificationVerb.REPLIED)
def get_replied_notification_url(
request: HttpRequest, notification: "Notification"
) -> str:
post = notification.post
post.category = notification.category
response = get_redirect_to_post_response(request, post)
return response.headers["location"]
# INVITED: invited to private thread
@registry.message(NotificationVerb.INVITED)
def get_invited_notification_message(notification: "Notification") -> str:
message = html.escape(
pgettext("notification invited", "%(actor)s invited you to %(thread)s")
)
return message % {
"actor": bold_escape(notification.actor_name),
"thread": bold_escape(notification.thread_title),
}
@registry.redirect(NotificationVerb.INVITED)
def get_invited_notification_url(
request: HttpRequest, notification: "Notification"
) -> str:
return notification.category.thread_type.get_thread_absolute_url(
notification.thread
)
def bold_escape(value: str) -> str:
return f"<b>{html.escape(value)}</b>"
| 5,662
|
Python
|
.py
| 139
| 33.935252
| 86
| 0.68527
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,422
|
verbs.py
|
rafalp_Misago/misago/notifications/verbs.py
|
from enum import StrEnum
class NotificationVerb(StrEnum):
REPLIED = "REPLIED"
INVITED = "INVITED"
| 108
|
Python
|
.py
| 4
| 23.5
| 32
| 0.754902
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,423
|
permissions.py
|
rafalp_Misago/misago/notifications/permissions.py
|
from typing import TYPE_CHECKING
from django.core.exceptions import PermissionDenied
from django.utils.translation import pgettext
if TYPE_CHECKING:
from misago.users.models import User
def allow_use_notifications(user: "User"):
if user.is_anonymous:
raise PermissionDenied(
pgettext(
"notifications permission",
"You must be signed in to access your notifications.",
)
)
| 456
|
Python
|
.py
| 13
| 27.615385
| 70
| 0.687927
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,424
|
targets.py
|
rafalp_Misago/misago/notifications/targets.py
|
from enum import StrEnum
class NotificationTarget(StrEnum):
USER = "USER"
THREAD = "THREAD"
POST = "POST"
| 120
|
Python
|
.py
| 5
| 20.2
| 34
| 0.699115
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,425
|
views.py
|
rafalp_Misago/misago/notifications/views.py
|
from django.db.models import F
from django.http import Http404, HttpRequest, HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from .exceptions import NotificationVerbError
from .models import Notification, WatchedThread
from .permissions import allow_use_notifications
from .registry import registry
def notifications(request: HttpRequest) -> HttpResponse:
allow_use_notifications(request.user)
return render(request, "misago/notifications.html")
def notification(request: HttpRequest, notification_id: int) -> HttpResponse:
allow_use_notifications(request.user)
user = request.user
notification = get_object_or_404(
Notification.objects.select_related(
"actor",
"category",
"thread",
"post",
),
user=user,
id=notification_id,
)
# Populate user relation cache
notification.user = request.user
if notification.category_id:
# Populate relations caches on thread and post models
if notification.thread_id:
notification.thread.category = notification.category
if notification.post_id:
notification.post.thread = notification.thread
notification.post.category = notification.category
if not notification.is_read:
notification.is_read = True
notification.save(update_fields=["is_read"])
if user.unread_notifications:
user.unread_notifications = F("unread_notifications") - 1
user.save(update_fields=["unread_notifications"])
try:
return redirect(registry.get_redirect_url(request, notification))
except NotificationVerbError as error:
raise Http404() from error
def disable_email_notifications(
request: HttpRequest, watched_thread_id: int, secret: str
) -> HttpResponse:
watched_thread = get_object_or_404(
WatchedThread.objects.select_related("user", "category", "thread"),
id=watched_thread_id,
secret=secret,
)
if watched_thread.send_emails:
watched_thread.send_emails = False
watched_thread.save(update_fields=["send_emails"])
watched_thread.thread.category = watched_thread.category
return render(
request,
"misago/notifications_disabled.html",
{
"watcher": watched_thread.user,
"thread": watched_thread.thread,
},
)
| 2,438
|
Python
|
.py
| 62
| 32
| 77
| 0.692797
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,426
|
0004_rename_read_at_watchedthread_read_time.py
|
rafalp_Misago/misago/notifications/migrations/0004_rename_read_at_watchedthread_read_time.py
|
# Generated by Django 4.2.10 on 2024-09-03 17:17
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("misago_notifications", "0003_indexes"),
]
operations = [
migrations.RenameField(
model_name="watchedthread",
old_name="read_at",
new_name="read_time",
),
]
| 377
|
Python
|
.py
| 13
| 21.769231
| 49
| 0.610028
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,427
|
0002_migrate_threads_subscriptions.py
|
rafalp_Misago/misago/notifications/migrations/0002_migrate_threads_subscriptions.py
|
# Generated by Django 3.2.15 on 2023-03-30 22:39
from django.db import migrations
from django.utils import timezone
BATCH_SIZE_LIMIT = 50
def migrate_threads_subscriptions(apps, schema_editor):
WatchedThread = apps.get_model("misago_notifications", "WatchedThread")
Subscription = apps.get_model("misago_threads", "Subscription")
WatchedThread.objects.all().delete()
timezone_now = timezone.now()
batch = []
batch_size = 0
for subscription in Subscription.objects.iterator(chunk_size=100):
batch.append(
WatchedThread(
user_id=subscription.user_id,
category_id=subscription.category_id,
thread_id=subscription.thread_id,
send_emails=subscription.send_email,
created_at=timezone_now,
read_at=subscription.last_read_on,
)
)
batch_size += 1
if batch_size == BATCH_SIZE_LIMIT:
WatchedThread.objects.bulk_create(batch)
batch = []
batch_size = 0
if batch:
WatchedThread.objects.bulk_create(batch)
class Migration(migrations.Migration):
atomic = False
dependencies = [
("misago_notifications", "0001_initial"),
("misago_threads", "0001_initial"),
]
operations = [
migrations.RunPython(migrate_threads_subscriptions, migrations.RunPython.noop),
]
| 1,423
|
Python
|
.py
| 38
| 28.973684
| 87
| 0.644574
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,428
|
0001_initial.py
|
rafalp_Misago/misago/notifications/migrations/0001_initial.py
|
# Generated by Django 3.2.15 on 2023-04-12 20:46
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import misago.notifications.models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("misago_threads", "0012_set_dj_partial_indexes"),
("misago_categories", "0009_auto_20221101_2111"),
]
operations = [
migrations.CreateModel(
name="WatchedThread",
fields=[
("id", models.BigAutoField(primary_key=True, serialize=False)),
("send_emails", models.BooleanField(default=True)),
(
"secret",
models.CharField(
default=misago.notifications.models.get_watched_thread_secret,
max_length=32,
),
),
("created_at", models.DateTimeField(auto_now_add=True)),
("read_at", models.DateTimeField(default=django.utils.timezone.now)),
(
"category",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="misago_categories.category",
),
),
(
"thread",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="misago_threads.thread",
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.CreateModel(
name="Notification",
fields=[
("id", models.BigAutoField(primary_key=True, serialize=False)),
("verb", models.CharField(max_length=32)),
("is_read", models.BooleanField(default=False)),
("actor_name", models.CharField(blank=True, max_length=255, null=True)),
(
"thread_title",
models.CharField(blank=True, max_length=255, null=True),
),
("created_at", models.DateTimeField(auto_now_add=True, db_index=True)),
(
"actor",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="+",
to=settings.AUTH_USER_MODEL,
),
),
(
"category",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="misago_categories.category",
),
),
(
"post",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="misago_threads.post",
),
),
(
"thread",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="misago_threads.thread",
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
),
]
| 4,171
|
Python
|
.py
| 110
| 20.145455
| 88
| 0.426529
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,429
|
0003_indexes.py
|
rafalp_Misago/misago/notifications/migrations/0003_indexes.py
|
# Generated by Django 3.2.15 on 2023-05-13 20:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("misago_notifications", "0002_migrate_threads_subscriptions"),
]
operations = [
migrations.AddIndex(
model_name="notification",
index=models.Index(
fields=["-id", "user"], name="misago_noti_id_5a01fa_idx"
),
),
migrations.AddIndex(
model_name="notification",
index=models.Index(
fields=["-id", "user", "is_read"], name="misago_noti_id_7b4a20_idx"
),
),
migrations.AddIndex(
model_name="notification",
index=models.Index(
condition=models.Q(("is_read", False)),
fields=["user", "is_read"],
name="misago_noti_user_unread",
),
),
migrations.AddIndex(
model_name="notification",
index=models.Index(
fields=["user", "post", "is_read"],
name="misago_noti_user_id_9b98fb_idx",
),
),
migrations.AddIndex(
model_name="watchedthread",
index=models.Index(
fields=["user", "-thread"], name="misago_noti_user_id_9cde34_idx"
),
),
]
| 1,382
|
Python
|
.py
| 41
| 22.560976
| 83
| 0.516829
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,430
|
test_username_change.py
|
rafalp_Misago/misago/notifications/tests/test_username_change.py
|
from ..models import Notification
def test_notification_actor_name_is_updated_on_username_change(user, other_user):
notification = Notification.objects.create(
user=user,
actor=other_user,
actor_name=other_user.username,
verb="TEST",
)
other_user.set_username("ChangedName")
notification.refresh_from_db()
assert notification.actor_name == "ChangedName"
| 410
|
Python
|
.py
| 11
| 31.181818
| 81
| 0.711392
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,431
|
test_delete_user_data.py
|
rafalp_Misago/misago/notifications/tests/test_delete_user_data.py
|
import pytest
from ..models import Notification, WatchedThread
def test_user_content_delete_deletes_user_notifications(user, other_user):
notification = Notification.objects.create(
user=user,
actor=other_user,
actor_name=other_user.username,
verb="TEST",
)
user.delete_content()
with pytest.raises(Notification.DoesNotExist):
notification.refresh_from_db()
def test_user_content_delete_deletes_actor_notifications(user, other_user):
notification = Notification.objects.create(
user=user,
actor=other_user,
actor_name=other_user.username,
verb="TEST",
)
other_user.delete_content()
with pytest.raises(Notification.DoesNotExist):
notification.refresh_from_db()
def test_user_content_delete_excludes_other_users_notifications(user, other_user):
notification = Notification.objects.create(
user=other_user,
verb="TEST",
)
user.delete_content()
notification.refresh_from_db()
def test_user_content_delete_deletes_users_watched_threads(
user, thread, watched_thread_factory
):
watched_thread = watched_thread_factory(user, thread, send_emails=True)
user.delete_content()
with pytest.raises(WatchedThread.DoesNotExist):
watched_thread.refresh_from_db()
def test_user_content_delete_excludes_other_users_watched_threads(
user, other_user, thread, watched_thread_factory
):
watched_thread = watched_thread_factory(other_user, thread, send_emails=True)
user.delete_content()
watched_thread.refresh_from_db()
| 1,604
|
Python
|
.py
| 42
| 32.309524
| 82
| 0.726801
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,432
|
test_notify_on_new_private_thread.py
|
rafalp_Misago/misago/notifications/tests/test_notify_on_new_private_thread.py
|
import pytest
from ...threads.models import ThreadParticipant
from ...users.bans import ban_user
from ..models import Notification, WatchedThread
from ..tasks import notify_on_new_private_thread
from ..threads import ThreadNotifications
from ..verbs import NotificationVerb
@pytest.fixture
def notify_participant_mock(mocker):
return mocker.patch(
"misago.notifications.tasks.notify_participant_on_new_private_thread"
)
def test_notify_on_new_private_thread_does_nothing_if_actor_is_not_found(
notify_participant_mock, other_user, private_thread
):
notify_on_new_private_thread(other_user.id + 1, private_thread.id, [other_user.id])
notify_participant_mock.assert_not_called()
def test_notify_on_new_private_thread_skips_banned_users(
notify_participant_mock, user, other_user, user_private_thread
):
other_user.notify_new_private_threads_by_followed = ThreadNotifications.NONE
other_user.notify_new_private_threads_by_other_users = (
ThreadNotifications.SITE_AND_EMAIL
)
other_user.save()
ThreadParticipant.objects.create(user=other_user, thread=user_private_thread)
ban_user(other_user)
notify_on_new_private_thread(user.id, user_private_thread.id, [other_user.id])
notify_participant_mock.assert_not_called()
def test_notify_on_new_private_thread_skips_inactive_users(
notify_participant_mock, user, inactive_user, user_private_thread
):
inactive_user.notify_new_private_threads_by_followed = ThreadNotifications.NONE
inactive_user.notify_new_private_threads_by_other_users = (
ThreadNotifications.SITE_AND_EMAIL
)
inactive_user.save()
ThreadParticipant.objects.create(user=inactive_user, thread=user_private_thread)
notify_on_new_private_thread(user.id, user_private_thread.id, [inactive_user.id])
notify_participant_mock.assert_not_called()
def test_notify_on_new_private_thread_handles_exceptions(
mocker, user, other_user, private_thread
):
ThreadParticipant.objects.create(user=other_user, thread=private_thread)
notify_participant_mock = mocker.patch(
"misago.notifications.tasks.notify_participant_on_new_private_thread",
side_effect=ValueError("Unknown"),
)
notify_on_new_private_thread(user.id, private_thread.id, [other_user.id])
notify_participant_mock.assert_called_once()
def test_notify_on_new_private_thread_creates_participant_watched_thread(
user, other_user, user_private_thread
):
other_user.watch_new_private_threads_by_followed = ThreadNotifications.NONE
other_user.watch_new_private_threads_by_other_users = (
ThreadNotifications.SITE_AND_EMAIL
)
other_user.save()
ThreadParticipant.objects.create(user=other_user, thread=user_private_thread)
notify_on_new_private_thread(user.id, user_private_thread.id, [other_user.id])
WatchedThread.objects.get(
user=other_user,
category=user_private_thread.category,
thread=user_private_thread,
send_emails=True,
)
def test_notify_on_new_private_thread_from_followed_creates_participant_watched_thread(
user, other_user, user_private_thread
):
other_user.watch_new_private_threads_by_followed = (
ThreadNotifications.SITE_AND_EMAIL
)
other_user.watch_new_private_threads_by_other_users = ThreadNotifications.NONE
other_user.save()
other_user.follows.add(user)
ThreadParticipant.objects.create(user=other_user, thread=user_private_thread)
notify_on_new_private_thread(user.id, user_private_thread.id, [other_user.id])
WatchedThread.objects.get(
user=other_user,
category=user_private_thread.category,
thread=user_private_thread,
send_emails=True,
)
def test_notify_on_new_private_thread_notifies_participant(
user, other_user, user_private_thread, mailoutbox
):
other_user.notify_new_private_threads_by_followed = ThreadNotifications.NONE
other_user.notify_new_private_threads_by_other_users = ThreadNotifications.SITE_ONLY
other_user.save()
ThreadParticipant.objects.create(user=other_user, thread=user_private_thread)
notify_on_new_private_thread(user.id, user_private_thread.id, [other_user.id])
other_user.refresh_from_db()
assert other_user.unread_notifications == 1
Notification.objects.get(user=other_user, actor=user)
assert len(mailoutbox) == 0
def test_notify_on_new_private_thread_notifies_participant_with_email(
user, other_user, user_private_thread, mailoutbox
):
other_user.notify_new_private_threads_by_followed = ThreadNotifications.NONE
other_user.notify_new_private_threads_by_other_users = (
ThreadNotifications.SITE_AND_EMAIL
)
other_user.save()
ThreadParticipant.objects.create(user=other_user, thread=user_private_thread)
notify_on_new_private_thread(user.id, user_private_thread.id, [other_user.id])
other_user.refresh_from_db()
assert other_user.unread_notifications == 1
Notification.objects.get(user=other_user, actor=user)
assert len(mailoutbox) == 1
def test_notify_on_new_private_thread_notifies_participant_following_actor(
user, other_user, user_private_thread, mailoutbox
):
other_user.notify_new_private_threads_by_followed = ThreadNotifications.SITE_ONLY
other_user.notify_new_private_threads_by_other_users = ThreadNotifications.NONE
other_user.save()
other_user.follows.add(user)
ThreadParticipant.objects.create(user=other_user, thread=user_private_thread)
notify_on_new_private_thread(user.id, user_private_thread.id, [other_user.id])
other_user.refresh_from_db()
assert other_user.unread_notifications == 1
Notification.objects.get(user=other_user, actor=user)
assert len(mailoutbox) == 0
def test_notify_on_new_private_thread_notifies_participant_following_actor_with_email(
user, other_user, user_private_thread, mailoutbox
):
other_user.notify_new_private_threads_by_followed = (
ThreadNotifications.SITE_AND_EMAIL
)
other_user.notify_new_private_threads_by_other_users = ThreadNotifications.NONE
other_user.save()
other_user.follows.add(user)
ThreadParticipant.objects.create(user=other_user, thread=user_private_thread)
notify_on_new_private_thread(user.id, user_private_thread.id, [other_user.id])
other_user.refresh_from_db()
assert other_user.unread_notifications == 1
Notification.objects.get(user=other_user, actor=user)
assert len(mailoutbox) == 1
def test_notify_on_new_private_thread_skips_notification_if_one_already_exists(
user, other_user, user_private_thread, mailoutbox
):
other_user.notify_new_private_threads_by_followed = ThreadNotifications.NONE
other_user.notify_new_private_threads_by_other_users = (
ThreadNotifications.SITE_AND_EMAIL
)
other_user.save()
ThreadParticipant.objects.create(user=other_user, thread=user_private_thread)
Notification.objects.create(
user=other_user,
verb=NotificationVerb.INVITED,
category=user_private_thread.category,
thread=user_private_thread,
post=user_private_thread.first_post,
is_read=False,
)
notify_on_new_private_thread(user.id, user_private_thread.id, [other_user.id])
other_user.refresh_from_db()
assert other_user.unread_notifications == 0
Notification.objects.count() == 1
assert len(mailoutbox) == 0
def test_notify_on_new_private_thread_notifies_participant_if_old_notification_is_read(
user, other_user, user_private_thread, mailoutbox
):
other_user.notify_new_private_threads_by_followed = ThreadNotifications.NONE
other_user.notify_new_private_threads_by_other_users = (
ThreadNotifications.SITE_AND_EMAIL
)
other_user.save()
ThreadParticipant.objects.create(user=other_user, thread=user_private_thread)
Notification.objects.create(
user=other_user,
verb=NotificationVerb.INVITED,
category=user_private_thread.category,
thread=user_private_thread,
post=user_private_thread.first_post,
is_read=True,
)
notify_on_new_private_thread(user.id, user_private_thread.id, [other_user.id])
other_user.refresh_from_db()
assert other_user.unread_notifications == 1
Notification.objects.count() == 2
assert len(mailoutbox) == 1
def test_notify_on_new_private_thread_skips_participant_if_they_have_no_permission(
mocker, user, other_user, user_private_thread, mailoutbox
):
other_user.notify_new_private_threads_by_followed = ThreadNotifications.NONE
other_user.notify_new_private_threads_by_other_users = (
ThreadNotifications.SITE_AND_EMAIL
)
other_user.save()
ThreadParticipant.objects.create(user=other_user, thread=user_private_thread)
can_use_private_threads_mock = mocker.patch(
"misago.notifications.threads.can_use_private_threads",
return_value=False,
)
notify_on_new_private_thread(user.id, user_private_thread.id, [other_user.id])
other_user.refresh_from_db()
assert other_user.unread_notifications == 0
assert not Notification.objects.exists()
assert len(mailoutbox) == 0
can_use_private_threads_mock.assert_called_once()
def test_notify_on_new_private_thread_skips_user_not_participating(
user, other_user, user_private_thread, mailoutbox
):
other_user.notify_new_private_threads_by_followed = ThreadNotifications.NONE
other_user.notify_new_private_threads_by_other_users = (
ThreadNotifications.SITE_AND_EMAIL
)
other_user.save()
ThreadParticipant.objects.filter(user=other_user).delete()
notify_on_new_private_thread(user.id, user_private_thread.id, [other_user.id])
other_user.refresh_from_db()
assert other_user.unread_notifications == 0
assert not Notification.objects.exists()
assert len(mailoutbox) == 0
| 9,919
|
Python
|
.py
| 214
| 41
| 88
| 0.748597
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,433
|
test_disable_email_notifications.py
|
rafalp_Misago/misago/notifications/tests/test_disable_email_notifications.py
|
from django.urls import reverse
def test_disable_email_notifications_view_disables_emails_for_watched_thread(
watched_thread_factory, user, user_client, thread
):
watched_thread = watched_thread_factory(user, thread, send_emails=True)
response = user_client.get(
reverse(
"misago:notifications-disable-email",
kwargs={
"watched_thread_id": watched_thread.id,
"secret": watched_thread.secret,
},
)
)
assert response.status_code == 200
watched_thread.refresh_from_db()
assert not watched_thread.send_emails
def test_disable_email_notifications_view_works_without_authentication(
watched_thread_factory, user, client, thread
):
watched_thread = watched_thread_factory(user, thread, send_emails=True)
response = client.get(
reverse(
"misago:notifications-disable-email",
kwargs={
"watched_thread_id": watched_thread.id,
"secret": watched_thread.secret,
},
)
)
assert response.status_code == 200
watched_thread.refresh_from_db()
assert not watched_thread.send_emails
def test_disable_email_notifications_view_returns_404_if_secret_is_invalid(
watched_thread_factory, user, client, thread
):
watched_thread = watched_thread_factory(user, thread, send_emails=True)
response = client.get(
reverse(
"misago:notifications-disable-email",
kwargs={
"watched_thread_id": watched_thread.id,
"secret": "invalid",
},
)
)
assert response.status_code == 404
def test_disable_email_notifications_view_returns_404_if_watched_thread_is_not_found(
watched_thread_factory, user, client, thread
):
watched_thread = watched_thread_factory(user, thread, send_emails=True)
response = client.get(
reverse(
"misago:notifications-disable-email",
kwargs={
"watched_thread_id": watched_thread.id + 1,
"secret": watched_thread.secret,
},
)
)
assert response.status_code == 404
| 2,190
|
Python
|
.py
| 61
| 27.590164
| 85
| 0.636407
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,434
|
test_anonymize_data.py
|
rafalp_Misago/misago/notifications/tests/test_anonymize_data.py
|
from ..models import Notification
def test_notification_actor_name_is_anonymized(user, other_user):
notification = Notification.objects.create(
user=user,
actor=other_user,
actor_name=other_user.username,
verb="TEST",
)
other_user.anonymize_data("Deleted")
notification.refresh_from_db()
assert notification.actor_name == "Deleted"
| 388
|
Python
|
.py
| 11
| 29.181818
| 65
| 0.702413
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,435
|
test_notification_registry.py
|
rafalp_Misago/misago/notifications/tests/test_notification_registry.py
|
import pytest
from ..exceptions import NotificationVerbError
from ..registry import NotificationRegistry, registry
from ..models import Notification
from ..verbs import NotificationVerb
@pytest.fixture
def request_mock(rf, user):
request = rf.get("/notification/1/")
request.user = user
return request
def test_notification_registry_can_have_message_set_with_setter():
notification_registry = NotificationRegistry()
notification_registry.message("TEST", lambda obj: f"Hello #{obj.id}")
message = notification_registry.get_message(Notification(id=1, verb="TEST"))
assert message == "Hello #1"
def test_notification_registry_can_have_message_set_with_decorator():
notification_registry = NotificationRegistry()
@notification_registry.message("TEST")
def get_test_message(obj):
return f"Hello #{obj.id}"
message = notification_registry.get_message(Notification(id=1, verb="TEST"))
assert message == "Hello #1"
def test_notification_registry_get_message_produces_message_for_unsupported_verb():
notification_registry = NotificationRegistry()
message = notification_registry.get_message(Notification(id=1, verb="REMOVED"))
assert message == "REMOVED"
def test_notification_registry_get_message_produces_message_with_actor_name_for_unsupported_verb():
notification_registry = NotificationRegistry()
message = notification_registry.get_message(
Notification(id=1, verb="REMOVED", actor_name="ACTOR")
)
assert message == "<b>ACTOR</b> REMOVED"
def test_notification_registry_get_message_produces_message_with_thread_title_for_unsupported_verb():
notification_registry = NotificationRegistry()
message = notification_registry.get_message(
Notification(id=1, verb="REMOVED", thread_title="THREAD")
)
assert message == "REMOVED <b>THREAD</b>"
def test_notification_registry_get_message_produces_message_with_actor_and_thread_for_unsupported_verb():
notification_registry = NotificationRegistry()
message = notification_registry.get_message(
Notification(
id=1,
verb="REMOVED",
actor_name="ACTOR",
thread_title="THREAD",
)
)
assert message == "<b>ACTOR</b> REMOVED <b>THREAD</b>"
def test_notification_registry_can_have_redirect_set_with_setter(request_mock):
notification_registry = NotificationRegistry()
notification_registry.redirect("TEST", lambda _, obj: f"/test/#{obj.id}")
redirect = notification_registry.get_redirect_url(
request_mock, Notification(id=1, verb="TEST")
)
assert redirect == "/test/#1"
def test_notification_registry_can_have_redirect_set_with_decorator(
request_mock,
):
notification_registry = NotificationRegistry()
@notification_registry.redirect("TEST")
def get_test_redirect_url(request, obj):
return f"/test/#{obj.id}"
redirect = notification_registry.get_redirect_url(
request_mock, Notification(id=1, verb="TEST")
)
assert redirect == "/test/#1"
def test_notification_registry_get_redirect_url_raises_verb_error_for_unknown_verb(
request_mock,
):
notification_registry = NotificationRegistry()
with pytest.raises(NotificationVerbError) as excinfo:
notification_registry.get_redirect_url(
request_mock, Notification(id=1, verb="TEST")
)
assert "TEST" in str(excinfo)
def test_default_notification_registry_supports_test_notifications(request_mock):
message = registry.get_message(Notification(id=1, verb="TEST"))
assert message == "Test notification #1"
redirect = registry.get_redirect_url(request_mock, Notification(id=1, verb="TEST"))
assert redirect == "/#test-notification-1"
def test_default_notification_registry_supports_reply_notifications():
message = registry.get_message(
Notification(
id=1,
verb=NotificationVerb.REPLIED,
actor_name="Aerith",
thread_title="Midgar was destroyed!",
)
)
assert message == ("<b>Aerith</b> replied to <b>Midgar was destroyed!</b>")
def test_default_notification_registry_supports_invite_notifications():
message = registry.get_message(
Notification(
id=1,
verb=NotificationVerb.INVITED,
actor_name="Aerith",
thread_title="Midgar was destroyed!",
)
)
assert message == ("<b>Aerith</b> invited you to <b>Midgar was destroyed!</b>")
| 4,514
|
Python
|
.py
| 101
| 38.524752
| 105
| 0.709906
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,436
|
test_update_watched_thread_read_time.py
|
rafalp_Misago/misago/notifications/tests/test_update_watched_thread_read_time.py
|
from django.utils import timezone
from ..threads import update_watched_thread_read_time
def test_update_watched_thread_read_time_updates_watched_thread_read_time(
thread, user, watched_thread_factory
):
watched_thread = watched_thread_factory(user, thread, False)
new_read_time = timezone.now()
update_watched_thread_read_time(user, thread, new_read_time)
watched_thread.refresh_from_db()
assert watched_thread.read_time == new_read_time
def test_update_watched_thread_read_time_doesnt_update_other_threads_entries(
thread, other_thread, user, watched_thread_factory
):
watched_thread = watched_thread_factory(user, other_thread, False)
new_read_time = timezone.now()
update_watched_thread_read_time(user, thread, new_read_time)
watched_thread.refresh_from_db()
assert watched_thread.read_time != new_read_time
def test_update_watched_thread_read_time_doesnt_update_other_users_entries(
thread, user, other_user, watched_thread_factory
):
watched_thread = watched_thread_factory(other_user, thread, False)
new_read_time = timezone.now()
update_watched_thread_read_time(user, thread, new_read_time)
watched_thread.refresh_from_db()
assert watched_thread.read_time != new_read_time
def test_update_watched_thread_read_time_does_nothing_if_watched_thread_doesnt_exist(
thread, user
):
new_read_time = timezone.now()
update_watched_thread_read_time(user, thread, new_read_time)
| 1,473
|
Python
|
.py
| 31
| 43.322581
| 85
| 0.756833
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,437
|
test_clearnotifications_command.py
|
rafalp_Misago/misago/notifications/tests/test_clearnotifications_command.py
|
from datetime import timedelta
from io import StringIO
from django.core import management
from django.utils import timezone
from ...conf.test import override_dynamic_settings
from ..management.commands import clearnotifications
from ..models import Notification
def call_command():
command = clearnotifications.Command()
out = StringIO()
management.call_command(command, stdout=out)
return out.getvalue().strip().splitlines()[-1].strip()
def test_command_works_if_there_are_no_notifications(db):
command_output = call_command()
assert command_output == "No old notifications have been deleted."
@override_dynamic_settings(delete_notifications_older_than=5)
def test_recent_notification_is_kept(user, post):
Notification.objects.create(user=user, verb="TEST")
command_output = call_command()
assert command_output == "No old notifications have been deleted."
assert Notification.objects.exists()
@override_dynamic_settings(delete_notifications_older_than=5)
def test_old_notification_is_deleted(user, post):
Notification.objects.create(user=user, verb="TEST")
Notification.objects.update(created_at=timezone.now() - timedelta(days=10))
command_output = call_command()
assert command_output == "Deleted 1 old notifications."
assert not Notification.objects.exists()
| 1,337
|
Python
|
.py
| 28
| 44.142857
| 79
| 0.777006
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,438
|
test_delete_duplicate_watched_threads.py
|
rafalp_Misago/misago/notifications/tests/test_delete_duplicate_watched_threads.py
|
from datetime import timedelta
import pytest
from django.utils import timezone
from ..models import WatchedThread
from ..tasks import delete_duplicate_watched_threads
def test_delete_duplicate_watched_threads_deletes_duplicates_ordered_by_read_time_desc(
user, thread
):
kept_watched_thread = WatchedThread.objects.create(
user=user,
category=thread.category,
thread=thread,
read_time=timezone.now(),
)
deleted_watched_thread = WatchedThread.objects.create(
user=user,
category=thread.category,
thread=thread,
read_time=timezone.now() - timedelta(seconds=30),
)
delete_duplicate_watched_threads(thread.id)
kept_watched_thread.refresh_from_db()
with pytest.raises(WatchedThread.DoesNotExist):
deleted_watched_thread.refresh_from_db()
assert WatchedThread.objects.count() == 1
def test_delete_duplicate_watched_threads_keeps_email_notifications(user, thread):
kept_watched_thread = WatchedThread.objects.create(
user=user,
category=thread.category,
thread=thread,
send_emails=False,
read_time=timezone.now(),
)
deleted_watched_thread = WatchedThread.objects.create(
user=user,
category=thread.category,
thread=thread,
send_emails=True,
read_time=timezone.now() - timedelta(seconds=30),
)
delete_duplicate_watched_threads(thread.id)
kept_watched_thread.refresh_from_db()
assert kept_watched_thread.send_emails
with pytest.raises(WatchedThread.DoesNotExist):
deleted_watched_thread.refresh_from_db()
assert WatchedThread.objects.count() == 1
def test_delete_duplicate_watched_threads_skips_non_duplicated_watched_threads(
user, other_user, thread
):
kept_watched_thread = WatchedThread.objects.create(
user=user,
category=thread.category,
thread=thread,
read_time=timezone.now(),
)
deleted_watched_thread = WatchedThread.objects.create(
user=user,
category=thread.category,
thread=thread,
read_time=timezone.now() - timedelta(seconds=30),
)
other_kept_watched_thread = WatchedThread.objects.create(
user=other_user,
category=thread.category,
thread=thread,
read_time=timezone.now(),
)
delete_duplicate_watched_threads(thread.id)
kept_watched_thread.refresh_from_db()
other_kept_watched_thread.refresh_from_db()
with pytest.raises(WatchedThread.DoesNotExist):
deleted_watched_thread.refresh_from_db()
assert WatchedThread.objects.count() == 2
def test_delete_duplicate_watched_threads_skips_other_threads_watched_threads(
user, other_user, thread, other_thread
):
kept_watched_thread = WatchedThread.objects.create(
user=user,
category=thread.category,
thread=thread,
read_time=timezone.now(),
)
deleted_watched_thread = WatchedThread.objects.create(
user=user,
category=thread.category,
thread=thread,
read_time=timezone.now() - timedelta(seconds=30),
)
other_kept_watched_thread = WatchedThread.objects.create(
user=other_user,
category=thread.category,
thread=thread,
read_time=timezone.now(),
)
other_thread_watched_thread = WatchedThread.objects.create(
user=other_user,
category=other_thread.category,
thread=other_thread,
read_time=timezone.now(),
)
other_thread_watched_thread_duplicate = WatchedThread.objects.create(
user=other_user,
category=other_thread.category,
thread=other_thread,
read_time=timezone.now(),
)
delete_duplicate_watched_threads(thread.id)
other_thread_watched_thread.refresh_from_db()
other_thread_watched_thread_duplicate.refresh_from_db()
kept_watched_thread.refresh_from_db()
other_kept_watched_thread.refresh_from_db()
with pytest.raises(WatchedThread.DoesNotExist):
deleted_watched_thread.refresh_from_db()
assert WatchedThread.objects.count() == 4
| 4,133
|
Python
|
.py
| 114
| 29.517544
| 87
| 0.699423
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,439
|
test_notification_view.py
|
rafalp_Misago/misago/notifications/tests/test_notification_view.py
|
from django.urls import reverse
from ...test import assert_contains
from ...threads.models import ThreadParticipant
from ..verbs import NotificationVerb
from ..models import Notification
from ..registry import registry
def test_notification_view_returns_redirect_to_user_notification(rf, user, user_client):
request = rf.get("/notification/1/")
notification = Notification.objects.create(user=user, verb="TEST")
response = user_client.get(
reverse("misago:notification", kwargs={"notification_id": notification.id})
)
assert response.status_code == 302
assert response.headers["location"] == registry.get_redirect_url(
request, notification
)
def test_notification_view_sets_notification_as_read(user, user_client):
notification = Notification.objects.create(user=user, verb="TEST", is_read=False)
response = user_client.get(
reverse("misago:notification", kwargs={"notification_id": notification.id})
)
assert response.status_code == 302
notification.refresh_from_db()
assert notification.is_read
def test_notification_view_updates_user_unread_notifications_count(user, user_client):
user.unread_notifications = 1
user.save()
notification = Notification.objects.create(user=user, verb="TEST", is_read=False)
response = user_client.get(
reverse("misago:notification", kwargs={"notification_id": notification.id})
)
assert response.status_code == 302
user.refresh_from_db()
assert user.unread_notifications == 0
def test_notification_view_skips_user_unread_notifications_count_for_read_notification(
user, user_client
):
user.unread_notifications = 1
user.save()
notification = Notification.objects.create(user=user, verb="TEST", is_read=True)
response = user_client.get(
reverse("misago:notification", kwargs={"notification_id": notification.id})
)
assert response.status_code == 302
user.refresh_from_db()
assert user.unread_notifications == 1
def test_notification_view_returns_404_error_for_nonexisting_notification(user_client):
response = user_client.get(
reverse("misago:notification", kwargs={"notification_id": 1})
)
assert response.status_code == 404
def test_notification_view_returns_404_error_for_other_user_notification(
other_user, user_client
):
notification = Notification.objects.create(user=other_user, verb="TEST")
response = user_client.get(
reverse("misago:notification", kwargs={"notification_id": notification.id})
)
assert response.status_code == 404
def test_notification_view_returns_404_error_for_unsupported_verb_notification(
user, user_client
):
notification = Notification.objects.create(user=user, verb="REMOVED")
response = user_client.get(
reverse("misago:notification", kwargs={"notification_id": notification.id})
)
assert response.status_code == 404
def test_notification_view_shows_permission_denied_page_to_guests(db, client):
response = client.get(reverse("misago:notification", kwargs={"notification_id": 1}))
assert_contains(response, "You must be signed in", status_code=403)
def test_notification_view_returns_redirect_to_thread_reply(
user, user_client, default_category, thread, reply
):
notification = Notification.objects.create(
user=user,
verb=NotificationVerb.REPLIED,
category=default_category,
thread=thread,
thread_title=thread.title,
post=reply,
)
response = user_client.get(
reverse("misago:notification", kwargs={"notification_id": notification.id})
)
assert response.status_code == 302
assert response.headers["location"]
def test_notification_view_returns_redirect_to_private_thread_reply(
user, user_client, private_threads_category, private_thread, private_thread_reply
):
ThreadParticipant.objects.create(thread=private_thread, user=user)
notification = Notification.objects.create(
user=user,
verb=NotificationVerb.REPLIED,
category=private_threads_category,
thread=private_thread,
thread_title=private_thread.title,
post=private_thread_reply,
)
response = user_client.get(
reverse("misago:notification", kwargs={"notification_id": notification.id})
)
assert response.status_code == 302
assert response.headers["location"]
def test_notification_view_returns_redirect_to_private_thread_invite(
user, user_client, private_threads_category, private_thread
):
ThreadParticipant.objects.create(thread=private_thread, user=user)
notification = Notification.objects.create(
user=user,
verb=NotificationVerb.INVITED,
category=private_threads_category,
thread=private_thread,
thread_title=private_thread.title,
post_id=private_thread.first_post_id,
)
response = user_client.get(
reverse("misago:notification", kwargs={"notification_id": notification.id})
)
assert response.status_code == 302
assert response.headers["location"]
| 5,119
|
Python
|
.py
| 120
| 37.183333
| 88
| 0.728957
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,440
|
test_notify_user.py
|
rafalp_Misago/misago/notifications/tests/test_notify_user.py
|
from ..models import Notification
from ..users import notify_user
def test_notify_user_creates_notification_for_user(user):
notification = notify_user(user, "TEST")
assert notification
assert notification.user == user
assert notification.verb == "TEST"
assert notification.actor is None
assert notification.actor_name is None
assert notification.category is None
assert notification.thread is None
assert notification.thread_title is None
assert notification.post is None
db_notification = Notification.objects.get(id=notification.id)
assert db_notification.user == user
assert db_notification.verb == "TEST"
assert db_notification.actor is None
assert db_notification.actor_name is None
assert db_notification.category is None
assert db_notification.thread is None
assert db_notification.thread_title is None
assert db_notification.post is None
def test_notify_user_increases_user_unread_notifications_counter(user):
assert user.unread_notifications == 0
assert notify_user(user, "TEST")
user.refresh_from_db()
assert user.unread_notifications == 1
def test_notify_user_sets_actor_on_notification(user, other_user):
notification = notify_user(user, "TEST", actor=other_user)
assert notification
assert notification.user == user
assert notification.verb == "TEST"
assert notification.actor == other_user
assert notification.actor_name == other_user.username
assert notification.category is None
assert notification.thread is None
assert notification.thread_title is None
assert notification.post is None
db_notification = Notification.objects.get(id=notification.id)
assert db_notification.user == user
assert db_notification.verb == "TEST"
assert db_notification.actor == other_user
assert db_notification.actor_name == other_user.username
assert db_notification.category is None
assert db_notification.thread is None
assert db_notification.thread_title is None
assert db_notification.post is None
def test_notify_user_sets_category_on_notification(user, default_category):
notification = notify_user(user, "TEST", category=default_category)
assert notification
assert notification.user == user
assert notification.verb == "TEST"
assert notification.actor is None
assert notification.actor_name is None
assert notification.category == default_category
assert notification.thread is None
assert notification.thread_title is None
assert notification.post is None
db_notification = Notification.objects.get(id=notification.id)
assert db_notification.user == user
assert db_notification.verb == "TEST"
assert db_notification.actor is None
assert db_notification.actor_name is None
assert db_notification.category == default_category
assert db_notification.thread is None
assert db_notification.thread_title is None
assert db_notification.post is None
def test_notify_user_sets_thread_on_notification(user, thread):
notification = notify_user(user, "TEST", thread=thread)
assert notification
assert notification.user == user
assert notification.verb == "TEST"
assert notification.actor is None
assert notification.actor_name is None
assert notification.category is None
assert notification.thread == thread
assert notification.thread_title == thread.title
assert notification.post is None
db_notification = Notification.objects.get(id=notification.id)
assert db_notification.user == user
assert db_notification.verb == "TEST"
assert db_notification.actor is None
assert db_notification.actor_name is None
assert db_notification.category is None
assert db_notification.thread == thread
assert db_notification.thread_title == thread.title
assert db_notification.post is None
def test_notify_user_sets_post_on_notification(user, post):
notification = notify_user(user, "TEST", post=post)
assert notification
assert notification.user == user
assert notification.verb == "TEST"
assert notification.actor is None
assert notification.actor_name is None
assert notification.category is None
assert notification.thread is None
assert notification.thread_title is None
assert notification.post == post
db_notification = Notification.objects.get(id=notification.id)
assert db_notification.user == user
assert db_notification.verb == "TEST"
assert db_notification.actor is None
assert db_notification.actor_name is None
assert db_notification.category is None
assert db_notification.thread is None
assert db_notification.thread_title is None
assert db_notification.post == post
| 4,776
|
Python
|
.py
| 107
| 39.766355
| 75
| 0.763922
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,441
|
test_get_watched_thread.py
|
rafalp_Misago/misago/notifications/tests/test_get_watched_thread.py
|
from ..models import WatchedThread
from ..threads import get_watched_thread
def test_get_watched_thread_returns_null_if_thread_is_not_watched(user, thread):
watched_thread = get_watched_thread(user, thread)
assert watched_thread is None
def test_get_watched_thread_returns_watched_thread_for_user(
user, other_user, thread, watched_thread_factory
):
watched_thread_factory(other_user, thread, send_emails=True)
user_watched_thread = watched_thread_factory(user, thread, send_emails=True)
watched_thread = get_watched_thread(user, thread)
assert watched_thread == user_watched_thread
def test_get_watched_thread_returns_watched_thread_for_user_and_thread(
user, thread, other_thread, watched_thread_factory
):
watched_thread_factory(user, other_thread, send_emails=True)
watched_thread = get_watched_thread(user, thread)
assert watched_thread is None
def test_get_watched_thread_returns_first_watched_thread_for_user_if_multiple_exist(
user, thread, watched_thread_factory
):
first_watched_thread = watched_thread_factory(user, thread, send_emails=True)
watched_thread_factory(user, thread, send_emails=False)
watched_thread = get_watched_thread(user, thread)
assert watched_thread == first_watched_thread
def test_get_watched_thread_removes_extra_watched_threads_for_user(
user, thread, watched_thread_factory
):
first_watched_thread = watched_thread_factory(user, thread, send_emails=True)
watched_thread_factory(user, thread, send_emails=False)
assert WatchedThread.objects.count() == 2
watched_thread = get_watched_thread(user, thread)
assert watched_thread == first_watched_thread
assert WatchedThread.objects.count() == 1
| 1,735
|
Python
|
.py
| 34
| 46.852941
| 84
| 0.767359
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,442
|
test_notifications_view.py
|
rafalp_Misago/misago/notifications/tests/test_notifications_view.py
|
from django.urls import reverse
from ...test import assert_contains
def test_notifications_view_is_accessible_by_users(user_client):
response = user_client.get(reverse("misago:notifications"))
assert_contains(response, "Notifications")
assert_contains(response, "enable JavaScript")
def test_notifications_view_shows_permission_denied_page_to_guests(db, client):
response = client.get(reverse("misago:notifications"))
assert_contains(response, "You must be signed in", status_code=403)
| 511
|
Python
|
.py
| 9
| 53
| 79
| 0.780684
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,443
|
test_notify_on_new_thread_reply.py
|
rafalp_Misago/misago/notifications/tests/test_notify_on_new_thread_reply.py
|
from datetime import timedelta
import pytest
from django.utils import timezone
from ...threads.models import ThreadParticipant
from ...users.bans import ban_user
from ..models import Notification
from ..tasks import notify_on_new_thread_reply
@pytest.fixture
def notify_watcher_mock(mocker):
return mocker.patch("misago.notifications.tasks.notify_watcher_on_new_thread_reply")
def test_notify_on_new_thread_reply_does_nothing_for_unwatched_thread(
notify_watcher_mock, user_reply
):
notify_on_new_thread_reply(user_reply.id)
notify_watcher_mock.assert_not_called()
def test_notify_on_new_thread_reply_skips_reply_author(
watched_thread_factory, notify_watcher_mock, user, thread, user_reply
):
watched_thread_factory(user, thread, send_emails=True)
notify_on_new_thread_reply(user_reply.id)
notify_watcher_mock.assert_not_called()
def test_notify_on_new_thread_reply_skips_watcher_with_deactivated_account(
watched_thread_factory, notify_watcher_mock, inactive_user, thread, user_reply
):
watched_thread_factory(inactive_user, thread, send_emails=True)
notify_on_new_thread_reply(user_reply.id)
notify_watcher_mock.assert_not_called()
def test_notify_on_new_thread_reply_skips_watcher_with_banned_account(
watched_thread_factory, notify_watcher_mock, other_user, thread, user_reply
):
ban_user(other_user)
watched_thread_factory(other_user, thread, send_emails=True)
notify_on_new_thread_reply(user_reply.id)
notify_watcher_mock.assert_not_called()
def test_notify_on_new_thread_reply_handles_exceptions(
mocker, watched_thread_factory, other_user, thread, user_reply
):
notify_watcher_mock = mocker.patch(
"misago.notifications.tasks.notify_watcher_on_new_thread_reply",
side_effect=ValueError("Unknown"),
)
watched_thread_factory(other_user, thread, send_emails=True)
notify_on_new_thread_reply(user_reply.id)
notify_watcher_mock.assert_called_once()
def test_notify_on_new_thread_reply_notifies_user_about_thread_reply(
watched_thread_factory, user, other_user, thread, user_reply, mailoutbox
):
watched_thread_factory(other_user, thread, send_emails=False)
notify_on_new_thread_reply(user_reply.id)
other_user.refresh_from_db()
assert other_user.unread_notifications == 1
Notification.objects.get(user=other_user, actor=user)
assert len(mailoutbox) == 0
def test_notify_on_new_thread_reply_notifies_user_with_email_about_thread_reply(
watched_thread_factory, user, other_user, thread, user_reply, mailoutbox
):
watched_thread_factory(other_user, thread, send_emails=True)
notify_on_new_thread_reply(user_reply.id)
other_user.refresh_from_db()
assert other_user.unread_notifications == 1
Notification.objects.get(user=other_user, actor=user)
assert len(mailoutbox) == 1
def test_notify_on_new_thread_reply_checks_user_thread_permissions(
mocker, watched_thread_factory, other_user, thread, user_reply, mailoutbox
):
can_see_thread_mock = mocker.patch(
"misago.notifications.threads.can_see_thread", return_value=False
)
watched_thread_factory(other_user, thread, send_emails=True)
notify_on_new_thread_reply(user_reply.id)
other_user.refresh_from_db()
assert other_user.unread_notifications == 0
assert not Notification.objects.exists()
assert len(mailoutbox) == 0
can_see_thread_mock.assert_called_once()
def test_notify_on_new_thread_reply_checks_user_has_no_older_unread_posts(
watched_thread_factory, other_user, thread, user_reply, mailoutbox
):
watched_thread = watched_thread_factory(other_user, thread, send_emails=True)
# Make thread's first post unread
watched_thread.read_time = timezone.now() - timedelta(seconds=5)
watched_thread.save()
notify_on_new_thread_reply(user_reply.id)
other_user.refresh_from_db()
assert other_user.unread_notifications == 0
assert not Notification.objects.exists()
assert len(mailoutbox) == 0
def test_notify_on_new_thread_reply_excludes_user_posts_from_unread_check(
watched_thread_factory, user, other_user, thread, post, user_reply, mailoutbox
):
watched_thread = watched_thread_factory(other_user, thread, send_emails=True)
# Make thread's first post unread
watched_thread.read_time = timezone.now() - timedelta(seconds=5)
watched_thread.save()
# Make thread's first post author the watcher
post.poster = other_user
post.save()
notify_on_new_thread_reply(user_reply.id)
other_user.refresh_from_db()
assert other_user.unread_notifications == 1
Notification.objects.get(user=other_user, actor=user)
assert len(mailoutbox) == 1
def test_notify_on_new_thread_reply_notifies_user_with_email_about_private_thread_reply(
watched_thread_factory,
other_user,
private_thread,
user,
private_thread_user_reply,
mailoutbox,
):
ThreadParticipant.objects.create(thread=private_thread, user=other_user)
watched_thread_factory(other_user, private_thread, send_emails=True)
notify_on_new_thread_reply(private_thread_user_reply.id)
other_user.refresh_from_db()
assert other_user.unread_notifications == 1
Notification.objects.get(user=other_user, actor=user)
assert len(mailoutbox) == 1
def test_notify_on_new_thread_reply_checks_if_user_is_private_thread_participant(
watched_thread_factory,
other_user,
private_thread,
private_thread_user_reply,
mailoutbox,
):
watched_thread_factory(other_user, private_thread, send_emails=True)
notify_on_new_thread_reply(private_thread_user_reply.id)
other_user.refresh_from_db()
assert other_user.unread_notifications == 0
assert not Notification.objects.exists()
assert len(mailoutbox) == 0
| 5,813
|
Python
|
.py
| 130
| 40.230769
| 88
| 0.753641
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,444
|
test_watch_new_private_thread.py
|
rafalp_Misago/misago/notifications/tests/test_watch_new_private_thread.py
|
from ..models import WatchedThread
from ..threads import ThreadNotifications, watch_new_private_thread
def test_private_thread_is_watched_with_email_notifications(user, private_thread):
user.watch_new_private_threads_by_other_users = ThreadNotifications.SITE_AND_EMAIL
user.save()
watched_thread = watch_new_private_thread(user, private_thread, from_followed=False)
assert watched_thread.user == user
assert watched_thread.category == private_thread.category
assert watched_thread.thread == private_thread
assert watched_thread.send_emails
assert watched_thread.read_time < private_thread.started_on
WatchedThread.objects.get(
user=user,
thread=private_thread,
send_emails=True,
)
def test_private_thread_is_watched_without_email_notifications(user, private_thread):
user.watch_new_private_threads_by_other_users = ThreadNotifications.SITE_ONLY
user.save()
watched_thread = watch_new_private_thread(user, private_thread, from_followed=False)
assert watched_thread.user == user
assert watched_thread.category == private_thread.category
assert watched_thread.thread == private_thread
assert not watched_thread.send_emails
assert watched_thread.read_time < private_thread.started_on
WatchedThread.objects.get(
user=user,
thread=private_thread,
send_emails=False,
)
def test_private_thread_is_not_watched(user, private_thread):
user.watch_new_private_threads_by_other_users = ThreadNotifications.NONE
user.save()
watched_thread = watch_new_private_thread(user, private_thread, from_followed=False)
assert watched_thread is None
assert not WatchedThread.objects.exists()
def test_private_thread_from_followed_is_watched_with_email_notifications(
user, private_thread
):
user.watch_new_private_threads_by_followed = ThreadNotifications.SITE_AND_EMAIL
user.save()
watched_thread = watch_new_private_thread(user, private_thread, from_followed=True)
assert watched_thread.user == user
assert watched_thread.category == private_thread.category
assert watched_thread.thread == private_thread
assert watched_thread.send_emails
assert watched_thread.read_time < private_thread.started_on
WatchedThread.objects.get(
user=user,
thread=private_thread,
send_emails=True,
)
def test_private_thread_from_followed_is_watched_without_email_notifications(
user, private_thread
):
user.watch_new_private_threads_by_followed = ThreadNotifications.SITE_ONLY
user.save()
watched_thread = watch_new_private_thread(user, private_thread, from_followed=True)
assert watched_thread.user == user
assert watched_thread.category == private_thread.category
assert watched_thread.thread == private_thread
assert not watched_thread.send_emails
assert watched_thread.read_time < private_thread.started_on
WatchedThread.objects.get(
user=user,
thread=private_thread,
send_emails=False,
)
def test_private_thread_from_followed_is_not_watched(user, private_thread):
user.watch_new_private_threads_by_followed = ThreadNotifications.NONE
user.save()
watched_thread = watch_new_private_thread(user, private_thread, from_followed=True)
assert watched_thread is None
assert not WatchedThread.objects.exists()
def test_old_watched_thread_notifications_are_not_disabled_by_new_preference(
user, private_thread
):
old_watched_thread = WatchedThread.objects.create(
user=user,
thread=private_thread,
category=private_thread.category,
send_emails=True,
)
user.watch_new_private_threads_by_other_users = ThreadNotifications.SITE_ONLY
user.save()
watched_thread = watch_new_private_thread(user, private_thread, from_followed=False)
assert watched_thread.id == old_watched_thread.id
assert watched_thread.send_emails
WatchedThread.objects.get(
user=user,
thread=private_thread,
send_emails=True,
)
| 4,078
|
Python
|
.py
| 93
| 38.182796
| 88
| 0.746646
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,445
|
test_watch_replied_thread.py
|
rafalp_Misago/misago/notifications/tests/test_watch_replied_thread.py
|
from ..models import WatchedThread
from ..threads import ThreadNotifications, watch_replied_thread
def test_replied_thread_is_watched_with_email_notifications(user, thread):
user.watch_replied_threads = ThreadNotifications.SITE_AND_EMAIL
user.save()
watch_replied_thread(user, thread)
watched_thread = WatchedThread.objects.get(user=user, thread=thread)
assert watched_thread.send_emails
def test_replied_thread_is_watched_without_email_notifications(user, thread):
user.watch_replied_threads = ThreadNotifications.SITE_ONLY
user.save()
watch_replied_thread(user, thread)
watched_thread = WatchedThread.objects.get(user=user, thread=thread)
assert not watched_thread.send_emails
def test_replied_thread_is_not_watched_if_option_is_disabled(user, thread):
user.watch_replied_threads = ThreadNotifications.NONE
user.save()
watch_replied_thread(user, thread)
assert not WatchedThread.objects.exists()
def test_replied_thread_watching_entry_notification_emails_are_not_disabled(
user, thread, watched_thread_factory
):
user.watch_replied_threads = ThreadNotifications.SITE_ONLY
user.save()
watched_thread = watched_thread_factory(user, thread, send_emails=True)
watch_replied_thread(user, thread)
watched_thread = WatchedThread.objects.get(user=user, thread=thread)
assert watched_thread.send_emails
def test_replied_thread_watching_entry_notification_emails_are_not_enabled(
user, thread, watched_thread_factory
):
user.watch_replied_threads = ThreadNotifications.SITE_AND_EMAIL
user.save()
watched_thread = watched_thread_factory(user, thread, send_emails=False)
watch_replied_thread(user, thread)
watched_thread = WatchedThread.objects.get(user=user, thread=thread)
assert not watched_thread.send_emails
def test_replied_thread_watching_entry_is_not_removed_if_option_is_disabled(
user, thread, watched_thread_factory
):
user.watch_replied_threads = ThreadNotifications.NONE
user.save()
watched_thread = watched_thread_factory(user, thread, send_emails=False)
watch_replied_thread(user, thread)
watched_thread = WatchedThread.objects.get(user=user, thread=thread)
assert not watched_thread.send_emails
| 2,268
|
Python
|
.py
| 46
| 44.673913
| 77
| 0.778132
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,446
|
test_get_watched_threads.py
|
rafalp_Misago/misago/notifications/tests/test_get_watched_threads.py
|
from ..threads import ThreadNotifications, get_watched_threads
def test_get_watched_threads_returns_empty_dict_if_threads_are_not_watched(
user, thread, other_thread
):
watched_threads = get_watched_threads(user, [thread, other_thread])
assert watched_threads == {}
def test_get_watched_threads_returns_watched_threads_for_user(
user, other_user, thread, other_thread, watched_thread_factory
):
watched_thread_factory(other_user, thread, send_emails=True)
watched_thread_factory(user, thread, send_emails=False)
watched_thread_factory(user, other_thread, send_emails=True)
watched_threads = get_watched_threads(user, [thread, other_thread])
assert watched_threads == {
thread.id: ThreadNotifications.SITE_ONLY,
other_thread.id: ThreadNotifications.SITE_AND_EMAIL,
}
def test_get_watched_threads_excludes_unspecified_threads(
user, thread, other_thread, watched_thread_factory
):
watched_thread_factory(user, other_thread, send_emails=True)
watched_threads = get_watched_threads(user, [thread])
assert watched_threads == {}
def test_get_watched_threads_returns_first_watched_thread_for_user(
user, thread, watched_thread_factory
):
watched_thread_factory(user, thread, send_emails=False)
watched_thread_factory(user, thread, send_emails=True)
watched_threads = get_watched_threads(user, [thread])
assert watched_threads == {thread.id: ThreadNotifications.SITE_ONLY}
| 1,468
|
Python
|
.py
| 30
| 44.5
| 75
| 0.754029
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,447
|
test_permissions.py
|
rafalp_Misago/misago/notifications/tests/test_permissions.py
|
import pytest
from django.core.exceptions import PermissionDenied
from ..permissions import allow_use_notifications
def test_allow_use_notifications_permission_check_passes_authenticated(user):
allow_use_notifications(user)
def test_allow_use_notifications_permission_check_blocks_anonymous_users(
anonymous_user,
):
with pytest.raises(PermissionDenied) as excinfo:
allow_use_notifications(anonymous_user)
assert "You must be signed in" in str(excinfo)
| 483
|
Python
|
.py
| 11
| 40.181818
| 77
| 0.809013
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,448
|
test_delete_user_account.py
|
rafalp_Misago/misago/notifications/tests/test_delete_user_account.py
|
import pytest
from ..models import Notification, WatchedThread
def test_user_delete_deletes_user_notifications(user, other_user):
notification = Notification.objects.create(
user=user,
actor=other_user,
actor_name=other_user.username,
verb="TEST",
)
user.delete(anonymous_username="Deleted")
with pytest.raises(Notification.DoesNotExist):
notification.refresh_from_db()
def test_user_delete_clears_notifications_actor(user, other_user):
notification = Notification.objects.create(
user=user,
actor=other_user,
actor_name=other_user.username,
verb="TEST",
)
other_user.delete(anonymous_username="Deleted")
notification.refresh_from_db()
assert notification.actor is None
def test_user_delete_excludes_other_users_notifications(user, other_user):
notification = Notification.objects.create(
user=other_user,
verb="TEST",
)
user.delete(anonymous_username="Deleted")
notification.refresh_from_db()
def test_user_delete_deletes_users_watched_threads(
user, thread, watched_thread_factory
):
watched_thread = watched_thread_factory(user, thread, send_emails=True)
user.delete(anonymous_username="Deleted")
with pytest.raises(WatchedThread.DoesNotExist):
watched_thread.refresh_from_db()
def test_user_delete_excludes_other_users_watched_threads(
user, other_user, thread, watched_thread_factory
):
watched_thread = watched_thread_factory(other_user, thread, send_emails=True)
user.delete(anonymous_username="Deleted")
watched_thread.refresh_from_db()
| 1,646
|
Python
|
.py
| 42
| 33.404762
| 81
| 0.731522
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,449
|
test_watch_started_thread.py
|
rafalp_Misago/misago/notifications/tests/test_watch_started_thread.py
|
from ..models import WatchedThread
from ..threads import ThreadNotifications, watch_started_thread
def test_started_thread_is_watched_with_email_notifications(user, thread):
user.watch_started_threads = ThreadNotifications.SITE_AND_EMAIL
user.save()
watch_started_thread(user, thread)
watched_thread = WatchedThread.objects.get(user=user, thread=thread)
assert watched_thread.send_emails
def test_started_thread_is_watched_without_email_notifications(user, thread):
user.watch_started_threads = ThreadNotifications.SITE_ONLY
user.save()
watch_started_thread(user, thread)
watched_thread = WatchedThread.objects.get(user=user, thread=thread)
assert not watched_thread.send_emails
def test_started_thread_is_not_watched_if_option_is_disabled(user, thread):
user.watch_started_threads = ThreadNotifications.NONE
user.save()
watch_started_thread(user, thread)
assert not WatchedThread.objects.exists()
| 966
|
Python
|
.py
| 19
| 46.263158
| 77
| 0.785027
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,450
|
clearnotifications.py
|
rafalp_Misago/misago/notifications/management/commands/clearnotifications.py
|
from datetime import timedelta
from django.core.management.base import BaseCommand
from django.utils import timezone
from ....conf.shortcuts import get_dynamic_settings
from ...models import Notification
class Command(BaseCommand):
help = "Deletes old notifications"
def handle(self, *args, **options):
settings = get_dynamic_settings()
cutoff_date = timezone.now() - timedelta(
days=settings.delete_notifications_older_than
)
queryset = Notification.objects.filter(created_at__lt=cutoff_date)
deleted_count = queryset.count()
if deleted_count:
queryset.delete()
message = "\n\nDeleted %s old notifications." % deleted_count
else:
message = "\n\nNo old notifications have been deleted."
self.stdout.write(message)
| 841
|
Python
|
.py
| 20
| 34.7
| 74
| 0.687961
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,451
|
models.py
|
rafalp_Misago/misago/conf/models.py
|
from pathlib import Path
from django.db import models
from ..core.utils import get_file_hash
from .hydrators import dehydrate_value, hydrate_value
class SettingsManager(models.Manager):
def change_setting(self, setting, dry_value=None, wet_value=None):
if dry_value:
return self.filter(setting=setting).update(dry_value=dry_value)
if wet_value:
try:
setting = self.get(setting=setting)
setting.value = wet_value
setting.save(update_fields=["dry_value"])
except Setting.DoesNotExist:
return 0
class Setting(models.Model):
setting = models.CharField(max_length=255, unique=True)
python_type = models.CharField(max_length=255, default="string")
dry_value = models.TextField(null=True, blank=True)
image = models.ImageField(
upload_to="conf",
height_field="image_height",
width_field="image_width",
null=True,
blank=True,
)
image_size = models.PositiveIntegerField(null=True, blank=True)
image_width = models.PositiveIntegerField(null=True, blank=True)
image_height = models.PositiveIntegerField(null=True, blank=True)
is_public = models.BooleanField(default=False)
is_lazy = models.BooleanField(default=False)
objects = SettingsManager()
@property
def image_dimensions(self):
if self.image_width and self.image_height:
return self.image_width, self.image_height
return None
@property
def value(self):
if self.python_type == "image":
return self.image
return hydrate_value(self.python_type, self.dry_value)
@value.setter
def value(self, new_value):
if new_value is not None:
if self.python_type == "image":
rename_image_file(new_value, self.setting)
self.image = new_value
self.image_size = new_value.size
else:
self.dry_value = dehydrate_value(self.python_type, new_value)
else:
self.dry_value = None
return new_value
def rename_image_file(file_obj, prefix):
name_parts = [
prefix.replace("_", "-"),
get_file_hash(file_obj),
Path(file_obj.name).suffix.strip(".").lower(),
]
file_obj.name = ".".join(name_parts)
| 2,365
|
Python
|
.py
| 61
| 30.278689
| 77
| 0.638149
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,452
|
test.py
|
rafalp_Misago/misago/conf/test.py
|
from functools import wraps
from .dynamicsettings import DynamicSettings
class override_dynamic_settings:
def __init__(self, **settings):
self._overrides = settings
def __enter__(self):
DynamicSettings.override_settings(self._overrides)
def __exit__(self, *_):
DynamicSettings.remove_overrides()
def __call__(self, f):
@wraps(f)
def test_function_wrapper(*args, **kwargs):
with self:
return f(*args, **kwargs)
return test_function_wrapper
| 538
|
Python
|
.py
| 15
| 28.266667
| 58
| 0.637597
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,453
|
apps.py
|
rafalp_Misago/misago/conf/apps.py
|
from django.apps import AppConfig
class MisagoConfConfig(AppConfig):
name = "misago.conf"
label = "misago_conf"
verbose_name = "Misago Configuration"
| 164
|
Python
|
.py
| 5
| 29
| 41
| 0.751592
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,454
|
context_processors.py
|
rafalp_Misago/misago/conf/context_processors.py
|
import json
from hashlib import sha256
from django.templatetags.static import static
from django.urls import reverse
from django.utils.translation import get_language
import misago
from ..auth.loginurl import get_login_url
from . import settings
# Simple but hard to guess version signature for current Misago version
# Used to cache-bust django-i18n.js URL in the browser
I18N_VERSION_SIGNATURE = sha256(
(
f"{misago.__version__}{misago.__released__}"
f"{settings.LANGUAGE_CODE}{settings.SECRET_KEY}"
).encode()
).hexdigest()
def conf(request):
return {
"BLANK_AVATAR_URL": (
request.settings.blank_avatar or static(settings.MISAGO_BLANK_AVATAR)
),
"DEBUG": settings.DEBUG,
"I18N_VERSION_SIGNATURE": I18N_VERSION_SIGNATURE,
"LANGUAGE_CODE_SHORT": get_language()[:2],
"LOGIN_REDIRECT_URL": settings.LOGIN_REDIRECT_URL,
"LOGIN_URL": get_login_url(),
"LOGOUT_URL": settings.LOGOUT_URL,
"THREADS_ON_INDEX": settings.MISAGO_THREADS_ON_INDEX,
"CSRF_COOKIE_NAME": json.dumps(settings.CSRF_COOKIE_NAME),
"settings": request.settings,
}
def og_image(request):
og_image = request.settings.get("og_image")
if not og_image["value"]:
return {"og_image": None}
return {
"og_image": {
"url": og_image["value"],
"width": og_image["width"],
"height": og_image["height"],
}
}
def preload_settings_json(request):
preloaded_settings = request.settings.get_public_settings()
delegate_auth = request.settings.enable_oauth2_client
if request.settings.enable_oauth2_client:
login_url = reverse("misago:oauth2-login")
else:
login_url = get_login_url()
preloaded_settings.update(
{
"DELEGATE_AUTH": delegate_auth,
"LOGIN_API_URL": settings.MISAGO_LOGIN_API_URL,
"LOGIN_REDIRECT_URL": reverse(settings.LOGIN_REDIRECT_URL),
"LOGIN_URL": login_url,
"LOGOUT_URL": reverse(settings.LOGOUT_URL),
}
)
request.frontend_context.update(
{
"BLANK_AVATAR_URL": (
request.settings.blank_avatar or static(settings.MISAGO_BLANK_AVATAR)
),
"CSRF_COOKIE_NAME": settings.CSRF_COOKIE_NAME,
"ENABLE_DELETE_OWN_ACCOUNT": (
not delegate_auth and request.settings.allow_delete_own_account
),
"ENABLE_DOWNLOAD_OWN_DATA": request.settings.allow_data_downloads,
"MISAGO_PATH": reverse("misago:index"),
"SETTINGS": preloaded_settings,
"STATIC_URL": settings.STATIC_URL,
"THREADS_ON_INDEX": settings.MISAGO_THREADS_ON_INDEX,
"NOTIFICATIONS_API": reverse("misago:apiv2:notifications"),
"NOTIFICATIONS_URL": reverse("misago:notifications"),
}
)
if (
request.user.is_authenticated
and request.user.is_misago_admin
and request.settings.show_admin_panel_link_in_ui
):
request.frontend_context["ADMIN_URL"] = reverse("misago:admin:index")
return {}
| 3,175
|
Python
|
.py
| 83
| 30.204819
| 85
| 0.637073
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,455
|
dynamicsettings.py
|
rafalp_Misago/misago/conf/dynamicsettings.py
|
from .cache import get_settings_cache, set_settings_cache
from .models import Setting
class DynamicSettings:
_overrides = {}
def __init__(self, cache_versions):
self._settings = get_settings_cache(cache_versions)
if self._settings is None:
self._settings = get_settings_from_db()
set_settings_cache(cache_versions, self._settings)
def get(self, setting):
return self._settings.get(setting)
def get_public_settings(self):
public_settings = {}
for name, setting in self._settings.items():
if setting["is_public"]:
public_settings[name] = setting["value"]
return public_settings
def get_lazy_setting_value(self, setting):
try:
if self._settings[setting]["is_lazy"]:
if setting in self._overrides:
return self._overrides[setting]
if not self._settings[setting].get("real_value"):
real_value = Setting.objects.get(setting=setting).value
self._settings[setting]["real_value"] = real_value
return self._settings[setting]["real_value"]
raise ValueError("Setting %s is not lazy" % setting)
except (KeyError, Setting.DoesNotExist):
raise AttributeError("Setting %s is not defined" % setting)
def __getattr__(self, setting):
if setting in self._overrides:
return self._overrides[setting]
if setting in self._settings:
return self._settings[setting]["value"]
raise AttributeError("Setting %s is not defined" % setting)
@classmethod
def override_settings(cls, overrides):
cls._overrides = overrides
@classmethod
def remove_overrides(cls):
cls._overrides = {}
def get_settings_from_db():
settings = {}
for setting in Setting.objects.iterator():
settings[setting.setting] = {
"value": None,
"is_lazy": setting.is_lazy,
"is_public": setting.is_public,
"width": None,
"height": None,
}
if setting.is_lazy:
settings[setting.setting]["value"] = True if setting.value else None
elif setting.python_type == "image":
settings[setting.setting].update(
{
"value": setting.value.url if setting.value else None,
"width": setting.image_width,
"height": setting.image_height,
}
)
else:
settings[setting.setting]["value"] = setting.value
return settings
| 2,654
|
Python
|
.py
| 64
| 30.640625
| 80
| 0.589057
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,456
|
cache.py
|
rafalp_Misago/misago/conf/cache.py
|
from django.core.cache import cache
from . import SETTINGS_CACHE
from ..cache.versions import invalidate_cache
def get_settings_cache(cache_versions):
key = get_cache_key(cache_versions)
return cache.get(key)
def set_settings_cache(cache_versions, user_settings):
key = get_cache_key(cache_versions)
cache.set(key, user_settings)
def get_cache_key(cache_versions):
return "%s_%s" % (SETTINGS_CACHE, cache_versions[SETTINGS_CACHE])
def clear_settings_cache():
invalidate_cache(SETTINGS_CACHE)
| 525
|
Python
|
.py
| 13
| 36.846154
| 69
| 0.763419
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,457
|
defaults.py
|
rafalp_Misago/misago/conf/defaults.py
|
# pylint: disable=line-too-long
"""
Default Misago settings. Override these with settings in the module pointed to
by the DJANGO_SETTINGS_MODULE environment variable.
If you rely on any of those in your code, make sure you use `misago.conf.settings`
instead of Django's `django.conf.settings`.
"""
# Permissions system extensions
# https://misago.readthedocs.io/en/latest/developers/acls.html#extending-permissions-system
MISAGO_ACL_EXTENSIONS = [
"misago.users.permissions.account",
"misago.users.permissions.profiles",
"misago.users.permissions.moderation",
"misago.users.permissions.delete",
"misago.categories.permissions",
"misago.threads.permissions.attachments",
"misago.threads.permissions.polls",
"misago.threads.permissions.threads",
"misago.threads.permissions.privatethreads",
"misago.threads.permissions.bestanswers",
"misago.search.permissions",
]
# Path to the directory that Misago should use to prepare user data downloads.
# Should not be accessible from internet.
MISAGO_USER_DATA_DOWNLOADS_WORKING_DIR = None
# Custom markup extensions
MISAGO_MARKUP_EXTENSIONS = []
# Custom post validators
MISAGO_POST_VALIDATORS = []
# Post search filters
MISAGO_POST_SEARCH_FILTERS = []
# Posting middlewares
# https://misago.readthedocs.io/en/latest/developers/posting_process.html
MISAGO_POSTING_MIDDLEWARES = [
# Always keep FloodProtectionMiddleware middleware first one
"misago.threads.api.postingendpoint.floodprotection.FloodProtectionMiddleware",
"misago.threads.api.postingendpoint.category.CategoryMiddleware",
"misago.threads.api.postingendpoint.privatethread.PrivateThreadMiddleware",
"misago.threads.api.postingendpoint.reply.ReplyMiddleware",
"misago.threads.api.postingendpoint.moderationqueue.ModerationQueueMiddleware",
"misago.threads.api.postingendpoint.attachments.AttachmentsMiddleware",
"misago.threads.api.postingendpoint.participants.ParticipantsMiddleware",
"misago.threads.api.postingendpoint.pin.PinMiddleware",
"misago.threads.api.postingendpoint.close.CloseMiddleware",
"misago.threads.api.postingendpoint.hide.HideMiddleware",
"misago.threads.api.postingendpoint.protect.ProtectMiddleware",
"misago.threads.api.postingendpoint.recordedit.RecordEditMiddleware",
"misago.threads.api.postingendpoint.updatestats.UpdateStatsMiddleware",
"misago.threads.api.postingendpoint.mentions.MentionsMiddleware",
"misago.threads.api.postingendpoint.syncprivatethreads.SyncPrivateThreadsMiddleware",
# Always keep SaveChangesMiddleware middleware after all state-changing middlewares
"misago.threads.api.postingendpoint.savechanges.SaveChangesMiddleware",
# Those middlewares are last because they don't change app state
"misago.threads.api.postingendpoint.notifications.NotificationsMiddleware",
]
# Configured thread types
MISAGO_THREAD_TYPES = [
"misago.threads.threadtypes.thread.Thread",
"misago.threads.threadtypes.privatethread.PrivateThread",
]
# Search extensions
MISAGO_SEARCH_EXTENSIONS = [
"misago.threads.search.SearchThreads",
"misago.users.search.SearchUsers",
]
# Additional registration validators
# https://misago.readthedocs.io/en/latest/developers/validating_registrations.html
MISAGO_NEW_REGISTRATIONS_VALIDATORS = [
"misago.users.validators.validate_gmail_email",
"misago.users.validators.validate_with_sfs",
]
# Custom profile fields
MISAGO_PROFILE_FIELDS = []
# Login API URL
MISAGO_LOGIN_API_URL = "auth"
# Misago Admin Path
# Omit starting and trailing slashes. To disable Misago admin, empty this value.
MISAGO_ADMIN_PATH = "admincp"
# Admin urls namespaces that Misago's AdminAuthMiddleware should protect
MISAGO_ADMIN_NAMESPACES = ["admin", "misago:admin"]
# How long (in minutes) since previous request to admin namespace should admin session last.
MISAGO_ADMIN_SESSION_EXPIRATION = 60
# Display threads on forum index
# Change this to false to display categories list instead
MISAGO_THREADS_ON_INDEX = True
# How many notifications may be retrieved from the API in single request?
MISAGO_NOTIFICATIONS_PAGE_LIMIT = 50
# How many unread notifications to track
# Misago will not report report unread notifications count bigger than this
# Example: if limit 50 and user has 56 unread notifications, UI will show "50+"
# Also used by the notifications healing mechanism
MISAGO_UNREAD_NOTIFICATIONS_LIMIT = 50
# Function used for generating individual avatar for user
MISAGO_DYNAMIC_AVATAR_DRAWER = "misago.users.avatars.dynamic.draw_default"
# Path to directory containing avatar galleries
# Those galleries can be loaded by running loadavatargallery command
MISAGO_AVATAR_GALLERY = None
# Save user avatars for sizes
# Keep sizes ordered from greatest to smallest
# Max size also controls min size of uploaded image as well as crop size
MISAGO_AVATARS_SIZES = [400, 200, 150, 128, 100, 64, 50, 40, 32, 20]
# Path to blank avatar image used for guests and removed users.
MISAGO_BLANK_AVATAR = "misago/img/blank-avatar.png"
# Max allowed size of image before Misago will generate thumbnail for it
MISAGO_ATTACHMENT_IMAGE_SIZE_LIMIT = (500, 500)
# Length of secret used for attachments url tokens and filenames
MISAGO_ATTACHMENT_SECRET_LENGTH = 64
# Names of files served when user requests file that doesn't exist or is unavailable
MISAGO_ATTACHMENT_403_IMAGE = "misago/img/attachment-403.png"
MISAGO_ATTACHMENT_404_IMAGE = "misago/img/attachment-404.png"
# Available Moment.js locales
MISAGO_MOMENT_JS_LOCALES = [
"af",
"ar-ma",
"ar-sa",
"ar-tn",
"ar",
"az",
"be",
"bg",
"bn",
"bo",
"br",
"bs",
"ca",
"cs",
"cv",
"cy",
"da",
"de-at",
"de",
"el",
"en-au",
"en-ca",
"en-gb",
"eo",
"es",
"et",
"eu",
"fa",
"fi",
"fo",
"fr-ca",
"fr",
"fy",
"gl",
"he",
"hi",
"hr",
"hu",
"hy-am",
"id",
"is",
"it",
"ja",
"ka",
"km",
"ko",
"lb",
"lt",
"lv",
"mk",
"ml",
"mr",
"ms-my",
"my",
"nb",
"ne",
"nl",
"nn",
"pl",
"pt-br",
"pt",
"ro",
"ru",
"sk",
"sl",
"sq",
"sr-cyrl",
"sr",
"sv",
"ta",
"th",
"tl-ph",
"tr",
"tzm-latn",
"tzm",
"uk",
"uz",
"vi",
"zh-cn",
"zh-hans",
"zh-tw",
]
| 6,456
|
Python
|
.py
| 194
| 29.458763
| 92
| 0.736221
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,458
|
__init__.py
|
rafalp_Misago/misago/conf/__init__.py
|
from .staticsettings import StaticSettings
SETTINGS_CACHE = "settings"
settings = StaticSettings()
| 101
|
Python
|
.py
| 3
| 32
| 42
| 0.84375
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,459
|
staticsettings.py
|
rafalp_Misago/misago/conf/staticsettings.py
|
from django.conf import settings
from . import defaults
class StaticSettings:
def __getattr__(self, name):
try:
return getattr(settings, name)
except AttributeError:
pass
try:
return getattr(defaults, name)
except AttributeError:
pass
raise AttributeError("%s setting is not defined" % name)
| 389
|
Python
|
.py
| 13
| 21.461538
| 64
| 0.619946
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,460
|
hydrators.py
|
rafalp_Misago/misago/conf/hydrators.py
|
# fixme: rename this module to serialize
def hydrate_string(dry_value):
return str(dry_value) if dry_value else ""
def dehydrate_string(wet_value):
return str(wet_value)
def hydrate_bool(dry_value):
return dry_value == "True"
def dehydrate_bool(wet_value):
return "True" if wet_value else "False"
def hydrate_int(dry_value):
return int(dry_value or 0)
def dehydrate_int(wet_value):
return str(wet_value or 0)
def hydrate_list(dry_value):
if dry_value:
return [x for x in dry_value.split(",") if x]
return []
def dehydrate_list(wet_value):
return ",".join(wet_value) if wet_value else ""
def noop(value):
return value
VALUE_HYDRATORS = {
"string": (hydrate_string, dehydrate_string),
"bool": (hydrate_bool, dehydrate_bool),
"int": (hydrate_int, dehydrate_int),
"list": (hydrate_list, dehydrate_list),
"image": (noop, noop),
}
def hydrate_value(python_type, dry_value):
try:
value_hydrator = VALUE_HYDRATORS[python_type][0]
except KeyError:
raise ValueError("%s type is not hydrateable" % python_type)
return value_hydrator(dry_value)
def dehydrate_value(python_type, wet_value):
try:
value_dehydrator = VALUE_HYDRATORS[python_type][1]
except KeyError:
raise ValueError("%s type is not dehydrateable" % python_type)
return value_dehydrator(wet_value)
| 1,397
|
Python
|
.py
| 40
| 30.225
| 70
| 0.693923
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,461
|
middleware.py
|
rafalp_Misago/misago/conf/middleware.py
|
from django.utils.functional import SimpleLazyObject
from .dynamicsettings import DynamicSettings
def dynamic_settings_middleware(get_response):
"""Sets request.settings attribute with DynamicSettings."""
def middleware(request):
def get_dynamic_settings():
return DynamicSettings(request.cache_versions)
request.settings = SimpleLazyObject(get_dynamic_settings)
return get_response(request)
return middleware
| 464
|
Python
|
.py
| 10
| 40
| 65
| 0.767857
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,462
|
shortcuts.py
|
rafalp_Misago/misago/conf/shortcuts.py
|
from ..cache.versions import get_cache_versions
from .dynamicsettings import DynamicSettings
def get_dynamic_settings():
cache_versions = get_cache_versions()
return DynamicSettings(cache_versions)
| 208
|
Python
|
.py
| 5
| 38.6
| 47
| 0.810945
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,463
|
0004_create_settings.py
|
rafalp_Misago/misago/conf/migrations/0004_create_settings.py
|
# Generated by Django 2.2.1 on 2019-05-19 00:16
from django.conf import settings
from django.db import migrations
from ..hydrators import dehydrate_value
default_settings = [
{"setting": "account_activation", "dry_value": "none", "is_public": True},
{"setting": "allow_custom_avatars", "python_type": "bool", "wet_value": True},
{
"setting": "avatar_upload_limit",
"python_type": "int",
"wet_value": 1536,
"is_public": True,
},
{"setting": "attachment_403_image", "python_type": "image"},
{"setting": "attachment_404_image", "python_type": "image"},
{"setting": "blank_avatar", "python_type": "image"},
{"setting": "captcha_type", "dry_value": "no", "is_public": True},
{"setting": "default_avatar", "dry_value": "gravatar"},
{"setting": "default_gravatar_fallback", "dry_value": "dynamic"},
{"setting": "unused_attachments_lifetime", "python_type": "int", "wet_value": 24},
{"setting": "email_footer"},
{
"setting": "forum_address",
"dry_value": getattr(settings, "MISAGO_ADDRESS", None),
"is_public": True,
},
{"setting": "forum_footnote", "is_public": True},
{"setting": "forum_name", "dry_value": "Misago", "is_public": True},
{"setting": "google_tracking_id"},
{"setting": "google_site_verification"},
{"setting": "index_header", "is_public": True},
{"setting": "index_meta_description", "is_public": True},
{"setting": "index_title", "is_public": True},
{"setting": "logo", "python_type": "image", "is_public": True},
{"setting": "logo_small", "python_type": "image", "is_public": True},
{"setting": "logo_text", "dry_value": "Misago", "is_public": True},
{"setting": "daily_post_limit", "python_type": "int", "wet_value": 600},
{"setting": "hourly_post_limit", "python_type": "int", "wet_value": 100},
{"setting": "post_attachments_limit", "python_type": "int", "wet_value": 16},
{
"setting": "post_length_max",
"python_type": "int",
"wet_value": 60000,
"is_public": True,
},
{
"setting": "post_length_min",
"python_type": "int",
"wet_value": 5,
"is_public": True,
},
{"setting": "readtracker_cutoff", "python_type": "int", "wet_value": 40},
{"setting": "threads_per_page", "python_type": "int", "wet_value": 26},
{"setting": "posts_per_page", "python_type": "int", "wet_value": 18},
{"setting": "posts_per_page_orphans", "python_type": "int", "wet_value": 6},
{"setting": "events_per_page", "python_type": "int", "wet_value": 20},
{"setting": "og_image", "python_type": "image"},
{
"setting": "og_image_avatar_on_profile",
"python_type": "bool",
"wet_value": False,
},
{"setting": "og_image_avatar_on_thread", "python_type": "bool", "wet_value": False},
{"setting": "qa_answers"},
{"setting": "qa_help_text"},
{"setting": "qa_question"},
{"setting": "recaptcha_secret_key"},
{"setting": "recaptcha_site_key", "is_public": True},
{
"setting": "signature_length_max",
"python_type": "int",
"wet_value": 256,
"is_public": True,
},
{"setting": "subscribe_reply", "dry_value": "watch_email"},
{"setting": "subscribe_start", "dry_value": "watch_email"},
{
"setting": "thread_title_length_max",
"python_type": "int",
"wet_value": 90,
"is_public": True,
},
{
"setting": "thread_title_length_min",
"python_type": "int",
"wet_value": 5,
"is_public": True,
},
{"setting": "username_length_min", "python_type": "int", "wet_value": 3},
{"setting": "username_length_max", "python_type": "int", "wet_value": 14},
{"setting": "anonymous_username", "dry_value": "Deleted"},
{"setting": "enable_stop_forum_spam", "python_type": "bool", "wet_value": False},
{"setting": "stop_forum_spam_confidence", "python_type": "int", "wet_value": 80},
{"setting": "users_per_page", "python_type": "int", "wet_value": 12},
{"setting": "users_per_page_orphans", "python_type": "int", "wet_value": 4},
{"setting": "allow_data_downloads", "python_type": "bool", "wet_value": True},
{"setting": "data_downloads_expiration", "python_type": "int", "wet_value": 48},
{"setting": "allow_delete_own_account", "python_type": "bool", "wet_value": False},
{"setting": "top_posters_ranking_length", "python_type": "int", "wet_value": 30},
{"setting": "top_posters_ranking_size", "python_type": "int", "wet_value": 50},
{"setting": "new_inactive_accounts_delete", "python_type": "int", "wet_value": 0},
{"setting": "ip_storage_time", "python_type": "int", "wet_value": 90},
]
removed_settings = ["forum_branding_display", "forum_branding_text"]
def create_settings(apps, _):
# This migration builds list of existing settings, and then
# creates settings not already in the database
Setting = apps.get_model("misago_conf", "Setting")
# Update existing settings and add new ones
existing_settings = list(Setting.objects.values_list("setting", flat=True))
for setting in default_settings:
if setting["setting"] in existing_settings:
continue # skip already existing setting (migration on existing forum)
data = setting.copy()
if "python_type" in data and "wet_value" in data:
data["dry_value"] = dehydrate_value(
data["python_type"], data.pop("wet_value")
)
Setting.objects.create(**data)
# Delete deprecated settings
Setting.objects.filter(setting__in=removed_settings).delete()
class Migration(migrations.Migration):
dependencies = [
("misago_conf", "0003_simplify_models"),
("misago_core", "0003_delete_cacheversion"),
("misago_threads", "0012_set_dj_partial_indexes"),
("misago_users", "0020_set_dj_partial_indexes"),
]
operations = [migrations.RunPython(create_settings)]
| 6,018
|
Python
|
.py
| 129
| 40.372093
| 88
| 0.600408
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,464
|
0005_add_sso_settings.py
|
rafalp_Misago/misago/conf/migrations/0005_add_sso_settings.py
|
# Generated by Django 2.2.1 on 2019-05-19 00:16
from django.db import migrations
from ..hydrators import dehydrate_value
settings = [
{
"setting": "enable_sso",
"python_type": "bool",
"wet_value": False,
"is_public": True,
},
{"setting": "sso_public_key", "is_public": False},
{"setting": "sso_private_key", "is_public": False},
{"setting": "sso_url", "is_public": False},
]
def create_settings(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
for setting in settings:
data = setting.copy()
if "python_type" in data and "wet_value" in data:
data["dry_value"] = dehydrate_value(
data["python_type"], data.pop("wet_value")
)
Setting.objects.create(**data)
class Migration(migrations.Migration):
dependencies = [("misago_conf", "0004_create_settings")]
operations = [migrations.RunPython(create_settings)]
| 956
|
Python
|
.py
| 26
| 30.346154
| 60
| 0.619978
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,465
|
0009_delete_oauth2_access_token_method.py
|
rafalp_Misago/misago/conf/migrations/0009_delete_oauth2_access_token_method.py
|
from django.db import migrations
def delete_oauth2_token_method_setting(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
Setting.objects.filter(setting="oauth2_token_method").delete()
class Migration(migrations.Migration):
dependencies = [
("misago_conf", "0008_delete_sso_settings"),
]
operations = [migrations.RunPython(delete_oauth2_token_method_setting)]
| 404
|
Python
|
.py
| 9
| 40.222222
| 75
| 0.733333
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,466
|
0006_add_index_message.py
|
rafalp_Misago/misago/conf/migrations/0006_add_index_message.py
|
# Generated by Django 3.2.15 on 2022-12-29 19:55
from django.db import migrations
def create_index_message_setting(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
Setting.objects.create(setting="index_message", is_public=False)
class Migration(migrations.Migration):
dependencies = [
("misago_conf", "0005_add_sso_settings"),
]
operations = [migrations.RunPython(create_index_message_setting)]
| 441
|
Python
|
.py
| 10
| 39.7
| 69
| 0.729412
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,467
|
0012_add_oauth2_pkce_settings.py
|
rafalp_Misago/misago/conf/migrations/0012_add_oauth2_pkce_settings.py
|
# Generated by Django 4.2.8 on 2024-01-27 12:54
from django.db import migrations
from misago.conf.hydrators import dehydrate_value
settings = [
{
"setting": "oauth2_enable_pkce",
"python_type": "bool",
"wet_value": False,
"is_public": False,
},
{
"setting": "oauth2_pkce_code_challenge_method",
"dry_value": "S256",
"is_public": False,
},
]
def create_settings(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
for setting in settings:
data = setting.copy()
if "python_type" in data and "wet_value" in data:
data["dry_value"] = dehydrate_value(
data["python_type"], data.pop("wet_value")
)
Setting.objects.create(**data)
def remove_settings(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
settings_to_delete = [setting["setting"] for setting in settings]
Setting.objects.filter(setting__in=settings_to_delete).delete()
class Migration(migrations.Migration):
dependencies = [
("misago_conf", "0011_add_notifications_settings"),
]
operations = [migrations.RunPython(create_settings, remove_settings)]
| 1,210
|
Python
|
.py
| 34
| 29.088235
| 73
| 0.636052
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,468
|
0008_delete_sso_settings.py
|
rafalp_Misago/misago/conf/migrations/0008_delete_sso_settings.py
|
# Generated by Django 3.2.15 on 2023-01-04 12:37
from django.db import migrations
settings = (
"enable_sso",
"sso_public_key",
"sso_private_key",
"sso_url",
)
def delete_sso_settings(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
Setting.objects.filter(setting__in=settings).delete()
class Migration(migrations.Migration):
dependencies = [
("misago_conf", "0007_add_oauth2_settings"),
]
operations = [migrations.RunPython(delete_sso_settings)]
| 509
|
Python
|
.py
| 16
| 27.625
| 60
| 0.691358
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,469
|
0003_simplify_models.py
|
rafalp_Misago/misago/conf/migrations/0003_simplify_models.py
|
# Generated by Django 2.2.1 on 2019-05-19 00:08
from django.db import migrations, models
from django.db.models import F
def set_default_dry_value(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
Setting.objects.filter(dry_value__isnull=True, default_value__isnull=False).update(
dry_value=F("default_value")
)
class Migration(migrations.Migration):
dependencies = [("misago_conf", "0002_cache_version")]
operations = [
migrations.RemoveField(model_name="setting", name="description"),
migrations.RemoveField(model_name="setting", name="field_extra"),
migrations.RemoveField(model_name="setting", name="form_field"),
migrations.RemoveField(model_name="setting", name="group"),
migrations.RemoveField(model_name="setting", name="legend"),
migrations.RemoveField(model_name="setting", name="name"),
migrations.RemoveField(model_name="setting", name="order"),
migrations.RunPython(set_default_dry_value),
migrations.RemoveField(model_name="setting", name="default_value"),
migrations.DeleteModel(name="SettingsGroup"),
migrations.AddField(
model_name="setting",
name="image",
field=models.ImageField(
blank=True,
null=True,
upload_to="conf",
height_field="image_height",
width_field="image_width",
),
),
migrations.AddField(
model_name="setting",
name="image_size",
field=models.PositiveIntegerField(null=True, blank=True),
),
migrations.AddField(
model_name="setting",
name="image_width",
field=models.PositiveIntegerField(null=True, blank=True),
),
migrations.AddField(
model_name="setting",
name="image_height",
field=models.PositiveIntegerField(null=True, blank=True),
),
]
| 2,004
|
Python
|
.py
| 48
| 32.041667
| 87
| 0.621026
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,470
|
0001_initial.py
|
rafalp_Misago/misago/conf/migrations/0001_initial.py
|
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="Setting",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("setting", models.CharField(unique=True, max_length=255)),
("name", models.CharField(max_length=255)),
("description", models.TextField(null=True, blank=True)),
("legend", models.CharField(max_length=255, null=True, blank=True)),
("order", models.IntegerField(default=0, db_index=True)),
("dry_value", models.TextField(null=True, blank=True)),
("default_value", models.TextField(null=True, blank=True)),
("python_type", models.CharField(default="string", max_length=255)),
("is_public", models.BooleanField(default=False)),
("is_lazy", models.BooleanField(default=False)),
("form_field", models.CharField(default="text", max_length=255)),
("field_extra", models.JSONField()),
],
options={},
bases=(models.Model,),
),
migrations.CreateModel(
name="SettingsGroup",
fields=[
(
"id",
models.AutoField(
verbose_name="ID",
serialize=False,
auto_created=True,
primary_key=True,
),
),
("key", models.CharField(unique=True, max_length=255)),
("name", models.CharField(max_length=255)),
("description", models.TextField(null=True, blank=True)),
],
options={},
bases=(models.Model,),
),
migrations.AddField(
model_name="setting",
name="group",
field=models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="misago_conf.SettingsGroup",
to_field="id",
),
preserve_default=True,
),
]
| 2,509
|
Python
|
.py
| 64
| 23.953125
| 84
| 0.475215
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,471
|
0011_add_notifications_settings.py
|
rafalp_Misago/misago/conf/migrations/0011_add_notifications_settings.py
|
# Generated by Django 3.2.15 on 2023-04-02 17:57
from django.db import migrations
from ...notifications.threads import ThreadNotifications
from ..hydrators import dehydrate_value
settings = [
{
"setting": "watch_started_threads",
"python_type": "int",
"dry_value": ThreadNotifications.SITE_AND_EMAIL,
"is_public": False,
},
{
"setting": "watch_replied_threads",
"python_type": "int",
"dry_value": ThreadNotifications.SITE_AND_EMAIL,
"is_public": False,
},
{
"setting": "watch_new_private_threads_by_followed",
"python_type": "int",
"dry_value": ThreadNotifications.SITE_AND_EMAIL,
"is_public": False,
},
{
"setting": "watch_new_private_threads_by_other_users",
"python_type": "int",
"dry_value": ThreadNotifications.SITE_AND_EMAIL,
"is_public": False,
},
{
"setting": "notify_new_private_threads_by_followed",
"python_type": "int",
"dry_value": ThreadNotifications.SITE_AND_EMAIL,
"is_public": False,
},
{
"setting": "notify_new_private_threads_by_other_users",
"python_type": "int",
"dry_value": ThreadNotifications.SITE_AND_EMAIL,
"is_public": False,
},
{
"setting": "delete_notifications_older_than",
"python_type": "int",
"dry_value": 60,
},
]
def create_settings(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
for setting in settings:
data = setting.copy()
if "python_type" in data and "dry_value" in data:
data["dry_value"] = dehydrate_value(data["python_type"], data["dry_value"])
Setting.objects.create(**setting)
def delete_settings(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
Setting.objects.filter(
setting__in=[setting["setting"] for setting in settings]
).delete()
class Migration(migrations.Migration):
dependencies = [
("misago_conf", "0010_add_admin_link_setting"),
]
operations = [
migrations.RunPython(create_settings, delete_settings),
]
| 2,168
|
Python
|
.py
| 66
| 26.090909
| 87
| 0.613397
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,472
|
0007_add_oauth2_settings.py
|
rafalp_Misago/misago/conf/migrations/0007_add_oauth2_settings.py
|
# Generated by Django 3.2.15 on 2023-01-04 12:36
from django.db import migrations
from ..hydrators import dehydrate_value
settings = [
{
"setting": "enable_oauth2_client",
"python_type": "bool",
"wet_value": False,
"is_public": True,
},
{"setting": "oauth2_provider", "is_public": True},
{"setting": "oauth2_client_id", "is_public": False},
{"setting": "oauth2_client_secret", "is_public": False},
{"setting": "oauth2_scopes", "is_public": False},
{"setting": "oauth2_login_url", "is_public": False},
{"setting": "oauth2_token_url", "is_public": False},
{"setting": "oauth2_token_method", "dry_value": "POST", "is_public": False},
{"setting": "oauth2_token_extra_headers", "is_public": False},
{
"setting": "oauth2_json_token_path",
"dry_value": "access_token",
"is_public": False,
},
{"setting": "oauth2_user_url", "is_public": False},
{"setting": "oauth2_user_method", "dry_value": "GET", "is_public": False},
{
"setting": "oauth2_user_token_location",
"dry_value": "QUERY",
"is_public": False,
},
{
"setting": "oauth2_user_token_name",
"dry_value": "access_token",
"is_public": False,
},
{"setting": "oauth2_user_extra_headers", "is_public": False},
{
"setting": "oauth2_send_welcome_email",
"python_type": "bool",
"wet_value": False,
"is_public": False,
},
{"setting": "oauth2_json_id_path", "dry_value": "id", "is_public": False},
{"setting": "oauth2_json_name_path", "dry_value": "name", "is_public": False},
{"setting": "oauth2_json_email_path", "dry_value": "email", "is_public": False},
{"setting": "oauth2_json_avatar_path", "is_public": False},
]
def create_settings(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
for setting in settings:
data = setting.copy()
if "python_type" in data and "wet_value" in data:
data["dry_value"] = dehydrate_value(
data["python_type"], data.pop("wet_value")
)
Setting.objects.create(**data)
class Migration(migrations.Migration):
dependencies = [
("misago_conf", "0006_add_index_message"),
]
operations = [migrations.RunPython(create_settings)]
| 2,340
|
Python
|
.py
| 61
| 31.836066
| 84
| 0.589868
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,473
|
0002_cache_version.py
|
rafalp_Misago/misago/conf/migrations/0002_cache_version.py
|
# Generated by Django 1.11.16 on 2018-12-02 15:54
from django.db import migrations
from .. import SETTINGS_CACHE
from ...cache.operations import StartCacheVersioning
class Migration(migrations.Migration):
dependencies = [("misago_conf", "0001_initial"), ("misago_cache", "0001_initial")]
operations = [StartCacheVersioning(SETTINGS_CACHE)]
| 352
|
Python
|
.py
| 7
| 47.571429
| 86
| 0.771261
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,474
|
0014_add_threads_lists_settings.py
|
rafalp_Misago/misago/conf/migrations/0014_add_threads_lists_settings.py
|
# Generated by Django 4.2.10 on 2024-07-03 17:12
from django.db import migrations
from ...threads.enums import ThreadsListsPolling
settings = {
"threads_list_item_categories_component": {
"dry_value": "breadcrumbs",
},
"threads_list_categories_component": {
"dry_value": "dropdown",
},
"threads_lists_polling": {
"python_type": "int",
"dry_value": ThreadsListsPolling.ENABLED.value,
},
}
def create_setting(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
for setting, data in settings.items():
Setting.objects.create(setting=setting, **data)
def remove_setting(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
Setting.objects.filter(setting__in=settings).delete()
class Migration(migrations.Migration):
dependencies = [
("misago_conf", "0013_add_index_view_setting"),
]
operations = [migrations.RunPython(create_setting, remove_setting)]
| 974
|
Python
|
.py
| 27
| 30.962963
| 71
| 0.680556
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,475
|
0010_add_admin_link_setting.py
|
rafalp_Misago/misago/conf/migrations/0010_add_admin_link_setting.py
|
# Generated by Django 3.2.15 on 2023-04-04 18:29
from django.db import migrations
from ..hydrators import dehydrate_value
setting = {
"setting": "show_admin_panel_link_in_ui",
"python_type": "bool",
"wet_value": True,
"is_public": False,
}
def create_settings(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
Setting.objects.create(
setting=setting["setting"],
python_type=setting["python_type"],
dry_value=dehydrate_value(setting["python_type"], setting["wet_value"]),
is_public=setting["is_public"],
)
def delete_settings(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
Setting.objects.filter(setting=setting["setting"]).delete()
class Migration(migrations.Migration):
dependencies = [
("misago_conf", "0009_delete_oauth2_access_token_method"),
]
operations = [migrations.RunPython(create_settings, delete_settings)]
| 944
|
Python
|
.py
| 25
| 32.76
| 80
| 0.685777
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,476
|
0013_add_index_view_setting.py
|
rafalp_Misago/misago/conf/migrations/0013_add_index_view_setting.py
|
# Generated by Django 4.2.10 on 2024-06-20 21:30
from django.conf import settings
from django.db import migrations
THREADS_ON_INDEX = getattr(settings, "MISAGO_THREADS_ON_INDEX", True)
def create_setting(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
Setting.objects.create(
setting="index_view",
dry_value="threads" if THREADS_ON_INDEX else "categories",
is_public=True,
)
def remove_setting(apps, _):
Setting = apps.get_model("misago_conf", "Setting")
Setting.objects.filter(setting="index_view").delete()
class Migration(migrations.Migration):
dependencies = [
("misago_conf", "0012_add_oauth2_pkce_settings"),
]
operations = [migrations.RunPython(create_setting, remove_setting)]
| 772
|
Python
|
.py
| 19
| 35.736842
| 71
| 0.707941
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,477
|
conftest.py
|
rafalp_Misago/misago/conf/tests/conftest.py
|
import pytest
from ..models import Setting
@pytest.fixture
def lazy_setting(db):
return Setting.objects.create(
setting="lazy_setting", dry_value="Hello", is_lazy=True
)
@pytest.fixture
def lazy_setting_without_value(db):
return Setting.objects.create(setting="lazy_setting", dry_value="", is_lazy=True)
@pytest.fixture
def private_setting(db):
return Setting.objects.create(
setting="private_setting", dry_value="Hello", is_public=False
)
@pytest.fixture
def public_setting(db):
return Setting.objects.create(
setting="public_setting", dry_value="Hello", is_public=True
)
| 634
|
Python
|
.py
| 20
| 27.65
| 85
| 0.728926
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,478
|
test_getting_static_settings_values.py
|
rafalp_Misago/misago/conf/tests/test_getting_static_settings_values.py
|
import pytest
from django.test import override_settings
def test_accessing_attr_returns_setting_value_defined_in_settings_file(settings):
assert settings.STATIC_URL
def test_accessing_attr_returns_setting_value_defined_in_misago_defaults_file(settings):
assert settings.MISAGO_MOMENT_JS_LOCALES
def test_setting_value_can_be_overridden_using_django_util(settings):
with override_settings(STATIC_URL="/test/"):
assert settings.STATIC_URL == "/test/"
def test_default_setting_value_can_be_overridden_using_django_util(settings):
with override_settings(MISAGO_MOMENT_JS_LOCALES="test"):
assert settings.MISAGO_MOMENT_JS_LOCALES == "test"
def test_undefined_setting_value_can_be_overridden_using_django_util(settings):
with override_settings(UNDEFINED_SETTING="test"):
assert settings.UNDEFINED_SETTING == "test"
def test_accessing_attr_for_undefined_setting_raises_attribute_error(settings):
with pytest.raises(AttributeError):
assert settings.UNDEFINED_SETTING
| 1,027
|
Python
|
.py
| 18
| 52.277778
| 88
| 0.782347
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,479
|
test_hydrators.py
|
rafalp_Misago/misago/conf/tests/test_hydrators.py
|
from unittest.mock import Mock
import pytest
from ..hydrators import dehydrate_value, hydrate_value
def test_string_value_can_be_dehydrated_and_hydrated_back():
assert hydrate_value("string", dehydrate_value("string", "test")) == "test"
def test_int_value_is_dehydrated_to_string():
assert dehydrate_value("string", 123) == "123"
def test_empty_string_value_is_hydrated_to_empty_string():
assert hydrate_value("string", None) == ""
def test_bool_false_value_can_be_dehydrated_and_hydrated_back():
assert hydrate_value("bool", dehydrate_value("bool", False)) is False
def test_bool_true_value_can_be_dehydrated_and_hydrated_back():
assert hydrate_value("bool", dehydrate_value("bool", True)) is True
def test_bool_none_value_can_be_dehydrated_and_hydrated_back_to_false():
assert hydrate_value("bool", dehydrate_value("bool", None)) is False
def test_int_value_can_be_dehydrated_and_hydrated_back():
assert hydrate_value("int", dehydrate_value("int", 123)) == 123
def test_empty_int_value_can_be_dehydrated_and_hydrated_back():
assert hydrate_value("int", dehydrate_value("int", 0)) == 0
def test_none_int_value_is_dehydrated_to_zero_string():
assert dehydrate_value("int", None) == "0"
def test_none_int_value_is_hydrated_to_zero():
assert hydrate_value("int", None) == 0
def test_empty_int_value_is_hydrated_to_zero():
assert hydrate_value("int", "") == 0
def test_list_value_can_be_dehydrated_and_hydrated_back():
assert hydrate_value("list", dehydrate_value("list", ["a", "b"])) == ["a", "b"]
def test_single_item_list_value_can_be_dehydrated_and_hydrated_back():
assert hydrate_value("list", dehydrate_value("list", ["a"])) == ["a"]
def test_empty_list_value_can_be_dehydrated_and_hydrated_back():
assert hydrate_value("list", dehydrate_value("list", [])) == []
def test_none_list_value_can_be_dehydrated_and_hydrated_to_empty_list():
assert hydrate_value("list", dehydrate_value("list", None)) == []
def test_empty_list_value_is_hydrated_to_empty_list():
assert hydrate_value("list", "") == []
def test_none_list_value_is_hydrated_to_empty_list():
assert hydrate_value("list", None) == []
def test_none_list_value_is_dehydrated_to_empty_string():
assert dehydrate_value("list", None) == ""
def test_image_value_hydration_is_noop():
image = Mock()
assert hydrate_value("image", image) is image
def test_image_value_dehydration_is_noop():
image = Mock()
assert dehydrate_value("image", image) is image
def test_value_error_is_raised_on_unsupported_type_dehydration():
with pytest.raises(ValueError):
dehydrate_value("unsupported", None)
def test_value_error_is_raised_on_unsupported_type_hydration():
with pytest.raises(ValueError):
hydrate_value("unsupported", None)
| 2,829
|
Python
|
.py
| 51
| 51.372549
| 83
| 0.715959
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,480
|
test_context_processors.py
|
rafalp_Misago/misago/conf/tests/test_context_processors.py
|
from unittest.mock import Mock
from ..context_processors import conf
from ..test import override_dynamic_settings
def test_request_settings_are_included_in_template_context(db, dynamic_settings):
mock_request = Mock(settings=dynamic_settings)
context_settings = conf(mock_request)["settings"]
assert context_settings == mock_request.settings
def test_settings_are_included_in_frontend_context(db, client):
response = client.get("/")
assert response.status_code == 200
assert '"SETTINGS": {"' in response.content.decode("utf-8")
def test_admin_panel_link_is_included_in_frontend_context_for_admins(admin_client):
response = admin_client.get("/")
assert response.status_code == 200
assert '"ADMIN_URL": "' in response.content.decode("utf-8")
@override_dynamic_settings(show_admin_panel_link_in_ui=False)
def test_admin_panel_link_is_excluded_from_frontend_context_for_admins_if_disabled(
admin_client,
):
response = admin_client.get("/")
assert response.status_code == 200
assert '"ADMIN_URL": "' not in response.content.decode("utf-8")
def test_admin_panel_link_is_excluded_from_frontend_context_for_staff_users(
staff_client,
):
response = staff_client.get("/")
assert response.status_code == 200
assert '"ADMIN_URL": "' not in response.content.decode("utf-8")
def test_admin_panel_link_is_excluded_from_frontend_context_for_users(user_client):
response = user_client.get("/")
assert response.status_code == 200
assert '"ADMIN_URL": "' not in response.content.decode("utf-8")
def test_admin_panel_link_is_excluded_from_frontend_context_for_guests(db, client):
response = client.get("/")
assert response.status_code == 200
assert '"ADMIN_URL": "' not in response.content.decode("utf-8")
| 1,793
|
Python
|
.py
| 36
| 45.833333
| 83
| 0.732491
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,481
|
test_getting_dynamic_settings_values.py
|
rafalp_Misago/misago/conf/tests/test_getting_dynamic_settings_values.py
|
import pytest
from .. import SETTINGS_CACHE
from ..dynamicsettings import DynamicSettings
def test_settings_are_loaded_from_database_if_cache_is_not_available(
db, mocker, cache_versions, django_assert_num_queries
):
mocker.patch("django.core.cache.cache.get", return_value=None)
with django_assert_num_queries(1):
DynamicSettings(cache_versions)
def test_settings_are_loaded_from_cache_if_it_is_set(
db, mocker, cache_versions, django_assert_num_queries
):
cache_get = mocker.patch("django.core.cache.cache.get", return_value={})
with django_assert_num_queries(0):
DynamicSettings(cache_versions)
cache_get.assert_called_once()
def test_settings_cache_is_set_if_none_exists(db, mocker, cache_versions):
cache_set = mocker.patch("django.core.cache.cache.set")
mocker.patch("django.core.cache.cache.get", return_value=None)
DynamicSettings(cache_versions)
cache_set.assert_called_once()
def test_settings_cache_is_not_set_if_it_already_exists(
db, mocker, cache_versions, django_assert_num_queries
):
cache_set = mocker.patch("django.core.cache.cache.set")
mocker.patch("django.core.cache.cache.get", return_value={})
with django_assert_num_queries(0):
DynamicSettings(cache_versions)
cache_set.assert_not_called()
def test_settings_cache_key_includes_cache_name_and_version(db, mocker, cache_versions):
cache_set = mocker.patch("django.core.cache.cache.set")
mocker.patch("django.core.cache.cache.get", return_value=None)
DynamicSettings(cache_versions)
cache_key = cache_set.call_args[0][0]
assert SETTINGS_CACHE in cache_key
assert cache_versions[SETTINGS_CACHE] in cache_key
def test_accessing_attr_returns_setting_value(db, cache_versions):
settings = DynamicSettings(cache_versions)
assert settings.forum_name == "Misago"
def test_accessing_attr_for_undefined_setting_raises_attribute_error(
db, cache_versions
):
settings = DynamicSettings(cache_versions)
with pytest.raises(AttributeError):
settings.not_existing # pylint: disable=pointless-statement
def test_accessing_attr_for_lazy_setting_with_value_returns_true(
cache_versions, lazy_setting
):
settings = DynamicSettings(cache_versions)
assert settings.lazy_setting is True
def test_lazy_setting_getter_for_lazy_setting_with_value_returns_real_value(
cache_versions, lazy_setting
):
settings = DynamicSettings(cache_versions)
assert settings.get_lazy_setting_value("lazy_setting") == lazy_setting.value
def test_lazy_setting_getter_for_lazy_setting_makes_db_query(
cache_versions, lazy_setting, django_assert_num_queries
):
settings = DynamicSettings(cache_versions)
with django_assert_num_queries(1):
settings.get_lazy_setting_value("lazy_setting")
def test_accessing_attr_for_lazy_setting_without_value_returns_none(
cache_versions, lazy_setting_without_value
):
settings = DynamicSettings(cache_versions)
assert settings.lazy_setting is None
def test_lazy_setting_getter_for_lazy_setting_is_reusing_query_result(
cache_versions, lazy_setting, django_assert_num_queries
):
settings = DynamicSettings(cache_versions)
settings.get_lazy_setting_value("lazy_setting")
with django_assert_num_queries(0):
settings.get_lazy_setting_value("lazy_setting")
def test_lazy_setting_getter_for_undefined_setting_raises_attribute_error(
db, cache_versions
):
settings = DynamicSettings(cache_versions)
with pytest.raises(AttributeError):
settings.get_lazy_setting_value("undefined")
def test_lazy_setting_getter_for_not_lazy_setting_raises_value_error(
db, cache_versions
):
settings = DynamicSettings(cache_versions)
with pytest.raises(ValueError):
settings.get_lazy_setting_value("forum_name")
def test_public_settings_getter_returns_dict_with_public_settings(
cache_versions, public_setting
):
settings = DynamicSettings(cache_versions)
public_settings = settings.get_public_settings()
assert public_settings["public_setting"] == "Hello"
def test_public_settings_getter_excludes_private_settings_from_dict(
cache_versions, private_setting
):
settings = DynamicSettings(cache_versions)
public_settings = settings.get_public_settings()
assert "private_setting" not in public_settings
def test_getter_returns_setting_dict(cache_versions, public_setting):
settings = DynamicSettings(cache_versions)
assert settings.get(public_setting.setting) == {
"value": public_setting.value,
"is_lazy": public_setting.is_lazy,
"is_public": public_setting.is_public,
"width": public_setting.image_width,
"height": public_setting.image_height,
}
| 4,760
|
Python
|
.py
| 106
| 40.320755
| 88
| 0.754223
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,482
|
test_dynamic_settings_middleware.py
|
rafalp_Misago/misago/conf/tests/test_dynamic_settings_middleware.py
|
from unittest.mock import Mock
import pytest
from django.utils.functional import SimpleLazyObject
from ..middleware import dynamic_settings_middleware
@pytest.fixture
def get_response():
return Mock()
class PlainRequest:
pass
@pytest.fixture
def plain_request():
return PlainRequest()
def test_middleware_sets_attr_on_request(db, get_response, plain_request):
middleware = dynamic_settings_middleware(get_response)
middleware(plain_request)
assert hasattr(plain_request, "settings")
def test_attr_set_by_middleware_on_request_is_lazy_object(
db, get_response, plain_request
):
middleware = dynamic_settings_middleware(get_response)
middleware(plain_request)
assert isinstance(plain_request.settings, SimpleLazyObject)
def test_middleware_calls_get_response(db, get_response, plain_request):
middleware = dynamic_settings_middleware(get_response)
middleware(plain_request)
get_response.assert_called_once()
def test_middleware_is_not_reading_from_db(
db, get_response, plain_request, django_assert_num_queries
):
with django_assert_num_queries(0):
middleware = dynamic_settings_middleware(get_response)
middleware(plain_request)
def test_middleware_is_not_reading_from_cache(db, mocker, get_response, plain_request):
cache_get = mocker.patch("django.core.cache.cache.get")
middleware = dynamic_settings_middleware(get_response)
middleware(plain_request)
cache_get.assert_not_called()
| 1,493
|
Python
|
.py
| 37
| 36.378378
| 87
| 0.777469
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,483
|
test_overridding_dynamic_settings.py
|
rafalp_Misago/misago/conf/tests/test_overridding_dynamic_settings.py
|
from ..dynamicsettings import DynamicSettings
from ..test import override_dynamic_settings
def test_dynamic_setting_can_be_overridden_using_context_manager(dynamic_settings):
assert dynamic_settings.forum_name == "Misago"
with override_dynamic_settings(forum_name="Overrided"):
assert dynamic_settings.forum_name == "Overrided"
assert dynamic_settings.forum_name == "Misago"
def test_dynamic_setting_can_be_overridden_using_decorator(dynamic_settings):
@override_dynamic_settings(forum_name="Overrided")
def decorated_function(settings):
return settings.forum_name
assert dynamic_settings.forum_name == "Misago"
assert decorated_function(dynamic_settings) == "Overrided"
assert dynamic_settings.forum_name == "Misago"
def test_lazy_dynamic_setting_can_be_overridden_using_context_manager(
cache_versions, lazy_setting
):
settings = DynamicSettings(cache_versions)
assert settings.get_lazy_setting_value("lazy_setting") == "Hello"
with override_dynamic_settings(lazy_setting="Overrided"):
assert settings.get_lazy_setting_value("lazy_setting") == "Overrided"
assert settings.get_lazy_setting_value("lazy_setting") == "Hello"
def test_lazy_dynamic_setting_can_be_overridden_using_decorator(
cache_versions, lazy_setting
):
@override_dynamic_settings(lazy_setting="Overrided")
def decorated_function(settings):
return settings.get_lazy_setting_value("lazy_setting")
settings = DynamicSettings(cache_versions)
assert settings.get_lazy_setting_value("lazy_setting") == "Hello"
assert decorated_function(settings) == "Overrided"
assert settings.get_lazy_setting_value("lazy_setting") == "Hello"
| 1,711
|
Python
|
.py
| 32
| 48.65625
| 83
| 0.756741
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,484
|
test_model_value_prop.py
|
rafalp_Misago/misago/conf/tests/test_model_value_prop.py
|
from ..models import Setting
def test_setting_value_is_hydrated_by_getter(db):
setting = Setting(python_type="list", dry_value="lorem,ipsum")
assert setting.value == ["lorem", "ipsum"]
def test_setting_value_is_dehydrated_by_setter(db):
setting = Setting(python_type="list")
setting.value = ["lorem", "ipsum"]
assert setting.dry_value == "lorem,ipsum"
def test_setting_value_is_set_to_none(db):
setting = Setting(python_type="list", dry_value="lorem,ipsum")
setting.value = None
assert setting.dry_value is None
| 550
|
Python
|
.py
| 12
| 41.666667
| 66
| 0.712406
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,485
|
__init__.py
|
rafalp_Misago/misago/conf/admin/__init__.py
|
from django.urls import path
from django.utils.translation import pgettext_lazy
from .views import (
AnalyticsSettingsView,
CaptchaSettingsView,
GeneralSettingsView,
NotificationsSettingsView,
OAuth2SettingsView,
ThreadsSettingsView,
UsersSettingsView,
index,
)
class MisagoAdminExtension:
def register_urlpatterns(self, urlpatterns):
urlpatterns.namespace("settings/", "settings")
urlpatterns.patterns("settings", path("", index, name="index"))
urlpatterns.single_pattern(
"analytics/",
"analytics",
"settings",
AnalyticsSettingsView.as_view(),
)
urlpatterns.single_pattern(
"captcha/", "captcha", "settings", CaptchaSettingsView.as_view()
)
urlpatterns.single_pattern(
"general/", "general", "settings", GeneralSettingsView.as_view()
)
urlpatterns.single_pattern(
"notifications/",
"notifications",
"settings",
NotificationsSettingsView.as_view(),
)
urlpatterns.single_pattern(
"oauth2/", "oauth2", "settings", OAuth2SettingsView.as_view()
)
urlpatterns.single_pattern(
"threads/", "threads", "settings", ThreadsSettingsView.as_view()
)
urlpatterns.single_pattern(
"users/", "users", "settings", UsersSettingsView.as_view()
)
def register_navigation_nodes(self, site):
site.add_node(
name=pgettext_lazy("admin node", "Settings"),
icon="fa fa-cog",
after="themes:index",
namespace="settings",
)
site.add_node(
name=pgettext_lazy("admin node", "General"),
description=pgettext_lazy(
"admin node", "Change forum details like name, description or footer."
),
parent="settings",
namespace="general",
)
site.add_node(
name=pgettext_lazy("admin node", "Users"),
description=pgettext_lazy(
"admin node",
"Customize user accounts default behavior and features availability.",
),
parent="settings",
namespace="users",
after="general:index",
)
site.add_node(
name=pgettext_lazy("admin node", "Captcha"),
description=pgettext_lazy(
"admin node",
"Setup protection against automatic registrations on the site.",
),
parent="settings",
namespace="captcha",
after="users:index",
)
site.add_node(
name=pgettext_lazy("admin node", "Threads"),
description=pgettext_lazy(
"admin node", "Threads, posts, polls and attachments options."
),
parent="settings",
namespace="threads",
after="captcha:index",
)
site.add_node(
name=pgettext_lazy("admin node", "Notifications"),
description=pgettext_lazy(
"admin node",
"Those settings control default notification preferences of new user accounts and storage time of existing notifications.",
),
parent="settings",
namespace="notifications",
after="threads:index",
)
site.add_node(
name=pgettext_lazy("admin node", "OAuth2"),
description=pgettext_lazy(
"admin node",
"Enable OAuth2 client and connect your site to existing auth provider.",
),
parent="settings",
namespace="oauth2",
after="notifications:index",
)
site.add_node(
name=pgettext_lazy("admin node", "Analytics"),
description=pgettext_lazy(
"admin node",
"Enable Google Analytics or setup Google Site Verification.",
),
parent="settings",
namespace="analytics",
after="oauth2:index",
)
| 4,161
|
Python
|
.py
| 117
| 24.384615
| 139
| 0.559822
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,486
|
views.py
|
rafalp_Misago/misago/conf/admin/views.py
|
from django.contrib import messages
from django.shortcuts import redirect
from django.utils.translation import pgettext
from ...admin.views import render
from ...admin.views.generic import AdminView
from ..models import Setting
from .forms import (
AnalyticsSettingsForm,
CaptchaSettingsForm,
GeneralSettingsForm,
NotificationsSettingsForm,
OAuth2SettingsForm,
ThreadsSettingsForm,
UsersSettingsForm,
)
def index(request):
return render(request, "misago/admin/conf/index.html")
class SettingsView(AdminView):
root_link = None # Unused by change config views
template_name = None
form_class = None
def get_template_name(self, request):
return self.template_name
def dispatch(self, request, *args, **kwargs):
settings = self.get_settings(self.form_class.settings)
initial = self.get_initial_form_data(settings)
form = self.form_class(request=request, initial=initial)
if request.method == "POST":
form = self.form_class(
request.POST, request.FILES, request=request, initial=initial
)
if form.is_valid():
form.save(settings)
messages.success(
request, pgettext("admin settings", "Settings have been saved.")
)
return redirect(request.path_info)
return self.render(request, {"form": form, "form_settings": settings})
def get_settings(self, form_settings):
settings = {}
for setting in Setting.objects.filter(setting__in=form_settings):
settings[setting.setting] = setting
if len(settings) != len(form_settings):
not_found_settings = list(
set(settings.keys()).symmetric_difference(set(form_settings))
)
raise ValueError(
"Some of settings defined in form could not be found: %s"
% (", ".join(not_found_settings))
)
return settings
def get_initial_form_data(self, settings):
return {key: setting.value for key, setting in settings.items()}
class AnalyticsSettingsView(SettingsView):
form_class = AnalyticsSettingsForm
template_name = "misago/admin/conf/analytics_settings.html"
class CaptchaSettingsView(SettingsView):
form_class = CaptchaSettingsForm
template_name = "misago/admin/conf/captcha_settings.html"
class GeneralSettingsView(SettingsView):
form_class = GeneralSettingsForm
template_name = "misago/admin/conf/general_settings.html"
class NotificationsSettingsView(SettingsView):
form_class = NotificationsSettingsForm
template_name = "misago/admin/conf/notifications_settings.html"
class OAuth2SettingsView(SettingsView):
form_class = OAuth2SettingsForm
template_name = "misago/admin/conf/oauth2_settings.html"
class ThreadsSettingsView(SettingsView):
form_class = ThreadsSettingsForm
template_name = "misago/admin/conf/threads_settings.html"
class UsersSettingsView(SettingsView):
form_class = UsersSettingsForm
template_name = "misago/admin/conf/users_settings.html"
| 3,150
|
Python
|
.py
| 74
| 35.162162
| 84
| 0.700656
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,487
|
users.py
|
rafalp_Misago/misago/conf/admin/forms/users.py
|
from django import forms
from django.utils.translation import npgettext_lazy, pgettext_lazy
from ....admin.forms import YesNoSwitch
from ....core.validators import validate_image_square
from ....users.validators import validate_username_content
from ... import settings
from .base import SettingsForm
class UsersSettingsForm(SettingsForm):
settings = [
"account_activation",
"allow_custom_avatars",
"avatar_upload_limit",
"default_avatar",
"default_gravatar_fallback",
"blank_avatar",
"signature_length_max",
"subscribe_reply",
"subscribe_start",
"username_length_max",
"username_length_min",
"anonymous_username",
"users_per_page",
"users_per_page_orphans",
"top_posters_ranking_length",
"top_posters_ranking_size",
"allow_data_downloads",
"data_downloads_expiration",
"allow_delete_own_account",
"new_inactive_accounts_delete",
"ip_storage_time",
]
account_activation = forms.ChoiceField(
label=pgettext_lazy(
"admin users settings form", "Require new accounts activation"
),
choices=[
(
"none",
pgettext_lazy(
"admin users account activation field choice",
"No activation required",
),
),
(
"user",
pgettext_lazy(
"admin users account activation field choice",
"Activation token sent to user e-mail",
),
),
(
"admin",
pgettext_lazy(
"admin users account activation field choice",
"Activation by administrator",
),
),
(
"closed",
pgettext_lazy(
"admin users account activation field choice",
"Disable new registrations",
),
),
],
widget=forms.RadioSelect(),
)
new_inactive_accounts_delete = forms.IntegerField(
label=pgettext_lazy(
"admin users settings form",
"Delete new inactive accounts if they weren't activated within this number of days",
),
help_text=pgettext_lazy(
"admin users settings form",
"Enter 0 to never delete inactive new accounts.",
),
min_value=0,
)
username_length_min = forms.IntegerField(
label=pgettext_lazy(
"admin users settings form", "Minimum allowed username length"
),
min_value=2,
max_value=20,
)
username_length_max = forms.IntegerField(
label=pgettext_lazy(
"admin users settings form", "Maximum allowed username length"
),
min_value=2,
max_value=20,
)
allow_custom_avatars = YesNoSwitch(
label=pgettext_lazy("admin users settings form", "Allow custom avatar uploads"),
help_text=pgettext_lazy(
"admin users settings form",
"Turning this option off will forbid forum users from uploading custom avatars.",
),
)
avatar_upload_limit = forms.IntegerField(
label=pgettext_lazy(
"admin users settings form", "Maximum size of uploaded avatar"
),
help_text=pgettext_lazy(
"admin users settings form",
"Enter maximum allowed file size (in KB) for avatar uploads.",
),
min_value=0,
)
default_avatar = forms.ChoiceField(
label=pgettext_lazy("admin users settings form", "Default avatar"),
choices=[
(
"dynamic",
pgettext_lazy(
"admin users default avatar choice",
"Individual",
),
),
(
"gravatar",
pgettext_lazy(
"admin users default avatar choice",
"Gravatar",
),
),
(
"gallery",
pgettext_lazy(
"admin users default avatar choice",
"Random avatar from gallery",
),
),
],
widget=forms.RadioSelect(),
)
default_gravatar_fallback = forms.ChoiceField(
label=pgettext_lazy(
"admin users settings form", "Fallback for default Gravatar"
),
help_text=pgettext_lazy(
"admin users settings form",
"Select which avatar to use when user has no Gravatar associated with their e-mail address.",
),
choices=[
(
"dynamic",
pgettext_lazy("admin users gravatar fallback choice", "Individual"),
),
(
"gallery",
pgettext_lazy(
"admin users gravatar fallback choice", "Random avatar from gallery"
),
),
],
widget=forms.RadioSelect(),
)
blank_avatar = forms.ImageField(
label=pgettext_lazy("admin users settings form", "Blank avatar"),
help_text=pgettext_lazy(
"admin users settings form",
"Blank avatar is displayed in the interface when user's avatar is not available: when user was deleted or is guest. Uploaded image should be a square.",
),
required=False,
)
blank_avatar_delete = forms.BooleanField(
label=pgettext_lazy("admin users settings form", "Delete custom blank avatar"),
required=False,
)
signature_length_max = forms.IntegerField(
label=pgettext_lazy(
"admin users settings form", "Maximum allowed signature length"
),
min_value=10,
max_value=5000,
)
subscribe_start = forms.ChoiceField(
label=pgettext_lazy("admin users settings form", "Started threads"),
choices=[
("no", pgettext_lazy("admin users settings form", "Don't watch")),
(
"watch",
pgettext_lazy(
"admin users default subscription choice",
"Put on watched threads list",
),
),
(
"watch_email",
pgettext_lazy(
"admin users default subscription choice",
"Put on watched threads list and e-mail user when somebody replies",
),
),
],
widget=forms.RadioSelect(),
)
subscribe_reply = forms.ChoiceField(
label=pgettext_lazy("admin users settings form", "Replied threads"),
choices=[
("no", pgettext_lazy("admin users settings form", "Don't watch")),
(
"watch",
pgettext_lazy(
"admin users default subscription choice",
"Put on watched threads list",
),
),
(
"watch_email",
pgettext_lazy(
"admin users default subscription choice",
"Put on watched threads list and e-mail user when somebody replies",
),
),
],
widget=forms.RadioSelect(),
)
users_per_page = forms.IntegerField(
label=pgettext_lazy(
"admin users settings form", "Number of users displayed on a single page"
),
min_value=4,
)
users_per_page_orphans = forms.IntegerField(
label=pgettext_lazy("admin users settings form", "Maximum orphans"),
help_text=pgettext_lazy(
"admin users settings form",
"This setting prevents situations when the last page of a users list contains very few items. If number of users to be displayed on the last page is less or equal to number specified in this setting, those users will instead be appended to the previous page, reducing number of list's pages.",
),
min_value=0,
)
top_posters_ranking_length = forms.IntegerField(
label=pgettext_lazy(
"admin users settings form",
"Maximum age in days of posts that should count to the ranking position",
),
min_value=1,
)
top_posters_ranking_size = forms.IntegerField(
label=pgettext_lazy(
"admin users settings form", "Maximum number of ranked users"
),
min_value=2,
)
allow_data_downloads = YesNoSwitch(
label=pgettext_lazy(
"admin users settings form", "Allow users to download their data"
)
)
data_downloads_expiration = forms.IntegerField(
label=pgettext_lazy(
"admin users settings form",
"Maximum age in hours of data downloads before they expire",
),
help_text=pgettext_lazy(
"admin users settings form",
"Data downloads older than specified will have their files deleted and will be marked as expired.",
),
min_value=1,
)
allow_delete_own_account = YesNoSwitch(
label=pgettext_lazy(
"admin users settings form", "Allow users to delete their own accounts"
)
)
ip_storage_time = forms.IntegerField(
label=pgettext_lazy("admin users settings form", "IP storage time"),
help_text=pgettext_lazy(
"admin users settings form",
"Number of days for which users IP addresses are stored in forum database. Enter zero to store registered IP addresses forever. Deleting user account always deletes the IP addresses associated with it.",
),
min_value=0,
)
anonymous_username = forms.CharField(
label=pgettext_lazy("admin users settings form", "Anonymous username"),
help_text=pgettext_lazy(
"admin users settings form",
"This username is displayed instead of delete user's actual name next to their content.",
),
min_length=1,
max_length=15,
validators=[validate_username_content],
)
def clean_blank_avatar(self):
upload = self.cleaned_data.get("blank_avatar")
if not upload or upload == self.initial.get("blank_avatar"):
return None
validate_image_square(upload.image)
min_size = max(settings.MISAGO_AVATARS_SIZES)
if upload.image.width < min_size:
raise forms.ValidationError(
npgettext_lazy(
"admin users settings form",
"Uploaded image's edge should be at least %(size)s pixel long.",
"Uploaded image's edge should be at least %(size)s pixels long.",
min_size,
)
% {"size": min_size}
)
return upload
def clean(self):
cleaned_data = super().clean()
if cleaned_data.get("users_per_page_orphans") > cleaned_data.get(
"users_per_page"
):
self.add_error(
"users_per_page_orphans",
pgettext_lazy(
"admin users settings form",
"This value must be lower than number of users per page.",
),
)
return cleaned_data
| 11,472
|
Python
|
.py
| 315
| 25.088889
| 305
| 0.556154
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,488
|
general.py
|
rafalp_Misago/misago/conf/admin/forms/general.py
|
from django import forms
from django.utils.translation import pgettext_lazy
from ....admin.forms import YesNoSwitch
from ....forumindex.views import index_views
from .base import SettingsForm
class GeneralSettingsForm(SettingsForm):
settings = [
"forum_name",
"forum_address",
"index_header",
"index_view",
"index_title",
"index_message",
"index_meta_description",
"logo",
"logo_small",
"logo_text",
"og_image",
"og_image_avatar_on_profile",
"og_image_avatar_on_thread",
"forum_footnote",
"email_footer",
"show_admin_panel_link_in_ui",
]
forum_name = forms.CharField(
label=pgettext_lazy("admin general settings form", "Forum name"),
min_length=2,
max_length=255,
)
forum_address = forms.URLField(
label=pgettext_lazy("admin general settings form", "Forum address"),
max_length=255,
)
index_title = forms.CharField(
label=pgettext_lazy("admin general settings form", "Page title"),
max_length=255,
required=False,
)
index_meta_description = forms.CharField(
label=pgettext_lazy("admin general settings form", "Meta Description"),
help_text=pgettext_lazy(
"admin general settings form",
"Short description of your forum that search and social sites may display next to link to your forum's index.",
),
max_length=255,
required=False,
)
index_header = forms.CharField(
label=pgettext_lazy("admin general settings form", "Header text"),
help_text=pgettext_lazy(
"admin general settings form",
"This text will be displayed in page header on forum index.",
),
max_length=255,
required=False,
)
index_message = forms.CharField(
label=pgettext_lazy("admin general settings form", "Header message"),
help_text=pgettext_lazy(
"admin general settings form",
"This message will be displayed in page header on forum index, under the header text.",
),
max_length=2048,
widget=forms.Textarea(attrs={"rows": 3}),
required=False,
)
logo = forms.ImageField(
label=pgettext_lazy("admin general settings form", "Large logo"),
help_text=pgettext_lazy(
"admin general settings form",
"Image that will be displayed in forum navbar instead of a small logo or text.",
),
required=False,
)
logo_delete = forms.BooleanField(
label=pgettext_lazy("admin general settings form", "Delete large logo image"),
required=False,
)
logo_small = forms.ImageField(
label=pgettext_lazy("admin general settings form", "Small logo"),
help_text=pgettext_lazy(
"admin general settings form",
"Image that will be displayed in the forum navbar next to the logo text if a large logo was not uploaded.",
),
required=False,
)
logo_small_delete = forms.BooleanField(
label=pgettext_lazy("admin general settings form", "Delete small logo image"),
required=False,
)
logo_text = forms.CharField(
label=pgettext_lazy("admin general settings form", "Text logo"),
help_text=pgettext_lazy(
"admin general settings form",
"Text displayed in forum navbar. If a small logo image was uploaded, this text will be displayed right next to it. If a large logo was uploaded, it will replace both the small logo and the text.",
),
max_length=255,
required=False,
)
og_image = forms.ImageField(
label=pgettext_lazy("admin general settings form", "Image"),
help_text=pgettext_lazy(
"admin general settings form",
"Custom image that will appear next to links to your forum posted on social sites. Facebook recommends that this image should be 1200 pixels wide and 630 pixels tall.",
),
required=False,
)
og_image_delete = forms.BooleanField(
label=pgettext_lazy("admin general settings form", "Delete image"),
required=False,
)
og_image_avatar_on_profile = YesNoSwitch(
label=pgettext_lazy(
"admin general settings form", "Replace image with avatar on user profiles"
)
)
og_image_avatar_on_thread = YesNoSwitch(
label=pgettext_lazy(
"admin general settings form", "Replace image with avatar on threads"
)
)
forum_footnote = forms.CharField(
label=pgettext_lazy("admin general settings form", "Forum footnote"),
help_text=pgettext_lazy(
"admin general settings form", "Short message displayed in forum footer."
),
max_length=300,
required=False,
)
email_footer = forms.CharField(
label=pgettext_lazy("admin general settings form", "E-mails footer"),
help_text=pgettext_lazy(
"admin general settings form",
"Optional short message included at the end of e-mails sent by forum.",
),
max_length=255,
required=False,
)
show_admin_panel_link_in_ui = YesNoSwitch(
label=pgettext_lazy(
"admin general settings form",
"Display the link to the Admin Control Panel in the administrator's user menu",
),
help_text=pgettext_lazy(
"admin general settings form",
"Hiding the link to the ACP from user menus reduces risk of malicious actors gaining access to admin session for admin users who are sharing their device with others or who are logging in to the site in public spaces.",
),
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Add index_view choice field
self.fields["index_view"] = forms.CharField(
label=pgettext_lazy("admin general settings form", "Index page"),
help_text=pgettext_lazy(
"admin general settings form",
"Select the page to display on the forum index.",
),
widget=forms.RadioSelect(choices=index_views.get_choices()),
required=True,
)
# Set help text with accurate forum address from request on forum_address field
address = self.request.build_absolute_uri("/").rstrip("/")
self["forum_address"].help_text = pgettext_lazy(
"admin general settings form",
'Misago uses this setting to build links in e-mails sent to site users. Address under which site is running appears to be "%(address)s".',
) % {"address": address}
def clean_forum_address(self):
return self.cleaned_data["forum_address"].lower().rstrip("/")
| 6,866
|
Python
|
.py
| 168
| 32.220238
| 231
| 0.632162
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,489
|
captcha.py
|
rafalp_Misago/misago/conf/admin/forms/captcha.py
|
from django import forms
from django.utils.translation import pgettext_lazy
from ....admin.forms import YesNoSwitch
from .base import SettingsForm
class CaptchaSettingsForm(SettingsForm):
settings = [
"captcha_type",
"recaptcha_site_key",
"recaptcha_secret_key",
"qa_question",
"qa_help_text",
"qa_answers",
"enable_stop_forum_spam",
"stop_forum_spam_confidence",
]
captcha_type = forms.ChoiceField(
label=pgettext_lazy("admin captcha settings form", "Enable CAPTCHA"),
choices=[
("no", pgettext_lazy("admin captcha type field choice", "No CAPTCHA")),
("re", pgettext_lazy("admin captcha type field choice", "reCaptcha")),
(
"qa",
pgettext_lazy("admin captcha type field choice", "Question and answer"),
),
],
widget=forms.RadioSelect(),
)
recaptcha_site_key = forms.CharField(
label=pgettext_lazy("admin captcha settings form", "Site key"),
max_length=100,
required=False,
)
recaptcha_secret_key = forms.CharField(
label=pgettext_lazy("admin captcha settings form", "Secret key"),
max_length=100,
required=False,
)
qa_question = forms.CharField(
label=pgettext_lazy("admin captcha settings form", "Test question"),
max_length=100,
required=False,
)
qa_help_text = forms.CharField(
label=pgettext_lazy("admin captcha settings form", "Question help text"),
max_length=250,
required=False,
)
qa_answers = forms.CharField(
label=pgettext_lazy("admin captcha settings form", "Valid answers"),
help_text=pgettext_lazy(
"admin captcha settings form",
"Enter each answer in new line. Answers are case-insensitive.",
),
widget=forms.Textarea({"rows": 4}),
max_length=250,
required=False,
)
enable_stop_forum_spam = YesNoSwitch(
label=pgettext_lazy(
"admin captcha settings form",
"Validate new registrations against SFS database",
),
help_text=pgettext_lazy(
"admin captcha settings form",
"Turning this option on will result in Misago validating new user's e-mail and IP address against SFS database.",
),
)
stop_forum_spam_confidence = forms.IntegerField(
label=pgettext_lazy(
"admin captcha settings form", "Minimum SFS confidence required"
),
help_text=pgettext_lazy(
"admin captcha settings form",
"SFS compares user e-mail and IP address with database of known spammers and assigns the confidence score in range of 0 to 100 that user is a spammer themselves. If this score is equal or higher than specified, Misago will block user from registering and ban their IP address for 24 hours.",
),
min_value=0,
max_value=100,
)
def clean(self):
cleaned_data = super().clean()
if cleaned_data.get("captcha_type") == "re":
if not cleaned_data.get("recaptcha_site_key"):
self.add_error(
"recaptcha_site_key",
pgettext_lazy(
"admin captcha settings form",
"You need to enter site key if selected CAPTCHA type is reCaptcha.",
),
)
if not cleaned_data.get("recaptcha_secret_key"):
self.add_error(
"recaptcha_secret_key",
pgettext_lazy(
"admin captcha settings form",
"You need to enter secret key if selected CAPTCHA type is reCaptcha.",
),
)
if cleaned_data.get("captcha_type") == "qa":
if not cleaned_data.get("qa_question"):
self.add_error(
"qa_question",
pgettext_lazy(
"admin captcha settings form",
"You need to set question if selected CAPTCHA type is Q&A.",
),
)
if not cleaned_data.get("qa_answers"):
self.add_error(
"qa_answers",
pgettext_lazy(
"admin captcha settings form",
"You need to set question answers if selected CAPTCHA type is Q&A.",
),
)
return cleaned_data
| 4,603
|
Python
|
.py
| 115
| 28.269565
| 303
| 0.564469
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,490
|
analytics.py
|
rafalp_Misago/misago/conf/admin/forms/analytics.py
|
import re
from django import forms
from django.utils.translation import pgettext_lazy
from .base import SettingsForm
GOOGLE_SITE_VERIFICATION = re.compile(
r"^google-site-verification: google([0-9a-z]+)\.html$"
)
class AnalyticsSettingsForm(SettingsForm):
settings = ["google_tracking_id", "google_site_verification"]
google_tracking_id = forms.CharField(
label=pgettext_lazy("admin analytics settings form", "Tracking ID"),
help_text=pgettext_lazy(
"admin analytics settings form",
"Setting the Tracking ID will result in gtag.js file being included in your site's HTML markup, enabling Google Analytics integration.",
),
required=False,
)
google_site_verification = forms.CharField(
label=pgettext_lazy("admin analytics settings form", "Site verification code"),
help_text=pgettext_lazy(
"admin analytics settings form",
"This code was extracted from the uploaded site verification file. To change it, upload new verification file.",
),
required=False,
disabled=True,
)
google_site_verification_file = forms.FileField(
label=pgettext_lazy(
"admin analytics settings form", "Upload site verification file"
),
help_text=pgettext_lazy(
"admin analytics settings form",
'Site verification file can be downloaded from Search Console\'s "Ownership verification" page.',
),
required=False,
)
def clean_google_site_verification_file(self):
upload = self.cleaned_data.get("google_site_verification_file")
if not upload:
return None
if upload.content_type != "text/html":
raise forms.ValidationError(
pgettext_lazy(
"admin analytics settings form", "Uploaded file type is not HTML."
)
)
file_content = upload.read().decode("utf-8")
content_match = GOOGLE_SITE_VERIFICATION.match(file_content)
if not content_match:
raise forms.ValidationError(
pgettext_lazy(
"admin analytics settings form",
"Uploaded file doesn't contain a verification code.",
)
)
return content_match.group(1)
def clean(self):
cleaned_data = super().clean()
if cleaned_data.get("google_site_verification_file"):
new_verification = cleaned_data.pop("google_site_verification_file")
cleaned_data["google_site_verification"] = new_verification
return cleaned_data
| 2,658
|
Python
|
.py
| 62
| 33.241935
| 148
| 0.640232
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,491
|
__init__.py
|
rafalp_Misago/misago/conf/admin/forms/__init__.py
|
from .analytics import AnalyticsSettingsForm
from .base import SettingsForm
from .captcha import CaptchaSettingsForm
from .general import GeneralSettingsForm
from .notifications import NotificationsSettingsForm
from .oauth2 import OAuth2SettingsForm
from .threads import ThreadsSettingsForm
from .users import UsersSettingsForm
| 328
|
Python
|
.py
| 8
| 40
| 52
| 0.9
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,492
|
base.py
|
rafalp_Misago/misago/conf/admin/forms/base.py
|
from django import forms
from ...cache import clear_settings_cache
class SettingsForm(forms.Form):
settings = []
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request")
super().__init__(*args, **kwargs)
def save(self, settings):
self.save_settings(settings)
self.clear_cache()
def save_settings(self, settings):
for setting in self.settings:
setting_obj = settings[setting]
new_value = self.cleaned_data.get(setting)
if setting_obj.python_type == "image":
if new_value and new_value != self.initial.get(setting):
self.save_image(setting_obj, new_value)
elif self.cleaned_data.get("%s_delete" % setting):
self.delete_image(setting_obj)
else:
self.save_setting(setting_obj, new_value)
def delete_image(self, setting):
if setting.image:
setting.image.delete()
def save_image(self, setting, value):
if setting.image:
setting.image.delete(save=False)
setting.value = value
setting.save()
def save_setting(self, setting, value):
setting.value = value
setting.save()
def clear_cache(self):
clear_settings_cache()
| 1,322
|
Python
|
.py
| 34
| 29.117647
| 72
| 0.599374
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,493
|
threads.py
|
rafalp_Misago/misago/conf/admin/forms/threads.py
|
from django import forms
from django.utils.translation import pgettext_lazy
from ....categories.enums import CategoryChildrenComponent
from ....threads.enums import ThreadsListsPolling
from .base import SettingsForm
class ThreadsSettingsForm(SettingsForm):
settings = [
"attachment_403_image",
"attachment_404_image",
"daily_post_limit",
"hourly_post_limit",
"post_attachments_limit",
"post_length_max",
"post_length_min",
"readtracker_cutoff",
"thread_title_length_max",
"thread_title_length_min",
"unused_attachments_lifetime",
"threads_per_page",
"threads_list_item_categories_component",
"threads_list_categories_component",
"threads_lists_polling",
"posts_per_page",
"posts_per_page_orphans",
"events_per_page",
]
daily_post_limit = forms.IntegerField(
label=pgettext_lazy("admin threads settings form", "Daily post limit per user"),
help_text=pgettext_lazy(
"admin threads settings form",
"Daily limit of posts that may be posted by single user. Fail-safe for situations when forum is flooded by spam bots. Change to 0 to remove the limit.",
),
min_value=0,
)
hourly_post_limit = forms.IntegerField(
label=pgettext_lazy(
"admin threads settings form", "Hourly post limit per user"
),
help_text=pgettext_lazy(
"admin threads settings form",
"Hourly limit of posts that may be posted by single user. Fail-safe for situations when forum is flooded by spam bots. Change to 0 to remove the limit.",
),
min_value=0,
)
post_attachments_limit = forms.IntegerField(
label=pgettext_lazy(
"admin threads settings form", "Maximum number of attachments per post"
),
min_value=1,
)
post_length_max = forms.IntegerField(
label=pgettext_lazy(
"admin threads settings form", "Maximum allowed post length"
),
min_value=0,
)
post_length_min = forms.IntegerField(
label=pgettext_lazy(
"admin threads settings form", "Minimum required post length"
),
min_value=1,
)
thread_title_length_max = forms.IntegerField(
label=pgettext_lazy(
"admin threads settings form", "Maximum allowed thread title length"
),
min_value=2,
max_value=255,
)
thread_title_length_min = forms.IntegerField(
label=pgettext_lazy(
"admin threads settings form", "Minimum required thread title length"
),
min_value=2,
max_value=255,
)
unused_attachments_lifetime = forms.IntegerField(
label=pgettext_lazy(
"admin threads settings form", "Unused attachments lifetime"
),
help_text=pgettext_lazy(
"admin threads settings form",
"Period of time (in hours) after which user-uploaded files that weren't attached to any post are deleted from disk.",
),
min_value=1,
)
readtracker_cutoff = forms.IntegerField(
label=pgettext_lazy("admin threads settings form", "Read-tracker cutoff"),
help_text=pgettext_lazy(
"admin threads settings form",
"Controls amount of data used by read-tracking system. All content older than number of days specified in this setting is considered old and read, even if the opposite is true for the user. Active forums can try lowering this value while less active ones may wish to increase it instead.",
),
min_value=1,
)
threads_per_page = forms.IntegerField(
label=pgettext_lazy(
"admin threads settings form",
"Number of threads displayed on a single page",
),
min_value=10,
)
threads_list_item_categories_component = forms.CharField(
label=pgettext_lazy(
"admin threads settings form", "Thread's categories appearance"
),
help_text=pgettext_lazy(
"admin threads settings form",
"Select UI for displaying threads categories on threads lists.",
),
widget=forms.RadioSelect(
choices=(
(
"breadcrumbs",
pgettext_lazy(
"admin threads item categories choice", "Breadcrumbs"
),
),
(
"labels",
pgettext_lazy("admin threads item categories choice", "Labels"),
),
)
),
)
threads_lists_polling = forms.IntegerField(
label=pgettext_lazy(
"admin threads settings form",
"Enable polling for new or updated threads",
),
help_text=pgettext_lazy(
"admin threads settings form",
"Enabling polling will make threads lists call the server every minute for the number of new or updated threads. If there are new threads, a button will be displayed for the user that will let them refresh the list without having to refresh the entire page.",
),
widget=forms.RadioSelect(
choices=ThreadsListsPolling.get_choices(),
),
)
threads_list_categories_component = forms.CharField(
label=pgettext_lazy("admin threads settings form", "Categories UI component"),
help_text=pgettext_lazy(
"admin threads settings form",
"Select UI component to use for displaying list of categories on the threads page.",
),
widget=forms.RadioSelect(
choices=CategoryChildrenComponent.get_threads_choices(),
),
)
posts_per_page = forms.IntegerField(
label=pgettext_lazy(
"admin threads settings form", "Number of posts displayed on a single page"
),
min_value=5,
)
posts_per_page_orphans = forms.IntegerField(
label=pgettext_lazy("admin threads settings form", "Maximum orphans"),
help_text=pgettext_lazy(
"admin threads settings form",
"This setting prevents situations when the last page of a thread contains very few items. If number of posts to be displayed on the last page is less or equal to number specified in this setting, those posts will instead be appended to the previous page, reducing number of thread's pages.",
),
min_value=0,
)
events_per_page = forms.IntegerField(
label=pgettext_lazy(
"admin threads settings form",
"Maximum number of events displayed on a single page",
),
min_value=5,
)
attachment_403_image = forms.ImageField(
label=pgettext_lazy("admin threads settings form", "Permission denied"),
help_text=pgettext_lazy(
"admin threads settings form",
"Attachments proxy will display this image in place of default one when user tries to access attachment they have no permission to see.",
),
required=False,
)
attachment_403_image_delete = forms.BooleanField(
label=pgettext_lazy(
"admin threads settings form", "Delete custom permission denied image"
),
required=False,
)
attachment_404_image = forms.ImageField(
label=pgettext_lazy("admin threads settings form", "Not found"),
help_text=pgettext_lazy(
"admin threads settings form",
"Attachments proxy will display this image in place of default one when user tries to access attachment that doesn't exist.",
),
required=False,
)
attachment_404_image_delete = forms.BooleanField(
label=pgettext_lazy(
"admin threads settings form", "Delete custom not found image"
),
required=False,
)
def clean(self):
cleaned_data = super().clean()
if cleaned_data.get("posts_per_page_orphans") > cleaned_data.get(
"posts_per_page"
):
self.add_error(
"posts_per_page_orphans",
pgettext_lazy(
"admin threads settings form",
"This value must be lower than number of posts per page.",
),
)
return cleaned_data
| 8,394
|
Python
|
.py
| 209
| 30.578947
| 303
| 0.621651
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,494
|
oauth2.py
|
rafalp_Misago/misago/conf/admin/forms/oauth2.py
|
from django import forms
from django.contrib import messages
from django.utils.translation import pgettext, pgettext_lazy
from ....admin.forms import YesNoSwitch
from .base import SettingsForm
OAUTH2_OPTIONAL_FIELDS = (
"oauth2_enable_pkce",
"oauth2_token_extra_headers",
"oauth2_user_extra_headers",
"oauth2_send_welcome_email",
"oauth2_json_avatar_path",
)
class OAuth2SettingsForm(SettingsForm):
settings = [
"enable_oauth2_client",
"oauth2_provider",
"oauth2_client_id",
"oauth2_client_secret",
"oauth2_enable_pkce",
"oauth2_pkce_code_challenge_method",
"oauth2_scopes",
"oauth2_login_url",
"oauth2_token_url",
"oauth2_token_extra_headers",
"oauth2_json_token_path",
"oauth2_user_url",
"oauth2_user_method",
"oauth2_user_token_location",
"oauth2_user_token_name",
"oauth2_user_extra_headers",
"oauth2_send_welcome_email",
"oauth2_json_id_path",
"oauth2_json_name_path",
"oauth2_json_email_path",
"oauth2_json_avatar_path",
]
enable_oauth2_client = YesNoSwitch(
label=pgettext_lazy("admin oauth2 settings form", "Enable OAuth2 client"),
help_text=pgettext_lazy(
"admin oauth2 settings form",
"Enabling OAuth2 will make login option redirect users to the OAuth provider configured below. It will also disable option to register on forum, change username, email or password, as those features will be delegated to the 3rd party site.",
),
)
oauth2_provider = forms.CharField(
label=pgettext_lazy("admin oauth2 settings form", "Provider name"),
help_text=pgettext_lazy(
"admin oauth2 settings form",
"Name of the OAuth 2 provider to be displayed by interface.",
),
max_length=255,
required=False,
)
oauth2_client_id = forms.CharField(
label=pgettext_lazy("admin oauth2 settings form", "Client ID"),
max_length=200,
required=False,
)
oauth2_client_secret = forms.CharField(
label=pgettext_lazy("admin oauth2 settings form", "Client Secret"),
max_length=200,
required=False,
)
oauth2_scopes = forms.CharField(
label=pgettext_lazy("admin oauth2 settings form", "Scopes"),
help_text=pgettext_lazy(
"admin oauth2 settings form",
"List of scopes to request from provider, separated with spaces.",
),
max_length=500,
required=False,
)
oauth2_login_url = forms.URLField(
label=pgettext_lazy("admin oauth2 settings form", "Login form URL"),
help_text=pgettext_lazy(
"admin oauth2 settings form",
"Address of the login form on provider's server that users will be redirected to.",
),
max_length=500,
required=False,
)
oauth2_token_url = forms.URLField(
label=pgettext_lazy("admin oauth2 settings form", "Access token retrieval URL"),
help_text=pgettext_lazy(
"admin oauth2 settings form",
"URL that will be called after user completes the login process and authorization code is sent back to your site. This URL is expected to take this code and return the access token that will be next used to retrieve user data.",
),
max_length=500,
required=False,
)
oauth2_token_extra_headers = forms.CharField(
label=pgettext_lazy(
"admin oauth2 settings form", "Extra HTTP headers in token request"
),
help_text=pgettext_lazy(
"admin oauth2 settings form",
'List of extra headers to include in a HTTP request made to retrieve the access token. Example header is "Header-name: value". Specify each header on separate line.',
),
widget=forms.Textarea(attrs={"rows": 4}),
max_length=500,
required=False,
)
oauth2_json_token_path = forms.CharField(
label=pgettext_lazy("admin oauth2 settings form", "JSON path to access token"),
help_text=pgettext_lazy(
"admin oauth2 settings form",
'Name of key containing the access token in JSON returned by the provider. If token is nested, use period (".") for path, eg: "result.token" will retrieve the token from "token" key nested in "result".',
),
max_length=500,
required=False,
)
oauth2_user_url = forms.URLField(
label=pgettext_lazy("admin oauth2 settings form", "User data URL"),
max_length=500,
required=False,
)
oauth2_user_method = forms.ChoiceField(
label=pgettext_lazy("admin oauth2 settings form", "Request method"),
choices=[
("POST", "POST"),
("GET", "GET"),
],
widget=forms.RadioSelect(),
)
oauth2_user_token_location = forms.ChoiceField(
label=pgettext_lazy("admin oauth2 settings form", "Access token location"),
choices=[
(
"QUERY",
pgettext_lazy(
"admin oauth2 token location choice",
"Query string",
),
),
(
"HEADER",
pgettext_lazy(
"admin oauth2 token location choice",
"HTTP header",
),
),
(
"HEADER_BEARER",
pgettext_lazy(
"admin oauth2 token location choice",
"HTTP header (Bearer)",
),
),
],
widget=forms.RadioSelect(),
)
oauth2_user_token_name = forms.CharField(
label=pgettext_lazy("admin oauth2 settings form", "Access token name"),
max_length=200,
required=False,
)
oauth2_user_extra_headers = forms.CharField(
label=pgettext_lazy(
"admin oauth2 settings form", "Extra HTTP headers in user request"
),
help_text=pgettext_lazy(
"admin oauth2 settings form",
'List of extra headers to include in a HTTP request made to retrieve the user profile. Example header is "Header-name: value". Specify each header on separate line.',
),
widget=forms.Textarea(attrs={"rows": 4}),
max_length=500,
required=False,
)
oauth2_send_welcome_email = YesNoSwitch(
label=pgettext_lazy(
"admin oauth2 settings form",
"Send a welcoming e-mail to users on their first sign-ons",
),
required=False,
)
oauth2_json_id_path = forms.CharField(
label=pgettext_lazy("admin oauth2 settings form", "User ID path"),
max_length=200,
required=False,
)
oauth2_json_name_path = forms.CharField(
label=pgettext_lazy("admin oauth2 settings form", "User name path"),
max_length=200,
required=False,
)
oauth2_json_email_path = forms.CharField(
label=pgettext_lazy("admin oauth2 settings form", "User e-mail path"),
max_length=200,
required=False,
)
oauth2_json_avatar_path = forms.CharField(
label=pgettext_lazy("admin oauth2 settings form", "User avatar URL path"),
help_text=pgettext_lazy(
"admin oauth2 settings form",
"Optional, leave empty to don't download avatar from provider.",
),
max_length=200,
required=False,
)
oauth2_enable_pkce = YesNoSwitch(
label=pgettext_lazy("admin oauth2 settings form", "Enable OAuth2 PKCE"),
help_text=pgettext_lazy(
"admin oauth2 settings form",
"Enabling this option will make Misago's OAuth2 client use PKCE (Proof Key for Code Exchange), increasing the security of the authentication process. The OAuth 2 server must also support PKCE.",
),
required=False,
)
oauth2_pkce_code_challenge_method = forms.ChoiceField(
label=pgettext_lazy("admin oauth2 settings form", "PKCE Code Challenge method"),
help_text=pgettext_lazy(
"admin oauth2 settings form",
"When PKCE is enabled this hashing method is used to generate the PKCE code challenge for the OAuth2 server.",
),
choices=[
("S256", "S256"),
(
"plain",
pgettext_lazy(
"admin oauth2 settings pkce choice", "plain (no hashing)"
),
),
],
widget=forms.RadioSelect(),
)
def clean_oauth2_scopes(self):
# Remove duplicates and extra spaces, keep order of scopes
clean_scopes = []
for scope in self.cleaned_data["oauth2_scopes"].split():
scope = scope.strip()
if scope and scope not in clean_scopes:
clean_scopes.append(scope)
return " ".join(clean_scopes) or None
def clean_oauth2_token_extra_headers(self):
return clean_headers(self.cleaned_data["oauth2_token_extra_headers"])
def clean_oauth2_user_extra_headers(self):
return clean_headers(self.cleaned_data["oauth2_user_extra_headers"])
def clean(self):
data = super().clean()
if not data.get("enable_oauth2_client"):
return data
required_data = [data[key] for key in data if key not in OAUTH2_OPTIONAL_FIELDS]
if not all(required_data):
data["enable_oauth2_client"] = False
messages.error(
self.request,
pgettext(
"admin oauth2 settings form",
"You need to complete the configuration before you will be able to enable OAuth 2 on your site.",
),
)
return data
def clean_headers(headers_value):
clean_headers = {}
for header in headers_value.splitlines():
header = header.strip()
if not header:
continue
if ":" not in header:
raise forms.ValidationError(
pgettext(
"admin oauth2 settings form",
'"%(header)s" is not a valid header. It\'s missing a colon (":").',
)
% {"header": header},
)
name, value = [part.strip() for part in header.split(":", 1)]
if not name:
raise forms.ValidationError(
pgettext(
"admin oauth2 settings form",
'"%(header)s" is not a valid header. It\'s missing a header name before the colon (":").',
)
% {"header": header},
)
if name in clean_headers:
raise forms.ValidationError(
pgettext(
"admin oauth2 settings form",
'"%(header)s" header is entered more than once.',
)
% {"header": name},
)
if not value:
raise forms.ValidationError(
pgettext(
"admin oauth2 settings form",
'"%(header)s" is not a valid header. It\'s missing a header value after the colon (":").',
)
% {"header": header},
)
clean_headers[name] = value
return "\n".join([f"{key}: {value}" for key, value in clean_headers.items()])
| 11,464
|
Python
|
.py
| 291
| 29.130584
| 253
| 0.588246
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,495
|
notifications.py
|
rafalp_Misago/misago/conf/admin/forms/notifications.py
|
from django import forms
from django.utils.translation import pgettext_lazy
from ....notifications.threads import ThreadNotifications
from .base import SettingsForm
class NotificationsSettingsForm(SettingsForm):
settings = [
"watch_started_threads",
"watch_replied_threads",
"watch_new_private_threads_by_followed",
"watch_new_private_threads_by_other_users",
"notify_new_private_threads_by_followed",
"notify_new_private_threads_by_other_users",
"delete_notifications_older_than",
]
watch_started_threads = forms.TypedChoiceField(
label=pgettext_lazy(
"admin notifications settings form",
"Notify about new replies in threads started by them",
),
choices=ThreadNotifications.choices,
widget=forms.RadioSelect(),
coerce=int,
)
watch_replied_threads = forms.TypedChoiceField(
label=pgettext_lazy(
"admin notifications settings form",
"Notify about new replies in threads replied to by them",
),
choices=ThreadNotifications.choices,
widget=forms.RadioSelect(),
coerce=int,
)
watch_new_private_threads_by_followed = forms.TypedChoiceField(
label=pgettext_lazy(
"admin notifications settings form",
"Notify about new replies in new private threads started by followed users",
),
choices=ThreadNotifications.choices,
widget=forms.RadioSelect(),
coerce=int,
)
watch_new_private_threads_by_other_users = forms.TypedChoiceField(
label=pgettext_lazy(
"admin notifications settings form",
"Notify about new replies in new private threads started by other users",
),
choices=ThreadNotifications.choices,
widget=forms.RadioSelect(),
coerce=int,
)
notify_new_private_threads_by_followed = forms.TypedChoiceField(
label=pgettext_lazy(
"admin notifications settings form",
"Notify about new private threads started by followed users",
),
choices=ThreadNotifications.choices,
widget=forms.RadioSelect(),
coerce=int,
)
notify_new_private_threads_by_other_users = forms.TypedChoiceField(
label=pgettext_lazy(
"admin notifications settings form",
"Notify about new private threads started by other users",
),
choices=ThreadNotifications.choices,
widget=forms.RadioSelect(),
coerce=int,
)
delete_notifications_older_than = forms.IntegerField(
label=pgettext_lazy(
"admin notifications settings form",
"Delete notifications older than (in days)",
),
help_text=pgettext_lazy(
"admin notifications settings form",
"Misago automatically deletes notifications older than the specified age.",
),
min_value=1,
)
| 2,984
|
Python
|
.py
| 79
| 29.189873
| 88
| 0.658385
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,496
|
conftest.py
|
rafalp_Misago/misago/conf/admin/tests/conftest.py
|
import pytest
from ...models import Setting
@pytest.fixture
def setting(db):
return Setting.objects.get(setting="forum_name")
| 133
|
Python
|
.py
| 5
| 24.2
| 52
| 0.792
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,497
|
test_image_setting_handling.py
|
rafalp_Misago/misago/conf/admin/tests/test_image_setting_handling.py
|
import os
import pytest
from django.urls import reverse
from ....test import assert_contains
from ...models import Setting
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
IMAGE = os.path.join(BASE_DIR, "testfiles", "image.png")
OTHER_IMAGE = os.path.join(BASE_DIR, "testfiles", "image-other.png")
OTHER_FILE = os.path.join(BASE_DIR, "testfiles", "other")
@pytest.fixture
def setting(db):
obj = Setting.objects.get(setting="logo")
yield obj
obj.refresh_from_db()
if obj.image:
obj.image.delete(save=False)
def test_image_setting_can_be_set(admin_client, setting):
with open(IMAGE, "rb") as image:
admin_client.post(
reverse("misago:admin:settings:general:index"),
{
"forum_name": "Misago",
"forum_address": "http://test.com",
"index_view": "threads",
"logo": image,
},
)
setting.refresh_from_db()
assert setting.image
def test_setting_image_also_sets_its_dimensions(admin_client, setting):
with open(IMAGE, "rb") as image:
admin_client.post(
reverse("misago:admin:settings:general:index"),
{
"forum_name": "Misago",
"forum_address": "http://test.com",
"index_view": "threads",
"logo": image,
},
)
setting.refresh_from_db()
assert setting.image_width == 4
assert setting.image_height == 2
def test_setting_image_filename_is_prefixed_with_setting_name(admin_client, setting):
with open(IMAGE, "rb") as image:
admin_client.post(
reverse("misago:admin:settings:general:index"),
{
"forum_name": "Misago",
"forum_address": "http://test.com",
"index_view": "threads",
"logo": image,
},
)
setting.refresh_from_db()
assert ("%s." % setting.setting) in str(setting.image.name)
def test_setting_image_filename_is_hashed(admin_client, setting):
with open(IMAGE, "rb") as image:
admin_client.post(
reverse("misago:admin:settings:general:index"),
{
"forum_name": "Misago",
"forum_address": "http://test.com",
"index_view": "threads",
"logo": image,
},
)
setting.refresh_from_db()
assert str(setting.image.name).endswith(".c68ed127.png")
def test_image_setting_rejects_non_image_file(admin_client, setting):
with open(OTHER_FILE, "rb") as not_image:
admin_client.post(
reverse("misago:admin:settings:general:index"),
{
"forum_name": "Misago",
"forum_address": "http://test.com",
"index_view": "threads",
"logo": not_image,
},
)
setting.refresh_from_db()
assert not setting.image
@pytest.fixture
def setting_with_value(admin_client, setting):
with open(IMAGE, "rb") as not_image:
admin_client.post(
reverse("misago:admin:settings:general:index"),
{
"forum_name": "Misago",
"forum_address": "http://test.com",
"index_view": "threads",
"logo": not_image,
},
)
setting.refresh_from_db()
return setting
def test_image_setting_value_is_rendered_in_form(admin_client, setting_with_value):
response = admin_client.get(reverse("misago:admin:settings:general:index"))
assert_contains(response, setting_with_value.image.url)
def test_invalid_file_is_not_set_as_value(admin_client, setting):
with open(OTHER_FILE, "rb") as not_image:
admin_client.post(
reverse("misago:admin:settings:general:index"),
{
"forum_name": "Misago",
"forum_address": "http://test.com",
"index_view": "threads",
"logo": not_image,
},
)
setting.refresh_from_db()
assert not setting.image
def test_uploading_invalid_file_doesnt_remove_already_set_image(
admin_client, setting_with_value
):
with open(OTHER_FILE, "rb") as not_image:
admin_client.post(
reverse("misago:admin:settings:general:index"),
{
"forum_name": "Misago",
"forum_address": "http://test.com",
"index_view": "threads",
"logo": not_image,
},
)
setting_with_value.refresh_from_db()
assert setting_with_value.image
def test_set_image_is_still_rendered_when_invalid_file_was_uploaded(
admin_client, setting_with_value
):
with open(OTHER_FILE, "rb") as not_image:
response = admin_client.post(
reverse("misago:admin:settings:general:index"),
{
"forum_name": "Misago",
"forum_address": "http://test.com",
"index_view": "threads",
"logo": not_image,
},
)
assert_contains(response, setting_with_value.image.url)
def test_uploading_new_image_replaces_already_set_image(
admin_client, setting_with_value
):
with open(OTHER_IMAGE, "rb") as not_image:
admin_client.post(
reverse("misago:admin:settings:general:index"),
{
"forum_name": "Misago",
"forum_address": "http://test.com",
"index_view": "threads",
"logo": not_image,
},
)
setting_with_value.refresh_from_db()
assert str(setting_with_value.image.name).endswith(".d18644ab.png")
def test_uploading_new_image_deletes_image_file(admin_client, setting_with_value):
with open(OTHER_IMAGE, "rb") as not_image:
admin_client.post(
reverse("misago:admin:settings:general:index"),
{
"forum_name": "Misago",
"forum_address": "http://test.com",
"index_view": "threads",
"logo": not_image,
},
)
assert not os.path.exists(setting_with_value.image.path)
def test_omitting_setting_value_doesnt_remove_already_set_image(
admin_client, setting_with_value
):
admin_client.post(
reverse("misago:admin:settings:general:index"),
{"forum_name": "Misago", "forum_address": "http://test.com"},
)
setting_with_value.refresh_from_db()
assert setting_with_value.image
def test_set_image_can_be_deleted_by_extra_option(admin_client, setting_with_value):
admin_client.post(
reverse("misago:admin:settings:general:index"),
{
"forum_name": "Misago",
"forum_address": "http://test.com",
"index_view": "threads",
"logo_delete": 1,
},
)
setting_with_value.refresh_from_db()
assert not setting_with_value.image
def test_using_image_deletion_option_deletes_image_file(
admin_client, setting_with_value
):
admin_client.post(
reverse("misago:admin:settings:general:index"),
{
"forum_name": "Misago",
"forum_address": "http://test.com",
"index_view": "threads",
"logo_delete": 1,
},
)
assert not os.path.exists(setting_with_value.image.path)
| 7,375
|
Python
|
.py
| 202
| 27.049505
| 85
| 0.578186
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,498
|
test_settings_grid.py
|
rafalp_Misago/misago/conf/admin/tests/test_settings_grid.py
|
from django.urls import reverse
from ....test import assert_contains
def test_link_is_registered_in_admin_nav(admin_client):
response = admin_client.get(reverse("misago:admin:index"))
assert_contains(response, reverse("misago:admin:settings:index"))
def test_settings_grid_renders(admin_client):
response = admin_client.get(reverse("misago:admin:settings:index"))
assert response.status_code == 200
| 420
|
Python
|
.py
| 8
| 48.875
| 71
| 0.771499
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|
18,499
|
test_change_settings_form.py
|
rafalp_Misago/misago/conf/admin/tests/test_change_settings_form.py
|
from django import forms
from ....cache.test import assert_invalidates_cache
from ... import SETTINGS_CACHE
from ..forms import SettingsForm
class Form(SettingsForm):
settings = ["forum_name"]
forum_name = forms.CharField(max_length=255)
def test_form_updates_setting_on_save(setting):
form = Form({"forum_name": "New Value"}, request=None)
assert form.is_valid()
form.save({"forum_name": setting})
setting.refresh_from_db()
assert setting.value == "New Value"
def test_form_invalidates_settings_cache_on_save(setting):
with assert_invalidates_cache(SETTINGS_CACHE):
form = Form({"forum_name": "New Value"}, request=None)
assert form.is_valid()
form.save({"forum_name": setting})
| 745
|
Python
|
.py
| 18
| 36.777778
| 62
| 0.710306
|
rafalp/Misago
| 2,519
| 524
| 136
|
GPL-2.0
|
9/5/2024, 5:12:22 PM (Europe/Amsterdam)
|