Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion backend/samfundet/tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from root.utils import routes, permissions

from samfundet.serializers import UserSerializer, RegisterSerializer
from samfundet.models.event import Event
from samfundet.models.general import (
Gang,
User,
Expand All @@ -38,7 +39,7 @@
RecruitmentPosition,
RecruitmentApplication,
)
from samfundet.models.model_choices import RecruitmentStatusChoices, RecruitmentPriorityChoices
from samfundet.models.model_choices import EventAgeRestriction, RecruitmentStatusChoices, RecruitmentPriorityChoices

if TYPE_CHECKING:
from rest_framework.test import APIClient
Expand All @@ -55,6 +56,35 @@ def test_csrf(fixture_rest_client: APIClient):
assert status.is_success(code=response.status_code)


def test_events_rss_feed(fixture_rest_client: APIClient, fixture_image: Image):
now = timezone.now()
Event.objects.create(
title_nb='RSS Event',
title_en='RSS Event',
start_dt=now + timezone.timedelta(minutes=5),
end_dt=now + timezone.timedelta(hours=1),
visibility_from_dt=now - timezone.timedelta(hours=1),
visibility_to_dt=now + timezone.timedelta(days=1),
description_long_nb='RSS description',
description_long_en='RSS description',
description_short_nb='RSS short description',
description_short_en='RSS short description',
location='location',
host='host',
image=fixture_image,
age_restriction=EventAgeRestriction.AGE_18,
capacity=100,
)

response: Response = fixture_rest_client.get(path='/events/rss/')

assert status.is_success(code=response.status_code)
assert response['Content-Type'].startswith('application/rss+xml')
assert b'<rss' in response.content
assert b'RSS Event' in response.content
assert b'RSS short description' in response.content


class TestUserViews:
post_data = {
'username': 'username',
Expand Down
1 change: 1 addition & 0 deletions backend/samfundet/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
path('users-search-paginated/', samfundet.view.user_views.PaginatedSearchUsersView.as_view(), name='users_search_paginated'),
path('impersonate/', samfundet.view.user_views.ImpersonateView.as_view(), name='impersonate'),
path('events-per-day/', samfundet.view.event_views.EventPerDayView.as_view(), name='eventsperday'),
path('events/rss/', samfundet.view.event_views.EventRSSView.as_view(), name='events_rss'),
path('events-upcomming/', samfundet.view.event_views.EventsUpcomingView.as_view(), name='eventsupcomming'),
path('isclosed/', samfundet.view.general_views.IsClosedView().as_view(), name='isclosed'),
path('home/', samfundet.view.general_views.HomePageView().as_view(), name='home'),
Expand Down
56 changes: 56 additions & 0 deletions backend/samfundet/view/event_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@
from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import AllowAny, IsAuthenticated

from django.http import HttpResponse
from django.urls import reverse
from django.utils import timezone
from django.utils.feedgenerator import Rss201rev2Feed

from root.constants import WebFeatures
from root.custom_classes.permission_classes import FeatureEnabled, RoleProtectedOrAnonReadOnlyObjectPermissions
Expand Down Expand Up @@ -135,3 +138,56 @@ def post(self, request: Request) -> Response:
form=purchase_model,
)
return Response(status=status.HTTP_201_CREATED, data={'message': 'Feedback submitted successfully!'})


class SamfundetRssFeed(Rss201rev2Feed):
def __init__(self, *args, **kwargs):
self._feed_url = kwargs.get('feed_url')
super().__init__(*args, **kwargs)

def root_attributes(self):
attrs = super().root_attributes()
attrs['xmlns:atom'] = 'http://www.w3.org/2005/Atom'
return attrs

def writeString(self, encoding):
"""Override to add atom:link with rel='self'"""
feed_str = super().writeString(encoding)
# Insert atom:link after <rss>
atom_link = f'<atom:link href="{self._feed_url}" rel="self" type="application/rss+xml" />'
rss_open = '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">'
feed_str = feed_str.replace(rss_open, rss_open + '\n' + atom_link, 1)
return feed_str


class EventRSSView(APIView):
permission_classes = [AllowAny]

def get(self, request: Request) -> HttpResponse:
now = timezone.now()
events = Event.objects.filter(
start_dt__gt=now,
visibility_from_dt__lte=now,
visibility_to_dt__gte=now,
status=EventStatus.PUBLIC,
).order_by('start_dt')[:20]

feed = SamfundetRssFeed(
title='Samfundet Events',
link=request.build_absolute_uri('/'),
description='Upcoming public Samfundet events',
language='en',
feed_url=request.build_absolute_uri(), # Add feed_url for atom:link
)

for event in events:
event_url = request.build_absolute_uri(reverse('samfundet:events-detail', args=[event.pk]))
feed.add_item(
title=event.title_nb,
link=event_url,
description=event.description_short_nb or event.description_short_en,
pubdate=event.start_dt,
unique_id=event_url, # Use full URL as GUID
)

return HttpResponse(feed.writeString('utf-8'), content_type='application/rss+xml; charset=utf-8')