id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
19,776
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config from users.models import Identity, IdentityStates from users.services import IdentityService from users.shortcuts import by_handle_or_404 The provided code snippet includes necessary dependencies for implementing the `accounts_search` function. Write a Python function `def accounts_search( request, q: str, resolve: bool = False, following: bool = False, limit: int = 20, offset: int = 0, ) -> list[schemas.Account]` to solve the following problem: Handles searching for accounts by username or handle Here is the function: def accounts_search( request, q: str, resolve: bool = False, following: bool = False, limit: int = 20, offset: int = 0, ) -> list[schemas.Account]: """ Handles searching for accounts by username or handle """ if limit > 40: limit = 40 if offset: return [] searcher = SearchService(q, request.identity) search_result = searcher.search_identities_handle() return [schemas.Account.from_identity(i) for i in search_result]
Handles searching for accounts by username or handle
19,777
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config from users.models import Identity, IdentityStates from users.services import IdentityService from users.shortcuts import by_handle_or_404 def by_handle_or_404(request, handle, local=True, fetch=False) -> Identity: """ Retrieves an Identity by its long or short handle. Domain-sensitive, so it will understand short handles on alternate domains. """ if "@" not in handle: if "host" not in request.headers: raise Http404("No hostname available") username = handle domain_instance = Domain.get_domain(request.headers["host"]) if domain_instance is None: raise Http404("No matching domains found") domain = domain_instance.domain else: username, domain = handle.split("@", 1) if not Domain.is_valid_domain(domain): raise Http404("Invalid domain") # Resolve the domain to the display domain domain_instance = Domain.get_domain(domain) if domain_instance is None: domain_instance = Domain.get_remote_domain(domain) domain = domain_instance.domain identity = Identity.by_username_and_domain( username, domain_instance, local=local, fetch=fetch, ) if identity is None: raise Http404(f"No identity for handle {handle}") if identity.blocked: raise Http404("Blocked user") return identity The provided code snippet includes necessary dependencies for implementing the `lookup` function. Write a Python function `def lookup(request: HttpRequest, acct: str) -> schemas.Account` to solve the following problem: Quickly lookup a username to see if it is available, skipping WebFinger resolution. Here is the function: def lookup(request: HttpRequest, acct: str) -> schemas.Account: """ Quickly lookup a username to see if it is available, skipping WebFinger resolution. """ identity = by_handle_or_404(request, handle=acct, local=False) return schemas.Account.from_identity(identity)
Quickly lookup a username to see if it is available, skipping WebFinger resolution.
19,778
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config from users.models import Identity, IdentityStates from users.services import IdentityService from users.shortcuts import by_handle_or_404 def account(request, id: str) -> schemas.Account: identity = get_object_or_404( Identity.objects.exclude(restriction=Identity.Restriction.blocked), pk=id, ) return schemas.Account.from_identity(identity)
null
19,779
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config from users.models import Identity, IdentityStates from users.services import IdentityService from users.shortcuts import by_handle_or_404 class PaginatingApiResponse(ApiResponse[list[TI]]): """ An ApiResponse subclass that also handles pagination link headers """ def __init__( self, data: list[TI], request: HttpRequest, include_params: list[str], **kwargs, ): # Call superclass super().__init__(data, **kwargs) # Figure out if we need link headers self._request = request self.extra_params = self.filter_params(self._request, include_params) link_header = self.build_link_header() if link_header: self.headers["link"] = link_header def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params def get_part(self, data_index: int, param_name: str, rel: str) -> str | None: """ Used to get next/prev URLs """ if not self.data: return None # Use the ID of the last object for the next page start params = dict(self.extra_params) params[param_name] = self.data[data_index].id return ( "<" + self._request.build_absolute_uri(self._request.path) + "?" + urllib.parse.urlencode(params) + f'>; rel="{rel}"' ) def build_link_header(self): parts = [ entry for entry in [ self.get_part(-1, "max_id", "next"), self.get_part(0, "min_id", "prev"), ] if entry ] if not parts: return None return ", ".join(parts) class PaginationResult(Generic[T]): """ Represents a pagination result for Mastodon (it does Link header stuff) """ #: A list of objects that matched the pagination query. results: list[T] #: The actual applied limit, which may be different from what was requested. limit: int #: A list of transformed JSON objects json_results: list[dict] | None = None def empty(cls): return cls(results=[], limit=20) def next(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the next page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["max_id"] = self.json_results[-1]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def prev(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the previous page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["min_id"] = self.json_results[0]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def link_header(self, request: HttpRequest, allowed_params: list[str]): """ Creates a link header for the given request """ return ", ".join( ( f'<{self.next(request, allowed_params)}>; rel="next"', f'<{self.prev(request, allowed_params)}>; rel="prev"', ) ) def jsonify_results(self, map_function: Callable[[Any], Any]): """ Replaces our results with ones transformed via map_function """ self.json_results = [map_function(result) for result in self.results] def jsonify_posts(self, identity): """ Predefined way of JSON-ifying Post objects """ interactions = PostInteraction.get_post_interactions(self.results, identity) self.jsonify_results( lambda post: post.to_mastodon_json( interactions=interactions, identity=identity ) ) def jsonify_status_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing statuses """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_status_json( interactions=interactions, identity=identity ) ) def jsonify_notification_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing notifications """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_notification_json(interactions=interactions) ) def jsonify_identities(self): """ Predefined way of JSON-ifying Identity objects """ self.jsonify_results(lambda identity: identity.to_mastodon_json()) def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params class MastodonPaginator: """ Paginates in the Mastodon style (max_id, min_id, etc). Note that this basically _requires_ us to always do it on IDs, so we do. """ def __init__( self, default_limit: int = 20, max_limit: int = 40, ): self.default_limit = default_limit self.max_limit = max_limit def paginate( self, queryset: models.QuerySet[TM], min_id: str | None, max_id: str | None, since_id: str | None, limit: int | None, home: bool = False, ) -> PaginationResult[TM]: limit = min(limit or self.default_limit, self.max_limit) filters = {} id_field = "id" reverse = False if home: # The home timeline interleaves Post IDs and PostInteraction IDs in an # annotated field called "subject_id". id_field = "subject_id" queryset = queryset.annotate( subject_id=Case( When(type=TimelineEvent.Types.post, then=F("subject_post_id")), default=F("subject_post_interaction"), ) ) # These "does not start with interaction" checks can be removed after a # couple months, when clients have flushed them out. if max_id and not max_id.startswith("interaction"): filters[f"{id_field}__lt"] = max_id if since_id and not since_id.startswith("interaction"): filters[f"{id_field}__gt"] = since_id if min_id and not min_id.startswith("interaction"): # Min ID requires items _immediately_ newer than specified, so we # invert the ordering to accommodate filters[f"{id_field}__gt"] = min_id reverse = True # Default is to order by ID descending (newest first), except for min_id # queries, which should order by ID for limiting, then reverse the results to be # consistent. The clearest explanation of this I've found so far is this: # https://mastodon.social/@Gargron/100846335353411164 ordering = id_field if reverse else f"-{id_field}" results = list(queryset.filter(**filters).order_by(ordering)[:limit]) if reverse: results.reverse() return PaginationResult( results=results, limit=limit, ) def account_statuses( request: HttpRequest, id: str, exclude_reblogs: bool = False, exclude_replies: bool = False, only_media: bool = False, pinned: bool = False, tagged: str | None = None, max_id: str | None = None, since_id: str | None = None, min_id: str | None = None, limit: int = 20, ) -> ApiResponse[list[schemas.Status]]: identity = get_object_or_404( Identity.objects.exclude(restriction=Identity.Restriction.blocked), pk=id ) queryset = ( identity.posts.not_hidden() .unlisted(include_replies=not exclude_replies) .select_related("author", "author__domain") .prefetch_related( "attachments", "mentions__domain", "emojis", "author__inbound_follows", "author__outbound_follows", "author__posts", ) .order_by("-created") ) if pinned: queryset = queryset.filter( interactions__type=PostInteraction.Types.pin, interactions__state__in=PostInteractionStates.group_active(), ) if only_media: queryset = queryset.filter(attachments__pk__isnull=False) if tagged: queryset = queryset.tagged_with(tagged) # Get user posts with pagination paginator = MastodonPaginator() pager: PaginationResult[Post] = paginator.paginate( queryset, min_id=min_id, max_id=max_id, since_id=since_id, limit=limit, ) return PaginatingApiResponse( schemas.Status.map_from_post(pager.results, request.identity), request=request, include_params=[ "limit", "id", "exclude_reblogs", "exclude_replies", "only_media", "pinned", "tagged", ], )
null
19,780
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config from users.models import Identity, IdentityStates from users.services import IdentityService from users.shortcuts import by_handle_or_404 def account_follow(request, id: str, reblogs: bool = True) -> schemas.Relationship: identity = get_object_or_404( Identity.objects.exclude(restriction=Identity.Restriction.blocked), pk=id ) service = IdentityService(request.identity) service.follow(identity, boosts=reblogs) return schemas.Relationship.from_identity_pair(identity, request.identity)
null
19,781
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config from users.models import Identity, IdentityStates from users.services import IdentityService from users.shortcuts import by_handle_or_404 def account_unfollow(request, id: str) -> schemas.Relationship: identity = get_object_or_404( Identity.objects.exclude(restriction=Identity.Restriction.blocked), pk=id ) service = IdentityService(request.identity) service.unfollow(identity) return schemas.Relationship.from_identity_pair(identity, request.identity)
null
19,782
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config from users.models import Identity, IdentityStates from users.services import IdentityService from users.shortcuts import by_handle_or_404 def account_block(request, id: str) -> schemas.Relationship: identity = get_object_or_404(Identity, pk=id) service = IdentityService(request.identity) service.block(identity) return schemas.Relationship.from_identity_pair(identity, request.identity)
null
19,783
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config from users.models import Identity, IdentityStates from users.services import IdentityService from users.shortcuts import by_handle_or_404 def account_unblock(request, id: str) -> schemas.Relationship: identity = get_object_or_404(Identity, pk=id) service = IdentityService(request.identity) service.unblock(identity) return schemas.Relationship.from_identity_pair(identity, request.identity)
null
19,784
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config from users.models import Identity, IdentityStates from users.services import IdentityService from users.shortcuts import by_handle_or_404 def account_mute( request, id: str, notifications: QueryOrBody[bool] = True, duration: QueryOrBody[int] = 0, ) -> schemas.Relationship: identity = get_object_or_404(Identity, pk=id) service = IdentityService(request.identity) service.mute( identity, duration=duration, include_notifications=notifications, ) return schemas.Relationship.from_identity_pair(identity, request.identity)
null
19,785
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config from users.models import Identity, IdentityStates from users.services import IdentityService from users.shortcuts import by_handle_or_404 def account_unmute(request, id: str) -> schemas.Relationship: identity = get_object_or_404(Identity, pk=id) service = IdentityService(request.identity) service.unmute(identity) return schemas.Relationship.from_identity_pair(identity, request.identity)
null
19,786
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config from users.models import Identity, IdentityStates from users.services import IdentityService from users.shortcuts import by_handle_or_404 class PaginatingApiResponse(ApiResponse[list[TI]]): """ An ApiResponse subclass that also handles pagination link headers """ def __init__( self, data: list[TI], request: HttpRequest, include_params: list[str], **kwargs, ): # Call superclass super().__init__(data, **kwargs) # Figure out if we need link headers self._request = request self.extra_params = self.filter_params(self._request, include_params) link_header = self.build_link_header() if link_header: self.headers["link"] = link_header def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params def get_part(self, data_index: int, param_name: str, rel: str) -> str | None: """ Used to get next/prev URLs """ if not self.data: return None # Use the ID of the last object for the next page start params = dict(self.extra_params) params[param_name] = self.data[data_index].id return ( "<" + self._request.build_absolute_uri(self._request.path) + "?" + urllib.parse.urlencode(params) + f'>; rel="{rel}"' ) def build_link_header(self): parts = [ entry for entry in [ self.get_part(-1, "max_id", "next"), self.get_part(0, "min_id", "prev"), ] if entry ] if not parts: return None return ", ".join(parts) class PaginationResult(Generic[T]): """ Represents a pagination result for Mastodon (it does Link header stuff) """ #: A list of objects that matched the pagination query. results: list[T] #: The actual applied limit, which may be different from what was requested. limit: int #: A list of transformed JSON objects json_results: list[dict] | None = None def empty(cls): return cls(results=[], limit=20) def next(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the next page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["max_id"] = self.json_results[-1]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def prev(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the previous page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["min_id"] = self.json_results[0]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def link_header(self, request: HttpRequest, allowed_params: list[str]): """ Creates a link header for the given request """ return ", ".join( ( f'<{self.next(request, allowed_params)}>; rel="next"', f'<{self.prev(request, allowed_params)}>; rel="prev"', ) ) def jsonify_results(self, map_function: Callable[[Any], Any]): """ Replaces our results with ones transformed via map_function """ self.json_results = [map_function(result) for result in self.results] def jsonify_posts(self, identity): """ Predefined way of JSON-ifying Post objects """ interactions = PostInteraction.get_post_interactions(self.results, identity) self.jsonify_results( lambda post: post.to_mastodon_json( interactions=interactions, identity=identity ) ) def jsonify_status_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing statuses """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_status_json( interactions=interactions, identity=identity ) ) def jsonify_notification_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing notifications """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_notification_json(interactions=interactions) ) def jsonify_identities(self): """ Predefined way of JSON-ifying Identity objects """ self.jsonify_results(lambda identity: identity.to_mastodon_json()) def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params class MastodonPaginator: """ Paginates in the Mastodon style (max_id, min_id, etc). Note that this basically _requires_ us to always do it on IDs, so we do. """ def __init__( self, default_limit: int = 20, max_limit: int = 40, ): self.default_limit = default_limit self.max_limit = max_limit def paginate( self, queryset: models.QuerySet[TM], min_id: str | None, max_id: str | None, since_id: str | None, limit: int | None, home: bool = False, ) -> PaginationResult[TM]: limit = min(limit or self.default_limit, self.max_limit) filters = {} id_field = "id" reverse = False if home: # The home timeline interleaves Post IDs and PostInteraction IDs in an # annotated field called "subject_id". id_field = "subject_id" queryset = queryset.annotate( subject_id=Case( When(type=TimelineEvent.Types.post, then=F("subject_post_id")), default=F("subject_post_interaction"), ) ) # These "does not start with interaction" checks can be removed after a # couple months, when clients have flushed them out. if max_id and not max_id.startswith("interaction"): filters[f"{id_field}__lt"] = max_id if since_id and not since_id.startswith("interaction"): filters[f"{id_field}__gt"] = since_id if min_id and not min_id.startswith("interaction"): # Min ID requires items _immediately_ newer than specified, so we # invert the ordering to accommodate filters[f"{id_field}__gt"] = min_id reverse = True # Default is to order by ID descending (newest first), except for min_id # queries, which should order by ID for limiting, then reverse the results to be # consistent. The clearest explanation of this I've found so far is this: # https://mastodon.social/@Gargron/100846335353411164 ordering = id_field if reverse else f"-{id_field}" results = list(queryset.filter(**filters).order_by(ordering)[:limit]) if reverse: results.reverse() return PaginationResult( results=results, limit=limit, ) def account_following( request: HttpRequest, id: str, max_id: str | None = None, since_id: str | None = None, min_id: str | None = None, limit: int = 40, ) -> ApiResponse[list[schemas.Account]]: identity = get_object_or_404( Identity.objects.exclude(restriction=Identity.Restriction.blocked), pk=id ) if not identity.config_identity.visible_follows and request.identity != identity: return ApiResponse([]) service = IdentityService(identity) paginator = MastodonPaginator(max_limit=80) pager: PaginationResult[Identity] = paginator.paginate( service.following(), min_id=min_id, max_id=max_id, since_id=since_id, limit=limit, ) return PaginatingApiResponse( [schemas.Account.from_identity(i) for i in pager.results], request=request, include_params=["limit"], )
null
19,787
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config from users.models import Identity, IdentityStates from users.services import IdentityService from users.shortcuts import by_handle_or_404 class PaginatingApiResponse(ApiResponse[list[TI]]): """ An ApiResponse subclass that also handles pagination link headers """ def __init__( self, data: list[TI], request: HttpRequest, include_params: list[str], **kwargs, ): # Call superclass super().__init__(data, **kwargs) # Figure out if we need link headers self._request = request self.extra_params = self.filter_params(self._request, include_params) link_header = self.build_link_header() if link_header: self.headers["link"] = link_header def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params def get_part(self, data_index: int, param_name: str, rel: str) -> str | None: """ Used to get next/prev URLs """ if not self.data: return None # Use the ID of the last object for the next page start params = dict(self.extra_params) params[param_name] = self.data[data_index].id return ( "<" + self._request.build_absolute_uri(self._request.path) + "?" + urllib.parse.urlencode(params) + f'>; rel="{rel}"' ) def build_link_header(self): parts = [ entry for entry in [ self.get_part(-1, "max_id", "next"), self.get_part(0, "min_id", "prev"), ] if entry ] if not parts: return None return ", ".join(parts) class PaginationResult(Generic[T]): """ Represents a pagination result for Mastodon (it does Link header stuff) """ #: A list of objects that matched the pagination query. results: list[T] #: The actual applied limit, which may be different from what was requested. limit: int #: A list of transformed JSON objects json_results: list[dict] | None = None def empty(cls): return cls(results=[], limit=20) def next(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the next page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["max_id"] = self.json_results[-1]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def prev(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the previous page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["min_id"] = self.json_results[0]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def link_header(self, request: HttpRequest, allowed_params: list[str]): """ Creates a link header for the given request """ return ", ".join( ( f'<{self.next(request, allowed_params)}>; rel="next"', f'<{self.prev(request, allowed_params)}>; rel="prev"', ) ) def jsonify_results(self, map_function: Callable[[Any], Any]): """ Replaces our results with ones transformed via map_function """ self.json_results = [map_function(result) for result in self.results] def jsonify_posts(self, identity): """ Predefined way of JSON-ifying Post objects """ interactions = PostInteraction.get_post_interactions(self.results, identity) self.jsonify_results( lambda post: post.to_mastodon_json( interactions=interactions, identity=identity ) ) def jsonify_status_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing statuses """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_status_json( interactions=interactions, identity=identity ) ) def jsonify_notification_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing notifications """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_notification_json(interactions=interactions) ) def jsonify_identities(self): """ Predefined way of JSON-ifying Identity objects """ self.jsonify_results(lambda identity: identity.to_mastodon_json()) def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params class MastodonPaginator: """ Paginates in the Mastodon style (max_id, min_id, etc). Note that this basically _requires_ us to always do it on IDs, so we do. """ def __init__( self, default_limit: int = 20, max_limit: int = 40, ): self.default_limit = default_limit self.max_limit = max_limit def paginate( self, queryset: models.QuerySet[TM], min_id: str | None, max_id: str | None, since_id: str | None, limit: int | None, home: bool = False, ) -> PaginationResult[TM]: limit = min(limit or self.default_limit, self.max_limit) filters = {} id_field = "id" reverse = False if home: # The home timeline interleaves Post IDs and PostInteraction IDs in an # annotated field called "subject_id". id_field = "subject_id" queryset = queryset.annotate( subject_id=Case( When(type=TimelineEvent.Types.post, then=F("subject_post_id")), default=F("subject_post_interaction"), ) ) # These "does not start with interaction" checks can be removed after a # couple months, when clients have flushed them out. if max_id and not max_id.startswith("interaction"): filters[f"{id_field}__lt"] = max_id if since_id and not since_id.startswith("interaction"): filters[f"{id_field}__gt"] = since_id if min_id and not min_id.startswith("interaction"): # Min ID requires items _immediately_ newer than specified, so we # invert the ordering to accommodate filters[f"{id_field}__gt"] = min_id reverse = True # Default is to order by ID descending (newest first), except for min_id # queries, which should order by ID for limiting, then reverse the results to be # consistent. The clearest explanation of this I've found so far is this: # https://mastodon.social/@Gargron/100846335353411164 ordering = id_field if reverse else f"-{id_field}" results = list(queryset.filter(**filters).order_by(ordering)[:limit]) if reverse: results.reverse() return PaginationResult( results=results, limit=limit, ) def account_followers( request: HttpRequest, id: str, max_id: str | None = None, since_id: str | None = None, min_id: str | None = None, limit: int = 40, ) -> ApiResponse[list[schemas.Account]]: identity = get_object_or_404( Identity.objects.exclude(restriction=Identity.Restriction.blocked), pk=id ) if not identity.config_identity.visible_follows and request.identity != identity: return ApiResponse([]) service = IdentityService(identity) paginator = MastodonPaginator(max_limit=80) pager: PaginationResult[Identity] = paginator.paginate( service.followers(), min_id=min_id, max_id=max_id, since_id=since_id, limit=limit, ) return PaginatingApiResponse( [schemas.Account.from_identity(i) for i in pager.results], request=request, include_params=["limit"], )
null
19,788
from typing import Any from django.core.files import File from django.http import HttpRequest from django.shortcuts import get_object_or_404 from hatchway import ApiResponse, QueryOrBody, api_view from activities.models import Post, PostInteraction, PostInteractionStates from activities.services import SearchService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config from users.models import Identity, IdentityStates from users.services import IdentityService from users.shortcuts import by_handle_or_404 def account_featured_tags(request: HttpRequest, id: str) -> list[schemas.FeaturedTag]: # Not implemented yet return []
null
19,789
from django.shortcuts import get_object_or_404 from hatchway import api_view from api import schemas from api.decorators import scope_required from users.models import Announcement from users.services import AnnouncementService def announcement_list(request) -> list[schemas.Announcement]: return [ schemas.Announcement.from_announcement(a, request.user) for a in AnnouncementService(request.user).visible() ]
null
19,790
from django.shortcuts import get_object_or_404 from hatchway import api_view from api import schemas from api.decorators import scope_required from users.models import Announcement from users.services import AnnouncementService def announcement_dismiss(request, pk: str): announcement = get_object_or_404(Announcement, pk=pk) AnnouncementService(request.user).mark_seen(announcement)
null
19,791
from hatchway import api_view from api.decorators import identity_required def list_filters(request): return []
null
19,792
from django.conf import settings from django.http import Http404 from hatchway import ApiError, QueryOrBody, api_view from api import schemas from api.decorators import scope_required def create_subscription( request, subscription: QueryOrBody[schemas.PushSubscriptionCreation], data: QueryOrBody[schemas.PushData], ) -> schemas.PushSubscription: # First, check the server is set up to do push notifications if not settings.SETUP.VAPID_PRIVATE_KEY: raise Http404("Push not available") # Then, register this with our token request.token.set_push_subscription( { "endpoint": subscription.endpoint, "keys": subscription.keys, "alerts": data.alerts, "policy": data.policy, } ) # Then return the subscription return schemas.PushSubscription.from_token(request.token) # type:ignore
null
19,793
from django.conf import settings from django.http import Http404 from hatchway import ApiError, QueryOrBody, api_view from api import schemas from api.decorators import scope_required def get_subscription(request) -> schemas.PushSubscription: # First, check the server is set up to do push notifications if not settings.SETUP.VAPID_PRIVATE_KEY: raise Http404("Push not available") # Get the subscription if it exists subscription = schemas.PushSubscription.from_token(request.token) if not subscription: raise ApiError(404, "Not Found") return subscription
null
19,794
from django.conf import settings from django.http import Http404 from hatchway import ApiError, QueryOrBody, api_view from api import schemas from api.decorators import scope_required def update_subscription( request, data: QueryOrBody[schemas.PushData] ) -> schemas.PushSubscription: # First, check the server is set up to do push notifications if not settings.SETUP.VAPID_PRIVATE_KEY: raise Http404("Push not available") # Get the subscription if it exists subscription = schemas.PushSubscription.from_token(request.token) if not subscription: raise ApiError(404, "Not Found") # Update the subscription subscription.alerts = data.alerts subscription.policy = data.policy request.token.set_push_subscription(subscription) # Then return the subscription return schemas.PushSubscription.from_token(request.token) # type:ignore
null
19,795
from django.conf import settings from django.http import Http404 from hatchway import ApiError, QueryOrBody, api_view from api import schemas from api.decorators import scope_required def delete_subscription(request) -> dict: # Unset the subscription request.token.push_subscription = None return {}
null
19,796
from typing import Literal from hatchway import Field, api_view from activities.models import PostInteraction from activities.services.search import SearchService from api import schemas from api.decorators import scope_required class SearchService: """ Captures the logic needed to search - reused in the UI and API """ def __init__(self, query: str, identity: Identity | None): self.query = query.strip() self.identity = identity def search_identities_handle(self) -> set[Identity]: """ Searches for identities by their handles """ # Short circuit if it's obviously not for us if "://" in self.query: return set() # Try to fetch the user by handle handle = self.query.lstrip("@") results: set[Identity] = set() if "@" in handle: username, domain = handle.split("@", 1) # Resolve the domain to the display domain domain_instance = Domain.get_domain(domain) try: if domain_instance is None: raise Identity.DoesNotExist() identity = Identity.objects.get( domain=domain_instance, username__iexact=username, ) except Identity.DoesNotExist: identity = None if self.identity is not None: try: # Allow authenticated users to fetch remote identity = Identity.by_username_and_domain( username, domain_instance or domain, fetch=True ) if identity and identity.state == IdentityStates.outdated: identity.fetch_actor() except ValueError: pass if identity: results.add(identity) else: for identity in Identity.objects.filter(username=handle)[:20]: results.add(identity) for identity in Identity.objects.filter(username__istartswith=handle)[:20]: results.add(identity) return results def search_url(self) -> Post | Identity | None: """ Searches for an identity or post by URL. """ # Short circuit if it's obviously not for us if "://" not in self.query: return None # Fetch the provided URL as the system actor to retrieve the AP JSON try: response = SystemActor().signed_request( method="get", uri=self.query, ) except httpx.RequestError: return None if response.status_code >= 400: return None json_data = json_from_response(response) if not json_data: return None document = canonicalise(json_data, include_security=True) type = document.get("type", "unknown").lower() # Is it an identity? if type in Identity.ACTOR_TYPES: # Try and retrieve the profile by actor URI identity = Identity.by_actor_uri(document["id"], create=True) if identity and identity.state == IdentityStates.outdated: identity.fetch_actor() return identity # Is it a post? elif type in [value.lower() for value in Post.Types.values]: # Try and retrieve the post by URI # (we do not trust the JSON we just got - fetch from source!) try: return Post.by_object_uri(document["id"], fetch=True) except Post.DoesNotExist: return None # Dunno what it is else: return None def search_hashtags(self) -> set[Hashtag]: """ Searches for hashtags by their name """ # Short circuit out if it's obviously not a hashtag if "@" in self.query or "://" in self.query: return set() results: set[Hashtag] = set() name = self.query.lstrip("#").lower() for hashtag in Hashtag.objects.public().hashtag_or_alias(name)[:10]: results.add(hashtag) for hashtag in Hashtag.objects.public().filter(hashtag__startswith=name)[:10]: results.add(hashtag) return results def search_post_content(self): """ Searches for posts on an identity via full text search """ return self.identity.posts.unlisted(include_replies=True).filter( content__search=self.query )[:50] def search_all(self): """ Returns all possible results for a search """ results = { "identities": self.search_identities_handle(), "hashtags": self.search_hashtags(), "posts": set(), } url_result = self.search_url() if isinstance(url_result, Identity): results["identities"].add(url_result) if isinstance(url_result, Post): results["posts"].add(url_result) return results def search( request, q: str, type: Literal["accounts", "hashtags", "statuses", ""] | None = None, fetch_identities: bool = Field(False, alias="resolve"), following: bool = False, exclude_unreviewed: bool = False, account_id: str | None = None, max_id: str | None = None, since_id: str | None = None, min_id: str | None = None, limit: int = 20, offset: int = 0, ) -> schemas.Search: if limit > 40: limit = 40 result: dict[str, list] = {"accounts": [], "statuses": [], "hashtags": []} # We don't support pagination for searches yet if max_id or since_id or min_id or offset: return schemas.Search(**result) # Run search searcher = SearchService(q, request.identity) search_result = searcher.search_all() if type == "": type = None if type is None or type == "accounts": result["accounts"] = [ schemas.Account.from_identity(i, include_counts=False) for i in search_result["identities"] ] if type is None or type == "hashtag": result["hashtags"] = [ schemas.Tag.from_hashtag(h) for h in search_result["hashtags"] ] if type is None or type == "statuses": interactions = PostInteraction.get_post_interactions( search_result["posts"], request.identity ) result["statuses"] = [ schemas.Status.from_post( p, interactions=interactions, identity=request.identity ) for p in search_result["posts"] ] return schemas.Search(**result)
null
19,797
from django.http import HttpRequest from hatchway import api_view from api import schemas from api.decorators import scope_required def preferences(request: HttpRequest) -> dict: # Ideally this should just return Preferences; maybe hatchway needs a way to # indicate response models should be serialized by alias? return schemas.Preferences.from_identity(request.identity).dict(by_alias=True)
null
19,798
from django.http import HttpRequest from hatchway import ApiError, ApiResponse, api_view from activities.models import Post, TimelineEvent from activities.services import TimelineService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config class PaginatingApiResponse(ApiResponse[list[TI]]): """ An ApiResponse subclass that also handles pagination link headers """ def __init__( self, data: list[TI], request: HttpRequest, include_params: list[str], **kwargs, ): # Call superclass super().__init__(data, **kwargs) # Figure out if we need link headers self._request = request self.extra_params = self.filter_params(self._request, include_params) link_header = self.build_link_header() if link_header: self.headers["link"] = link_header def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params def get_part(self, data_index: int, param_name: str, rel: str) -> str | None: """ Used to get next/prev URLs """ if not self.data: return None # Use the ID of the last object for the next page start params = dict(self.extra_params) params[param_name] = self.data[data_index].id return ( "<" + self._request.build_absolute_uri(self._request.path) + "?" + urllib.parse.urlencode(params) + f'>; rel="{rel}"' ) def build_link_header(self): parts = [ entry for entry in [ self.get_part(-1, "max_id", "next"), self.get_part(0, "min_id", "prev"), ] if entry ] if not parts: return None return ", ".join(parts) class PaginationResult(Generic[T]): """ Represents a pagination result for Mastodon (it does Link header stuff) """ #: A list of objects that matched the pagination query. results: list[T] #: The actual applied limit, which may be different from what was requested. limit: int #: A list of transformed JSON objects json_results: list[dict] | None = None def empty(cls): return cls(results=[], limit=20) def next(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the next page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["max_id"] = self.json_results[-1]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def prev(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the previous page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["min_id"] = self.json_results[0]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def link_header(self, request: HttpRequest, allowed_params: list[str]): """ Creates a link header for the given request """ return ", ".join( ( f'<{self.next(request, allowed_params)}>; rel="next"', f'<{self.prev(request, allowed_params)}>; rel="prev"', ) ) def jsonify_results(self, map_function: Callable[[Any], Any]): """ Replaces our results with ones transformed via map_function """ self.json_results = [map_function(result) for result in self.results] def jsonify_posts(self, identity): """ Predefined way of JSON-ifying Post objects """ interactions = PostInteraction.get_post_interactions(self.results, identity) self.jsonify_results( lambda post: post.to_mastodon_json( interactions=interactions, identity=identity ) ) def jsonify_status_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing statuses """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_status_json( interactions=interactions, identity=identity ) ) def jsonify_notification_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing notifications """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_notification_json(interactions=interactions) ) def jsonify_identities(self): """ Predefined way of JSON-ifying Identity objects """ self.jsonify_results(lambda identity: identity.to_mastodon_json()) def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params class MastodonPaginator: """ Paginates in the Mastodon style (max_id, min_id, etc). Note that this basically _requires_ us to always do it on IDs, so we do. """ def __init__( self, default_limit: int = 20, max_limit: int = 40, ): self.default_limit = default_limit self.max_limit = max_limit def paginate( self, queryset: models.QuerySet[TM], min_id: str | None, max_id: str | None, since_id: str | None, limit: int | None, home: bool = False, ) -> PaginationResult[TM]: limit = min(limit or self.default_limit, self.max_limit) filters = {} id_field = "id" reverse = False if home: # The home timeline interleaves Post IDs and PostInteraction IDs in an # annotated field called "subject_id". id_field = "subject_id" queryset = queryset.annotate( subject_id=Case( When(type=TimelineEvent.Types.post, then=F("subject_post_id")), default=F("subject_post_interaction"), ) ) # These "does not start with interaction" checks can be removed after a # couple months, when clients have flushed them out. if max_id and not max_id.startswith("interaction"): filters[f"{id_field}__lt"] = max_id if since_id and not since_id.startswith("interaction"): filters[f"{id_field}__gt"] = since_id if min_id and not min_id.startswith("interaction"): # Min ID requires items _immediately_ newer than specified, so we # invert the ordering to accommodate filters[f"{id_field}__gt"] = min_id reverse = True # Default is to order by ID descending (newest first), except for min_id # queries, which should order by ID for limiting, then reverse the results to be # consistent. The clearest explanation of this I've found so far is this: # https://mastodon.social/@Gargron/100846335353411164 ordering = id_field if reverse else f"-{id_field}" results = list(queryset.filter(**filters).order_by(ordering)[:limit]) if reverse: results.reverse() return PaginationResult( results=results, limit=limit, ) def home( request: HttpRequest, max_id: str | None = None, since_id: str | None = None, min_id: str | None = None, limit: int = 20, ) -> ApiResponse[list[schemas.Status]]: # Grab a paginated result set of instances paginator = MastodonPaginator() queryset = TimelineService(request.identity).home() queryset = queryset.select_related( "subject_post_interaction__post", "subject_post_interaction__post__author", "subject_post_interaction__post__author__domain", ) queryset = queryset.prefetch_related( "subject_post__mentions__domain", "subject_post_interaction__post__attachments", "subject_post_interaction__post__mentions", "subject_post_interaction__post__emojis", "subject_post_interaction__post__mentions__domain", "subject_post_interaction__post__author__posts", ) pager: PaginationResult[TimelineEvent] = paginator.paginate( queryset, min_id=min_id, max_id=max_id, since_id=since_id, limit=limit, home=True, ) return PaginatingApiResponse( schemas.Status.map_from_timeline_event(pager.results, request.identity), request=request, include_params=["limit"], )
null
19,799
from django.http import HttpRequest from hatchway import ApiError, ApiResponse, api_view from activities.models import Post, TimelineEvent from activities.services import TimelineService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config class PaginatingApiResponse(ApiResponse[list[TI]]): """ An ApiResponse subclass that also handles pagination link headers """ def __init__( self, data: list[TI], request: HttpRequest, include_params: list[str], **kwargs, ): # Call superclass super().__init__(data, **kwargs) # Figure out if we need link headers self._request = request self.extra_params = self.filter_params(self._request, include_params) link_header = self.build_link_header() if link_header: self.headers["link"] = link_header def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params def get_part(self, data_index: int, param_name: str, rel: str) -> str | None: """ Used to get next/prev URLs """ if not self.data: return None # Use the ID of the last object for the next page start params = dict(self.extra_params) params[param_name] = self.data[data_index].id return ( "<" + self._request.build_absolute_uri(self._request.path) + "?" + urllib.parse.urlencode(params) + f'>; rel="{rel}"' ) def build_link_header(self): parts = [ entry for entry in [ self.get_part(-1, "max_id", "next"), self.get_part(0, "min_id", "prev"), ] if entry ] if not parts: return None return ", ".join(parts) class PaginationResult(Generic[T]): """ Represents a pagination result for Mastodon (it does Link header stuff) """ #: A list of objects that matched the pagination query. results: list[T] #: The actual applied limit, which may be different from what was requested. limit: int #: A list of transformed JSON objects json_results: list[dict] | None = None def empty(cls): return cls(results=[], limit=20) def next(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the next page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["max_id"] = self.json_results[-1]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def prev(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the previous page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["min_id"] = self.json_results[0]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def link_header(self, request: HttpRequest, allowed_params: list[str]): """ Creates a link header for the given request """ return ", ".join( ( f'<{self.next(request, allowed_params)}>; rel="next"', f'<{self.prev(request, allowed_params)}>; rel="prev"', ) ) def jsonify_results(self, map_function: Callable[[Any], Any]): """ Replaces our results with ones transformed via map_function """ self.json_results = [map_function(result) for result in self.results] def jsonify_posts(self, identity): """ Predefined way of JSON-ifying Post objects """ interactions = PostInteraction.get_post_interactions(self.results, identity) self.jsonify_results( lambda post: post.to_mastodon_json( interactions=interactions, identity=identity ) ) def jsonify_status_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing statuses """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_status_json( interactions=interactions, identity=identity ) ) def jsonify_notification_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing notifications """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_notification_json(interactions=interactions) ) def jsonify_identities(self): """ Predefined way of JSON-ifying Identity objects """ self.jsonify_results(lambda identity: identity.to_mastodon_json()) def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params class MastodonPaginator: """ Paginates in the Mastodon style (max_id, min_id, etc). Note that this basically _requires_ us to always do it on IDs, so we do. """ def __init__( self, default_limit: int = 20, max_limit: int = 40, ): self.default_limit = default_limit self.max_limit = max_limit def paginate( self, queryset: models.QuerySet[TM], min_id: str | None, max_id: str | None, since_id: str | None, limit: int | None, home: bool = False, ) -> PaginationResult[TM]: limit = min(limit or self.default_limit, self.max_limit) filters = {} id_field = "id" reverse = False if home: # The home timeline interleaves Post IDs and PostInteraction IDs in an # annotated field called "subject_id". id_field = "subject_id" queryset = queryset.annotate( subject_id=Case( When(type=TimelineEvent.Types.post, then=F("subject_post_id")), default=F("subject_post_interaction"), ) ) # These "does not start with interaction" checks can be removed after a # couple months, when clients have flushed them out. if max_id and not max_id.startswith("interaction"): filters[f"{id_field}__lt"] = max_id if since_id and not since_id.startswith("interaction"): filters[f"{id_field}__gt"] = since_id if min_id and not min_id.startswith("interaction"): # Min ID requires items _immediately_ newer than specified, so we # invert the ordering to accommodate filters[f"{id_field}__gt"] = min_id reverse = True # Default is to order by ID descending (newest first), except for min_id # queries, which should order by ID for limiting, then reverse the results to be # consistent. The clearest explanation of this I've found so far is this: # https://mastodon.social/@Gargron/100846335353411164 ordering = id_field if reverse else f"-{id_field}" results = list(queryset.filter(**filters).order_by(ordering)[:limit]) if reverse: results.reverse() return PaginationResult( results=results, limit=limit, ) def public( request: HttpRequest, local: bool = False, remote: bool = False, only_media: bool = False, max_id: str | None = None, since_id: str | None = None, min_id: str | None = None, limit: int = 20, ) -> ApiResponse[list[schemas.Status]]: if not request.identity and not Config.system.public_timeline: raise ApiError(error="public timeline is disabled", status=422) if local: queryset = TimelineService(request.identity).local() else: queryset = TimelineService(request.identity).federated() if remote: queryset = queryset.filter(local=False) if only_media: queryset = queryset.filter(attachments__id__isnull=True) # Grab a paginated result set of instances paginator = MastodonPaginator() pager: PaginationResult[Post] = paginator.paginate( queryset, min_id=min_id, max_id=max_id, since_id=since_id, limit=limit, ) return PaginatingApiResponse( schemas.Status.map_from_post(pager.results, request.identity), request=request, include_params=["limit", "local", "remote", "only_media"], )
null
19,800
from django.http import HttpRequest from hatchway import ApiError, ApiResponse, api_view from activities.models import Post, TimelineEvent from activities.services import TimelineService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config class PaginatingApiResponse(ApiResponse[list[TI]]): def __init__( self, data: list[TI], request: HttpRequest, include_params: list[str], **kwargs, ): def filter_params(request: HttpRequest, allowed_params: list[str]): def get_part(self, data_index: int, param_name: str, rel: str) -> str | None: def build_link_header(self): class PaginationResult(Generic[T]): def empty(cls): def next(self, request: HttpRequest, allowed_params: list[str]): def prev(self, request: HttpRequest, allowed_params: list[str]): def link_header(self, request: HttpRequest, allowed_params: list[str]): def jsonify_results(self, map_function: Callable[[Any], Any]): def jsonify_posts(self, identity): def jsonify_status_events(self, identity): def jsonify_notification_events(self, identity): def jsonify_identities(self): def filter_params(request: HttpRequest, allowed_params: list[str]): class MastodonPaginator: def __init__( self, default_limit: int = 20, max_limit: int = 40, ): def paginate( self, queryset: models.QuerySet[TM], min_id: str | None, max_id: str | None, since_id: str | None, limit: int | None, home: bool = False, ) -> PaginationResult[TM]: def hashtag( request: HttpRequest, hashtag: str, local: bool = False, only_media: bool = False, max_id: str | None = None, since_id: str | None = None, min_id: str | None = None, limit: int = 20, ) -> ApiResponse[list[schemas.Status]]: if limit > 40: limit = 40 queryset = TimelineService(request.identity).hashtag(hashtag.lower()) if local: queryset = queryset.filter(local=True) if only_media: queryset = queryset.filter(attachments__id__isnull=True) # Grab a paginated result set of instances paginator = MastodonPaginator() pager: PaginationResult[Post] = paginator.paginate( queryset, min_id=min_id, max_id=max_id, since_id=since_id, limit=limit, ) return PaginatingApiResponse( schemas.Status.map_from_post(pager.results, request.identity), request=request, include_params=["limit", "local", "remote", "only_media"], )
null
19,801
from django.http import HttpRequest from hatchway import ApiError, ApiResponse, api_view from activities.models import Post, TimelineEvent from activities.services import TimelineService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config def conversations( request: HttpRequest, max_id: str | None = None, since_id: str | None = None, min_id: str | None = None, limit: int = 20, ) -> list[schemas.Status]: # We don't implement this yet return []
null
19,802
from django.http import HttpRequest from hatchway import ApiError, ApiResponse, api_view from activities.models import Post, TimelineEvent from activities.services import TimelineService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config class PaginatingApiResponse(ApiResponse[list[TI]]): """ An ApiResponse subclass that also handles pagination link headers """ def __init__( self, data: list[TI], request: HttpRequest, include_params: list[str], **kwargs, ): # Call superclass super().__init__(data, **kwargs) # Figure out if we need link headers self._request = request self.extra_params = self.filter_params(self._request, include_params) link_header = self.build_link_header() if link_header: self.headers["link"] = link_header def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params def get_part(self, data_index: int, param_name: str, rel: str) -> str | None: """ Used to get next/prev URLs """ if not self.data: return None # Use the ID of the last object for the next page start params = dict(self.extra_params) params[param_name] = self.data[data_index].id return ( "<" + self._request.build_absolute_uri(self._request.path) + "?" + urllib.parse.urlencode(params) + f'>; rel="{rel}"' ) def build_link_header(self): parts = [ entry for entry in [ self.get_part(-1, "max_id", "next"), self.get_part(0, "min_id", "prev"), ] if entry ] if not parts: return None return ", ".join(parts) class PaginationResult(Generic[T]): """ Represents a pagination result for Mastodon (it does Link header stuff) """ #: A list of objects that matched the pagination query. results: list[T] #: The actual applied limit, which may be different from what was requested. limit: int #: A list of transformed JSON objects json_results: list[dict] | None = None def empty(cls): return cls(results=[], limit=20) def next(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the next page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["max_id"] = self.json_results[-1]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def prev(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the previous page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["min_id"] = self.json_results[0]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def link_header(self, request: HttpRequest, allowed_params: list[str]): """ Creates a link header for the given request """ return ", ".join( ( f'<{self.next(request, allowed_params)}>; rel="next"', f'<{self.prev(request, allowed_params)}>; rel="prev"', ) ) def jsonify_results(self, map_function: Callable[[Any], Any]): """ Replaces our results with ones transformed via map_function """ self.json_results = [map_function(result) for result in self.results] def jsonify_posts(self, identity): """ Predefined way of JSON-ifying Post objects """ interactions = PostInteraction.get_post_interactions(self.results, identity) self.jsonify_results( lambda post: post.to_mastodon_json( interactions=interactions, identity=identity ) ) def jsonify_status_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing statuses """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_status_json( interactions=interactions, identity=identity ) ) def jsonify_notification_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing notifications """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_notification_json(interactions=interactions) ) def jsonify_identities(self): """ Predefined way of JSON-ifying Identity objects """ self.jsonify_results(lambda identity: identity.to_mastodon_json()) def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params class MastodonPaginator: """ Paginates in the Mastodon style (max_id, min_id, etc). Note that this basically _requires_ us to always do it on IDs, so we do. """ def __init__( self, default_limit: int = 20, max_limit: int = 40, ): self.default_limit = default_limit self.max_limit = max_limit def paginate( self, queryset: models.QuerySet[TM], min_id: str | None, max_id: str | None, since_id: str | None, limit: int | None, home: bool = False, ) -> PaginationResult[TM]: limit = min(limit or self.default_limit, self.max_limit) filters = {} id_field = "id" reverse = False if home: # The home timeline interleaves Post IDs and PostInteraction IDs in an # annotated field called "subject_id". id_field = "subject_id" queryset = queryset.annotate( subject_id=Case( When(type=TimelineEvent.Types.post, then=F("subject_post_id")), default=F("subject_post_interaction"), ) ) # These "does not start with interaction" checks can be removed after a # couple months, when clients have flushed them out. if max_id and not max_id.startswith("interaction"): filters[f"{id_field}__lt"] = max_id if since_id and not since_id.startswith("interaction"): filters[f"{id_field}__gt"] = since_id if min_id and not min_id.startswith("interaction"): # Min ID requires items _immediately_ newer than specified, so we # invert the ordering to accommodate filters[f"{id_field}__gt"] = min_id reverse = True # Default is to order by ID descending (newest first), except for min_id # queries, which should order by ID for limiting, then reverse the results to be # consistent. The clearest explanation of this I've found so far is this: # https://mastodon.social/@Gargron/100846335353411164 ordering = id_field if reverse else f"-{id_field}" results = list(queryset.filter(**filters).order_by(ordering)[:limit]) if reverse: results.reverse() return PaginationResult( results=results, limit=limit, ) def favourites( request: HttpRequest, max_id: str | None = None, since_id: str | None = None, min_id: str | None = None, limit: int = 20, ) -> ApiResponse[list[schemas.Status]]: queryset = TimelineService(request.identity).likes() paginator = MastodonPaginator() pager: PaginationResult[Post] = paginator.paginate( queryset, min_id=min_id, max_id=max_id, since_id=since_id, limit=limit, ) return PaginatingApiResponse( schemas.Status.map_from_post(pager.results, request.identity), request=request, include_params=["limit"], )
null
19,803
from django.http import HttpRequest from hatchway import api_view from api import schemas from api.decorators import scope_required def suggested_users( request: HttpRequest, limit: int = 10, offset: int | None = None, ) -> list[schemas.Account]: # We don't implement this yet return []
null
19,804
import base64 import json import secrets import time from urllib.parse import urlparse, urlunparse from django.contrib.auth.mixins import LoginRequiredMixin from django.http import ( HttpResponse, HttpResponseForbidden, HttpResponseRedirect, JsonResponse, ) from django.shortcuts import render from django.utils import timezone from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.views.generic import View from api.models import Application, Authorization, Token def get_json_and_formdata(request): # Did they submit JSON? if request.content_type == "application/json" and request.body.strip(): return json.loads(request.body) # Fall back to form data value = {} for key, item in request.POST.items(): value[key] = item for key, item in request.GET.items(): value[key] = item return value
null
19,805
import base64 import json import secrets import time from urllib.parse import urlparse, urlunparse from django.contrib.auth.mixins import LoginRequiredMixin from django.http import ( HttpResponse, HttpResponseForbidden, HttpResponseRedirect, JsonResponse, ) from django.shortcuts import render from django.utils import timezone from django.utils.decorators import method_decorator from django.views.decorators.csrf import csrf_exempt from django.views.generic import View from api.models import Application, Authorization, Token def extract_client_info_from_basic_auth(request): if "authorization" in request.headers: auth = request.headers["authorization"].split() if len(auth) == 2: if auth[0].lower() == "basic": client_id, client_secret = ( base64.b64decode(auth[1]).decode("utf8").split(":", 1) ) return client_id, client_secret return None, None
null
19,806
from datetime import timedelta from typing import Literal from django.http import HttpRequest from django.shortcuts import get_object_or_404 from django.utils import timezone from hatchway import ApiError, ApiResponse, Schema, api_view from activities.models import ( Post, PostAttachment, PostInteraction, PostInteractionStates, TimelineEvent, ) from activities.services import PostService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config class PostStatusSchema(Schema): status: str | None in_reply_to_id: str | None = None sensitive: bool = False spoiler_text: str | None = None visibility: Literal["public", "unlisted", "private", "direct"] = "public" language: str | None = None scheduled_at: str | None = None media_ids: list[str] = [] poll: PostPollSchema | None = None def status(request, id: str) -> schemas.Status: post = post_for_id(request, id) interactions = PostInteraction.get_post_interactions([post], request.identity) return schemas.Status.from_post( post, interactions=interactions, identity=request.identity ) def post_status(request, details: PostStatusSchema) -> schemas.Status: # Check text length if details.status and len(details.status) > Config.system.post_length: raise ApiError(400, "Status is too long") if not details.status and not details.media_ids: raise ApiError(400, "Status is empty") # Grab attachments attachments = [get_object_or_404(PostAttachment, pk=id) for id in details.media_ids] # Create the Post visibility_map = { "public": Post.Visibilities.public, "unlisted": Post.Visibilities.unlisted, "private": Post.Visibilities.followers, "direct": Post.Visibilities.mentioned, } reply_post = None if details.in_reply_to_id: try: reply_post = Post.objects.get(pk=details.in_reply_to_id) except Post.DoesNotExist: pass post = Post.create_local( author=request.identity, content=details.status or "", summary=details.spoiler_text, sensitive=details.sensitive, visibility=visibility_map[details.visibility], reply_to=reply_post, attachments=attachments, question=details.poll.dict() if details.poll else None, ) # Add their own timeline event for immediate visibility TimelineEvent.add_post(request.identity, post) return schemas.Status.from_post(post, identity=request.identity)
null
19,807
from datetime import timedelta from typing import Literal from django.http import HttpRequest from django.shortcuts import get_object_or_404 from django.utils import timezone from hatchway import ApiError, ApiResponse, Schema, api_view from activities.models import ( Post, PostAttachment, PostInteraction, PostInteractionStates, TimelineEvent, ) from activities.services import PostService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config class EditStatusSchema(Schema): status: str sensitive: bool = False spoiler_text: str | None = None language: str | None = None media_ids: list[str] = [] media_attributes: list[MediaAttributesSchema] = [] def post_for_id(request: HttpRequest, id: str) -> Post: """ Common logic to get a Post object for an ID, taking visibility into account. """ if request.identity: queryset = Post.objects.not_hidden().visible_to( request.identity, include_replies=True ) else: queryset = Post.objects.not_hidden().unlisted() return get_object_or_404(queryset, pk=id) def status(request, id: str) -> schemas.Status: post = post_for_id(request, id) interactions = PostInteraction.get_post_interactions([post], request.identity) return schemas.Status.from_post( post, interactions=interactions, identity=request.identity ) def edit_status(request, id: str, details: EditStatusSchema) -> schemas.Status: post = post_for_id(request, id) if post.author != request.identity: raise ApiError(401, "Not the author of this status") # Grab attachments attachments = [get_object_or_404(PostAttachment, pk=id) for id in details.media_ids] # Update all details, as the client must provide them all post.edit_local( content=details.status, summary=details.spoiler_text, sensitive=details.sensitive, attachments=attachments, attachment_attributes=details.media_attributes, ) return schemas.Status.from_post(post)
null
19,808
from datetime import timedelta from typing import Literal from django.http import HttpRequest from django.shortcuts import get_object_or_404 from django.utils import timezone from hatchway import ApiError, ApiResponse, Schema, api_view from activities.models import ( Post, PostAttachment, PostInteraction, PostInteractionStates, TimelineEvent, ) from activities.services import PostService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config def post_for_id(request: HttpRequest, id: str) -> Post: """ Common logic to get a Post object for an ID, taking visibility into account. """ if request.identity: queryset = Post.objects.not_hidden().visible_to( request.identity, include_replies=True ) else: queryset = Post.objects.not_hidden().unlisted() return get_object_or_404(queryset, pk=id) def delete_status(request, id: str) -> schemas.Status: post = post_for_id(request, id) if post.author != request.identity: raise ApiError(401, "Not the author of this status") PostService(post).delete() return schemas.Status.from_post(post, identity=request.identity)
null
19,809
from datetime import timedelta from typing import Literal from django.http import HttpRequest from django.shortcuts import get_object_or_404 from django.utils import timezone from hatchway import ApiError, ApiResponse, Schema, api_view from activities.models import ( Post, PostAttachment, PostInteraction, PostInteractionStates, TimelineEvent, ) from activities.services import PostService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config def post_for_id(request: HttpRequest, id: str) -> Post: """ Common logic to get a Post object for an ID, taking visibility into account. """ if request.identity: queryset = Post.objects.not_hidden().visible_to( request.identity, include_replies=True ) else: queryset = Post.objects.not_hidden().unlisted() return get_object_or_404(queryset, pk=id) def status_source(request, id: str) -> schemas.StatusSource: post = post_for_id(request, id) return schemas.StatusSource.from_post(post)
null
19,810
from datetime import timedelta from typing import Literal from django.http import HttpRequest from django.shortcuts import get_object_or_404 from django.utils import timezone from hatchway import ApiError, ApiResponse, Schema, api_view from activities.models import ( Post, PostAttachment, PostInteraction, PostInteractionStates, TimelineEvent, ) from activities.services import PostService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config def post_for_id(request: HttpRequest, id: str) -> Post: """ Common logic to get a Post object for an ID, taking visibility into account. """ if request.identity: queryset = Post.objects.not_hidden().visible_to( request.identity, include_replies=True ) else: queryset = Post.objects.not_hidden().unlisted() return get_object_or_404(queryset, pk=id) def status_context(request, id: str) -> schemas.Context: post = post_for_id(request, id) service = PostService(post) ancestors, descendants = service.context(request.identity) interactions = PostInteraction.get_post_interactions( ancestors + descendants, request.identity ) return schemas.Context( ancestors=[ schemas.Status.from_post( p, interactions=interactions, identity=request.identity ) for p in reversed(ancestors) ], descendants=[ schemas.Status.from_post( p, interactions=interactions, identity=request.identity ) for p in descendants ], )
null
19,811
from datetime import timedelta from typing import Literal from django.http import HttpRequest from django.shortcuts import get_object_or_404 from django.utils import timezone from hatchway import ApiError, ApiResponse, Schema, api_view from activities.models import ( Post, PostAttachment, PostInteraction, PostInteractionStates, TimelineEvent, ) from activities.services import PostService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config def post_for_id(request: HttpRequest, id: str) -> Post: """ Common logic to get a Post object for an ID, taking visibility into account. """ if request.identity: queryset = Post.objects.not_hidden().visible_to( request.identity, include_replies=True ) else: queryset = Post.objects.not_hidden().unlisted() return get_object_or_404(queryset, pk=id) def favourite_status(request, id: str) -> schemas.Status: post = post_for_id(request, id) service = PostService(post) service.like_as(request.identity) interactions = PostInteraction.get_post_interactions([post], request.identity) return schemas.Status.from_post( post, interactions=interactions, identity=request.identity )
null
19,812
from datetime import timedelta from typing import Literal from django.http import HttpRequest from django.shortcuts import get_object_or_404 from django.utils import timezone from hatchway import ApiError, ApiResponse, Schema, api_view from activities.models import ( Post, PostAttachment, PostInteraction, PostInteractionStates, TimelineEvent, ) from activities.services import PostService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config def post_for_id(request: HttpRequest, id: str) -> Post: def unfavourite_status(request, id: str) -> schemas.Status: post = post_for_id(request, id) service = PostService(post) service.unlike_as(request.identity) interactions = PostInteraction.get_post_interactions([post], request.identity) return schemas.Status.from_post( post, interactions=interactions, identity=request.identity )
null
19,813
from datetime import timedelta from typing import Literal from django.http import HttpRequest from django.shortcuts import get_object_or_404 from django.utils import timezone from hatchway import ApiError, ApiResponse, Schema, api_view from activities.models import ( Post, PostAttachment, PostInteraction, PostInteractionStates, TimelineEvent, ) from activities.services import PostService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config def post_for_id(request: HttpRequest, id: str) -> Post: """ Common logic to get a Post object for an ID, taking visibility into account. """ if request.identity: queryset = Post.objects.not_hidden().visible_to( request.identity, include_replies=True ) else: queryset = Post.objects.not_hidden().unlisted() return get_object_or_404(queryset, pk=id) class PaginatingApiResponse(ApiResponse[list[TI]]): """ An ApiResponse subclass that also handles pagination link headers """ def __init__( self, data: list[TI], request: HttpRequest, include_params: list[str], **kwargs, ): # Call superclass super().__init__(data, **kwargs) # Figure out if we need link headers self._request = request self.extra_params = self.filter_params(self._request, include_params) link_header = self.build_link_header() if link_header: self.headers["link"] = link_header def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params def get_part(self, data_index: int, param_name: str, rel: str) -> str | None: """ Used to get next/prev URLs """ if not self.data: return None # Use the ID of the last object for the next page start params = dict(self.extra_params) params[param_name] = self.data[data_index].id return ( "<" + self._request.build_absolute_uri(self._request.path) + "?" + urllib.parse.urlencode(params) + f'>; rel="{rel}"' ) def build_link_header(self): parts = [ entry for entry in [ self.get_part(-1, "max_id", "next"), self.get_part(0, "min_id", "prev"), ] if entry ] if not parts: return None return ", ".join(parts) class PaginationResult(Generic[T]): """ Represents a pagination result for Mastodon (it does Link header stuff) """ #: A list of objects that matched the pagination query. results: list[T] #: The actual applied limit, which may be different from what was requested. limit: int #: A list of transformed JSON objects json_results: list[dict] | None = None def empty(cls): return cls(results=[], limit=20) def next(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the next page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["max_id"] = self.json_results[-1]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def prev(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the previous page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["min_id"] = self.json_results[0]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def link_header(self, request: HttpRequest, allowed_params: list[str]): """ Creates a link header for the given request """ return ", ".join( ( f'<{self.next(request, allowed_params)}>; rel="next"', f'<{self.prev(request, allowed_params)}>; rel="prev"', ) ) def jsonify_results(self, map_function: Callable[[Any], Any]): """ Replaces our results with ones transformed via map_function """ self.json_results = [map_function(result) for result in self.results] def jsonify_posts(self, identity): """ Predefined way of JSON-ifying Post objects """ interactions = PostInteraction.get_post_interactions(self.results, identity) self.jsonify_results( lambda post: post.to_mastodon_json( interactions=interactions, identity=identity ) ) def jsonify_status_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing statuses """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_status_json( interactions=interactions, identity=identity ) ) def jsonify_notification_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing notifications """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_notification_json(interactions=interactions) ) def jsonify_identities(self): """ Predefined way of JSON-ifying Identity objects """ self.jsonify_results(lambda identity: identity.to_mastodon_json()) def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params class MastodonPaginator: """ Paginates in the Mastodon style (max_id, min_id, etc). Note that this basically _requires_ us to always do it on IDs, so we do. """ def __init__( self, default_limit: int = 20, max_limit: int = 40, ): self.default_limit = default_limit self.max_limit = max_limit def paginate( self, queryset: models.QuerySet[TM], min_id: str | None, max_id: str | None, since_id: str | None, limit: int | None, home: bool = False, ) -> PaginationResult[TM]: limit = min(limit or self.default_limit, self.max_limit) filters = {} id_field = "id" reverse = False if home: # The home timeline interleaves Post IDs and PostInteraction IDs in an # annotated field called "subject_id". id_field = "subject_id" queryset = queryset.annotate( subject_id=Case( When(type=TimelineEvent.Types.post, then=F("subject_post_id")), default=F("subject_post_interaction"), ) ) # These "does not start with interaction" checks can be removed after a # couple months, when clients have flushed them out. if max_id and not max_id.startswith("interaction"): filters[f"{id_field}__lt"] = max_id if since_id and not since_id.startswith("interaction"): filters[f"{id_field}__gt"] = since_id if min_id and not min_id.startswith("interaction"): # Min ID requires items _immediately_ newer than specified, so we # invert the ordering to accommodate filters[f"{id_field}__gt"] = min_id reverse = True # Default is to order by ID descending (newest first), except for min_id # queries, which should order by ID for limiting, then reverse the results to be # consistent. The clearest explanation of this I've found so far is this: # https://mastodon.social/@Gargron/100846335353411164 ordering = id_field if reverse else f"-{id_field}" results = list(queryset.filter(**filters).order_by(ordering)[:limit]) if reverse: results.reverse() return PaginationResult( results=results, limit=limit, ) The provided code snippet includes necessary dependencies for implementing the `favourited_by` function. Write a Python function `def favourited_by( request: HttpRequest, id: str, max_id: str | None = None, since_id: str | None = None, min_id: str | None = None, limit: int = 20, ) -> ApiResponse[list[schemas.Account]]` to solve the following problem: View who favourited a given status. Here is the function: def favourited_by( request: HttpRequest, id: str, max_id: str | None = None, since_id: str | None = None, min_id: str | None = None, limit: int = 20, ) -> ApiResponse[list[schemas.Account]]: """ View who favourited a given status. """ post = post_for_id(request, id) paginator = MastodonPaginator() pager: PaginationResult[PostInteraction] = paginator.paginate( post.interactions.filter( type=PostInteraction.Types.like, state__in=PostInteractionStates.group_active(), ).select_related("identity"), min_id=min_id, max_id=max_id, since_id=since_id, limit=limit, ) return PaginatingApiResponse( [ schemas.Account.from_identity( interaction.identity, include_counts=False, ) for interaction in pager.results ], request=request, include_params=[ "limit", "id", ], )
View who favourited a given status.
19,814
from datetime import timedelta from typing import Literal from django.http import HttpRequest from django.shortcuts import get_object_or_404 from django.utils import timezone from hatchway import ApiError, ApiResponse, Schema, api_view from activities.models import ( Post, PostAttachment, PostInteraction, PostInteractionStates, TimelineEvent, ) from activities.services import PostService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config def post_for_id(request: HttpRequest, id: str) -> Post: """ Common logic to get a Post object for an ID, taking visibility into account. """ if request.identity: queryset = Post.objects.not_hidden().visible_to( request.identity, include_replies=True ) else: queryset = Post.objects.not_hidden().unlisted() return get_object_or_404(queryset, pk=id) class PaginatingApiResponse(ApiResponse[list[TI]]): """ An ApiResponse subclass that also handles pagination link headers """ def __init__( self, data: list[TI], request: HttpRequest, include_params: list[str], **kwargs, ): # Call superclass super().__init__(data, **kwargs) # Figure out if we need link headers self._request = request self.extra_params = self.filter_params(self._request, include_params) link_header = self.build_link_header() if link_header: self.headers["link"] = link_header def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params def get_part(self, data_index: int, param_name: str, rel: str) -> str | None: """ Used to get next/prev URLs """ if not self.data: return None # Use the ID of the last object for the next page start params = dict(self.extra_params) params[param_name] = self.data[data_index].id return ( "<" + self._request.build_absolute_uri(self._request.path) + "?" + urllib.parse.urlencode(params) + f'>; rel="{rel}"' ) def build_link_header(self): parts = [ entry for entry in [ self.get_part(-1, "max_id", "next"), self.get_part(0, "min_id", "prev"), ] if entry ] if not parts: return None return ", ".join(parts) class PaginationResult(Generic[T]): """ Represents a pagination result for Mastodon (it does Link header stuff) """ #: A list of objects that matched the pagination query. results: list[T] #: The actual applied limit, which may be different from what was requested. limit: int #: A list of transformed JSON objects json_results: list[dict] | None = None def empty(cls): return cls(results=[], limit=20) def next(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the next page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["max_id"] = self.json_results[-1]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def prev(self, request: HttpRequest, allowed_params: list[str]): """ Returns a URL to the previous page of results. """ if not self.results: return None if self.json_results is None: raise ValueError("You must JSONify the results first") params = self.filter_params(request, allowed_params) params["min_id"] = self.json_results[0]["id"] return f"{request.build_absolute_uri(request.path)}?{urllib.parse.urlencode(params)}" def link_header(self, request: HttpRequest, allowed_params: list[str]): """ Creates a link header for the given request """ return ", ".join( ( f'<{self.next(request, allowed_params)}>; rel="next"', f'<{self.prev(request, allowed_params)}>; rel="prev"', ) ) def jsonify_results(self, map_function: Callable[[Any], Any]): """ Replaces our results with ones transformed via map_function """ self.json_results = [map_function(result) for result in self.results] def jsonify_posts(self, identity): """ Predefined way of JSON-ifying Post objects """ interactions = PostInteraction.get_post_interactions(self.results, identity) self.jsonify_results( lambda post: post.to_mastodon_json( interactions=interactions, identity=identity ) ) def jsonify_status_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing statuses """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_status_json( interactions=interactions, identity=identity ) ) def jsonify_notification_events(self, identity): """ Predefined way of JSON-ifying TimelineEvent objects representing notifications """ interactions = PostInteraction.get_event_interactions(self.results, identity) self.jsonify_results( lambda event: event.to_mastodon_notification_json(interactions=interactions) ) def jsonify_identities(self): """ Predefined way of JSON-ifying Identity objects """ self.jsonify_results(lambda identity: identity.to_mastodon_json()) def filter_params(request: HttpRequest, allowed_params: list[str]): params = {} for key in allowed_params: value = request.GET.get(key, None) if value: params[key] = value return params class MastodonPaginator: """ Paginates in the Mastodon style (max_id, min_id, etc). Note that this basically _requires_ us to always do it on IDs, so we do. """ def __init__( self, default_limit: int = 20, max_limit: int = 40, ): self.default_limit = default_limit self.max_limit = max_limit def paginate( self, queryset: models.QuerySet[TM], min_id: str | None, max_id: str | None, since_id: str | None, limit: int | None, home: bool = False, ) -> PaginationResult[TM]: limit = min(limit or self.default_limit, self.max_limit) filters = {} id_field = "id" reverse = False if home: # The home timeline interleaves Post IDs and PostInteraction IDs in an # annotated field called "subject_id". id_field = "subject_id" queryset = queryset.annotate( subject_id=Case( When(type=TimelineEvent.Types.post, then=F("subject_post_id")), default=F("subject_post_interaction"), ) ) # These "does not start with interaction" checks can be removed after a # couple months, when clients have flushed them out. if max_id and not max_id.startswith("interaction"): filters[f"{id_field}__lt"] = max_id if since_id and not since_id.startswith("interaction"): filters[f"{id_field}__gt"] = since_id if min_id and not min_id.startswith("interaction"): # Min ID requires items _immediately_ newer than specified, so we # invert the ordering to accommodate filters[f"{id_field}__gt"] = min_id reverse = True # Default is to order by ID descending (newest first), except for min_id # queries, which should order by ID for limiting, then reverse the results to be # consistent. The clearest explanation of this I've found so far is this: # https://mastodon.social/@Gargron/100846335353411164 ordering = id_field if reverse else f"-{id_field}" results = list(queryset.filter(**filters).order_by(ordering)[:limit]) if reverse: results.reverse() return PaginationResult( results=results, limit=limit, ) The provided code snippet includes necessary dependencies for implementing the `reblogged_by` function. Write a Python function `def reblogged_by( request: HttpRequest, id: str, max_id: str | None = None, since_id: str | None = None, min_id: str | None = None, limit: int = 20, ) -> ApiResponse[list[schemas.Account]]` to solve the following problem: View who reblogged a given status. Here is the function: def reblogged_by( request: HttpRequest, id: str, max_id: str | None = None, since_id: str | None = None, min_id: str | None = None, limit: int = 20, ) -> ApiResponse[list[schemas.Account]]: """ View who reblogged a given status. """ post = post_for_id(request, id) paginator = MastodonPaginator() pager: PaginationResult[PostInteraction] = paginator.paginate( post.interactions.filter( type=PostInteraction.Types.boost, state__in=PostInteractionStates.group_active(), ).select_related("identity"), min_id=min_id, max_id=max_id, since_id=since_id, limit=limit, ) return PaginatingApiResponse( [ schemas.Account.from_identity( interaction.identity, include_counts=False, ) for interaction in pager.results ], request=request, include_params=[ "limit", "id", ], )
View who reblogged a given status.
19,815
from datetime import timedelta from typing import Literal from django.http import HttpRequest from django.shortcuts import get_object_or_404 from django.utils import timezone from hatchway import ApiError, ApiResponse, Schema, api_view from activities.models import ( Post, PostAttachment, PostInteraction, PostInteractionStates, TimelineEvent, ) from activities.services import PostService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config def post_for_id(request: HttpRequest, id: str) -> Post: def reblog_status(request, id: str) -> schemas.Status: post = post_for_id(request, id) service = PostService(post) service.boost_as(request.identity) interactions = PostInteraction.get_post_interactions([post], request.identity) return schemas.Status.from_post( post, interactions=interactions, identity=request.identity )
null
19,816
from datetime import timedelta from typing import Literal from django.http import HttpRequest from django.shortcuts import get_object_or_404 from django.utils import timezone from hatchway import ApiError, ApiResponse, Schema, api_view from activities.models import ( Post, PostAttachment, PostInteraction, PostInteractionStates, TimelineEvent, ) from activities.services import PostService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config def post_for_id(request: HttpRequest, id: str) -> Post: """ Common logic to get a Post object for an ID, taking visibility into account. """ if request.identity: queryset = Post.objects.not_hidden().visible_to( request.identity, include_replies=True ) else: queryset = Post.objects.not_hidden().unlisted() return get_object_or_404(queryset, pk=id) def unreblog_status(request, id: str) -> schemas.Status: post = post_for_id(request, id) service = PostService(post) service.unboost_as(request.identity) interactions = PostInteraction.get_post_interactions([post], request.identity) return schemas.Status.from_post( post, interactions=interactions, identity=request.identity )
null
19,817
from datetime import timedelta from typing import Literal from django.http import HttpRequest from django.shortcuts import get_object_or_404 from django.utils import timezone from hatchway import ApiError, ApiResponse, Schema, api_view from activities.models import ( Post, PostAttachment, PostInteraction, PostInteractionStates, TimelineEvent, ) from activities.services import PostService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config def post_for_id(request: HttpRequest, id: str) -> Post: """ Common logic to get a Post object for an ID, taking visibility into account. """ if request.identity: queryset = Post.objects.not_hidden().visible_to( request.identity, include_replies=True ) else: queryset = Post.objects.not_hidden().unlisted() return get_object_or_404(queryset, pk=id) def bookmark_status(request, id: str) -> schemas.Status: post = post_for_id(request, id) request.identity.bookmarks.get_or_create(post=post) interactions = PostInteraction.get_post_interactions([post], request.identity) return schemas.Status.from_post( post, interactions=interactions, bookmarks={post.pk}, identity=request.identity )
null
19,818
from datetime import timedelta from typing import Literal from django.http import HttpRequest from django.shortcuts import get_object_or_404 from django.utils import timezone from hatchway import ApiError, ApiResponse, Schema, api_view from activities.models import ( Post, PostAttachment, PostInteraction, PostInteractionStates, TimelineEvent, ) from activities.services import PostService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config def post_for_id(request: HttpRequest, id: str) -> Post: """ Common logic to get a Post object for an ID, taking visibility into account. """ if request.identity: queryset = Post.objects.not_hidden().visible_to( request.identity, include_replies=True ) else: queryset = Post.objects.not_hidden().unlisted() return get_object_or_404(queryset, pk=id) def unbookmark_status(request, id: str) -> schemas.Status: post = post_for_id(request, id) request.identity.bookmarks.filter(post=post).delete() interactions = PostInteraction.get_post_interactions([post], request.identity) return schemas.Status.from_post( post, interactions=interactions, identity=request.identity )
null
19,819
from datetime import timedelta from typing import Literal from django.http import HttpRequest from django.shortcuts import get_object_or_404 from django.utils import timezone from hatchway import ApiError, ApiResponse, Schema, api_view from activities.models import ( Post, PostAttachment, PostInteraction, PostInteractionStates, TimelineEvent, ) from activities.services import PostService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config def post_for_id(request: HttpRequest, id: str) -> Post: """ Common logic to get a Post object for an ID, taking visibility into account. """ if request.identity: queryset = Post.objects.not_hidden().visible_to( request.identity, include_replies=True ) else: queryset = Post.objects.not_hidden().unlisted() return get_object_or_404(queryset, pk=id) def pin_status(request, id: str) -> schemas.Status: post = post_for_id(request, id) try: PostService(post).pin_as(request.identity) interactions = PostInteraction.get_post_interactions([post], request.identity) return schemas.Status.from_post( post, identity=request.identity, interactions=interactions ) except ValueError as e: raise ApiError(422, str(e))
null
19,820
from datetime import timedelta from typing import Literal from django.http import HttpRequest from django.shortcuts import get_object_or_404 from django.utils import timezone from hatchway import ApiError, ApiResponse, Schema, api_view from activities.models import ( Post, PostAttachment, PostInteraction, PostInteractionStates, TimelineEvent, ) from activities.services import PostService from api import schemas from api.decorators import scope_required from api.pagination import MastodonPaginator, PaginatingApiResponse, PaginationResult from core.models import Config def post_for_id(request: HttpRequest, id: str) -> Post: """ Common logic to get a Post object for an ID, taking visibility into account. """ if request.identity: queryset = Post.objects.not_hidden().visible_to( request.identity, include_replies=True ) else: queryset = Post.objects.not_hidden().unlisted() return get_object_or_404(queryset, pk=id) def unpin_status(request, id: str) -> schemas.Status: post = post_for_id(request, id) PostService(post).unpin_as(request.identity) interactions = PostInteraction.get_post_interactions([post], request.identity) return schemas.Status.from_post( post, identity=request.identity, interactions=interactions )
null
19,821
from django.http import HttpRequest from hatchway import api_view from api import schemas from api.decorators import scope_required def trends_tags( request: HttpRequest, limit: int = 10, offset: int | None = None, ) -> list[schemas.Tag]: # We don't implement this yet return []
null
19,822
from django.http import HttpRequest from hatchway import api_view from api import schemas from api.decorators import scope_required def trends_statuses( request: HttpRequest, limit: int = 10, offset: int | None = None, ) -> list[schemas.Status]: # We don't implement this yet return []
null
19,823
from django.http import HttpRequest from hatchway import api_view from api import schemas from api.decorators import scope_required def trends_links( request: HttpRequest, limit: int = 10, offset: int | None = None, ) -> list: # We don't implement this yet return []
null
19,824
from django.http import HttpRequest from hatchway import api_view from api import schemas from api.decorators import scope_required def get_lists(request: HttpRequest) -> list[schemas.List]: # We don't implement this yet return []
null
19,825
import datetime from django.conf import settings from django.core.cache import cache from django.utils import timezone from hatchway import api_view from activities.models import Post from api import schemas from core.models import Config from takahe import __version__ from users.models import Domain, Identity __version__ = "0.11.0" def instance_info_v1(request): # The stats are expensive to calculate, so don't do it very often stats = cache.get("instance_info_stats") if stats is None: stats = { "user_count": Identity.objects.filter(local=True).count(), "status_count": Post.objects.filter(local=True).not_hidden().count(), "domain_count": Domain.objects.count(), } cache.set("instance_info_stats", stats, timeout=300) return { "uri": request.headers.get("host", settings.SETUP.MAIN_DOMAIN), "title": Config.system.site_name, "short_description": "", "description": "", "email": "", "version": f"takahe/{__version__}", "urls": {}, "stats": stats, "thumbnail": Config.system.site_banner, "languages": ["en"], "registrations": (Config.system.signup_allowed), "approval_required": False, "invites_enabled": False, "configuration": { "accounts": {}, "statuses": { "max_characters": Config.system.post_length, "max_media_attachments": Config.system.max_media_attachments, "characters_reserved_per_url": 23, }, "media_attachments": { "supported_mime_types": [ "image/apng", "image/avif", "image/gif", "image/jpeg", "image/png", "image/webp", ], "image_size_limit": (1024**2) * 10, "image_matrix_limit": 2000 * 2000, }, "polls": { "max_options": 4, "max_characters_per_option": 50, "min_expiration": 300, "max_expiration": 2629746, }, }, "contact_account": None, "rules": [], }
null
19,826
import datetime from django.conf import settings from django.core.cache import cache from django.utils import timezone from hatchway import api_view from activities.models import Post from api import schemas from core.models import Config from takahe import __version__ from users.models import Domain, Identity __version__ = "0.11.0" def instance_info_v2(request) -> dict: current_domain = Domain.get_domain( request.headers.get("host", settings.SETUP.MAIN_DOMAIN) ) if current_domain is None or not current_domain.local: current_domain = Domain.get_domain(settings.SETUP.MAIN_DOMAIN) if current_domain is None: raise ValueError("No domain set up for MAIN_DOMAIN") admin_identity = ( Identity.objects.filter(users__admin=True).order_by("created").first() ) return { "domain": current_domain.domain, "title": Config.system.site_name, "version": f"takahe/{__version__}", "source_url": "https://github.com/jointakahe/takahe", "description": "", "email": "", "urls": {}, "usage": { "users": { "active_month": Identity.objects.filter(local=True).count(), } }, "thumbnail": { "url": Config.system.site_banner, }, "languages": ["en"], "configuration": { "urls": {}, "accounts": {"max_featured_tags": 0}, "statuses": { "max_characters": Config.system.post_length, "max_media_attachments": Config.system.max_media_attachments, "characters_reserved_per_url": 23, }, "media_attachments": { "supported_mime_types": [ "image/apng", "image/avif", "image/gif", "image/jpeg", "image/png", "image/webp", ], "image_size_limit": (1024**2) * 10, "image_matrix_limit": 2000 * 2000, "video_size_limit": 0, "video_frame_rate_limit": 60, "video_matrix_limit": 2000 * 2000, }, "polls": { "max_options": 4, "max_characters_per_option": 50, "min_expiration": 300, "max_expiration": 2629746, }, "translation": {"enabled": False}, }, "registrations": { "enabled": Config.system.signup_allowed, "approval_required": False, "message": None, }, "contact": { "email": "", "account": schemas.Account.from_identity(admin_identity), }, "rules": [], }
null
19,827
import datetime from django.conf import settings from django.core.cache import cache from django.utils import timezone from hatchway import api_view from activities.models import Post from api import schemas from core.models import Config from takahe import __version__ from users.models import Domain, Identity def peers(request) -> list[str]: return list( Domain.objects.filter(local=False, blocked=False).values_list( "domain", flat=True ) )
null
19,828
import datetime from django.conf import settings from django.core.cache import cache from django.utils import timezone from hatchway import api_view from activities.models import Post from api import schemas from core.models import Config from takahe import __version__ from users.models import Domain, Identity The provided code snippet includes necessary dependencies for implementing the `activity` function. Write a Python function `def activity(request) -> list` to solve the following problem: Weekly activity endpoint Here is the function: def activity(request) -> list: """ Weekly activity endpoint """ # The stats are expensive to calculate, so don't do it very often stats = cache.get("instance_activity_stats") if stats is None: stats = [] # Work out our most recent week start now = timezone.now() week_start = now.replace( hour=0, minute=0, second=0, microsecond=0 ) - datetime.timedelta(now.weekday()) for i in range(12): week_end = week_start + datetime.timedelta(days=7) stats.append( { "week": int(week_start.timestamp()), "statuses": Post.objects.filter( local=True, created__gte=week_start, created__lt=week_end ).count(), # TODO: Populate when we have identity activity tracking "logins": 0, "registrations": Identity.objects.filter( local=True, created__gte=week_start, created__lt=week_end ).count(), } ) week_start -= datetime.timedelta(days=7) cache.set("instance_activity_stats", stats, timeout=300) return stats
Weekly activity endpoint
19,829
from django.shortcuts import get_object_or_404 from hatchway import Schema, api_view from activities.models import Post, PostInteraction from api import schemas from api.decorators import scope_required def get_poll(request, id: str) -> schemas.Poll: post = get_object_or_404(Post, pk=id, type=Post.Types.question) return schemas.Poll.from_post(post, identity=request.identity)
null
19,830
from django.shortcuts import get_object_or_404 from hatchway import Schema, api_view from activities.models import Post, PostInteraction from api import schemas from api.decorators import scope_required class PostVoteSchema(Schema): choices: list[int] def vote_poll(request, id: str, details: PostVoteSchema) -> schemas.Poll: post = get_object_or_404(Post, pk=id, type=Post.Types.question) PostInteraction.create_votes(post, request.identity, details.choices) post.refresh_from_db() return schemas.Poll.from_post(post, identity=request.identity)
null
19,831
from collections.abc import Callable from functools import wraps from django.http import JsonResponse The provided code snippet includes necessary dependencies for implementing the `identity_required` function. Write a Python function `def identity_required(function)` to solve the following problem: Makes sure the token is tied to an identity, not an app only. Here is the function: def identity_required(function): """ Makes sure the token is tied to an identity, not an app only. """ @wraps(function) def inner(request, *args, **kwargs): # They need an identity if not request.identity: return JsonResponse({"error": "identity_token_required"}, status=401) return function(request, *args, **kwargs) # This is for the API only inner.csrf_exempt = True return inner
Makes sure the token is tied to an identity, not an app only.
19,832
from collections.abc import Callable from functools import wraps from django.http import JsonResponse The provided code snippet includes necessary dependencies for implementing the `scope_required` function. Write a Python function `def scope_required(scope: str, requires_identity=True)` to solve the following problem: Asserts that the token we're using has the provided scope Here is the function: def scope_required(scope: str, requires_identity=True): """ Asserts that the token we're using has the provided scope """ def decorator(function: Callable): @wraps(function) def inner(request, *args, **kwargs): if not request.token: if request.identity: # They're just logged in via cookie - give full access pass else: return JsonResponse( {"error": "identity_token_required"}, status=401 ) elif not request.token.has_scope(scope): return JsonResponse({"error": "out_of_scope_for_token"}, status=403) # They need an identity if not request.identity and requires_identity: return JsonResponse({"error": "identity_token_required"}, status=401) return function(request, *args, **kwargs) inner.csrf_exempt = True # type:ignore return inner return decorator
Asserts that the token we're using has the provided scope
19,833
from sphinx.application import Sphinx from sphinx.builders.dirhtml import DirectoryHTMLBuilder def canonical_url(app: Sphinx, pagename, templatename, context, doctree): """Sphinx 1.8 builds a canonical URL if ``html_baseurl`` config is set. However, it builds a URL ending with ".html" when using the dirhtml builder, which is incorrect. Detect this and generate the correct URL for each page. Also accepts the custom, deprecated ``canonical_url`` config as the base URL. This will be removed in version 2.1. """ base = app.config.html_baseurl if ( not base or not isinstance(app.builder, DirectoryHTMLBuilder) or not context["pageurl"] or not context["pageurl"].endswith(".html") ): return # Fix pageurl for dirhtml builder if this version of Sphinx still # generates .html URLs. target = app.builder.get_target_uri(pagename) context["pageurl"] = base + target def setup(app: Sphinx): app.connect("html-page-context", canonical_url)
null
19,834
import datetime from urllib.parse import urlencode from django import template from django.utils import timezone def timedeltashort(value: datetime.datetime): """ A more compact version of timesince """ if not value: return "" delta = timezone.now() - value seconds = int(delta.total_seconds()) sign = "-" if seconds < 0 else "" seconds = abs(seconds) days = abs(delta.days) if seconds < 60: text = f"{seconds:0n}s" elif seconds < 60 * 60: minutes = seconds // 60 text = f"{minutes:0n}m" elif seconds < 60 * 60 * 24: hours = seconds // (60 * 60) text = f"{hours:0n}h" elif days < 365: text = f"{days:0n}d" else: years = max(days // 365.25, 1) text = f"{years:0n}y" return sign + text The provided code snippet includes necessary dependencies for implementing the `timedeltashortenddate` function. Write a Python function `def timedeltashortenddate(value: datetime.datetime)` to solve the following problem: Formatter for end dates - timedeltashort but it adds "ended ... ago" or "left" depending on the direction. Here is the function: def timedeltashortenddate(value: datetime.datetime): """ Formatter for end dates - timedeltashort but it adds "ended ... ago" or "left" depending on the direction. """ output = timedeltashort(value) if output.startswith("-"): return f"{output[1:]} left" else: return f"Ended {output} ago"
Formatter for end dates - timedeltashort but it adds "ended ... ago" or "left" depending on the direction.
19,835
import datetime from urllib.parse import urlencode from django import template from django.utils import timezone The provided code snippet includes necessary dependencies for implementing the `urlparams` function. Write a Python function `def urlparams(context, **kwargs)` to solve the following problem: Generates a URL parameter string the same as the current page but with the given items changed. Here is the function: def urlparams(context, **kwargs): """ Generates a URL parameter string the same as the current page but with the given items changed. """ params = dict(context["request"].GET.items()) for name, value in kwargs.items(): if value: params[name] = value elif name in params: del params[name] return urlencode(params)
Generates a URL parameter string the same as the current page but with the given items changed.
19,836
from django import template The provided code snippet includes necessary dependencies for implementing the `dict_merge` function. Write a Python function `def dict_merge(base: dict, defaults: dict)` to solve the following problem: Merges two input dictionaries, returning the merged result. `input|dict_merge:defaults` The defaults are overridden by any key present in the `input` dict. Here is the function: def dict_merge(base: dict, defaults: dict): """ Merges two input dictionaries, returning the merged result. `input|dict_merge:defaults` The defaults are overridden by any key present in the `input` dict. """ if not (isinstance(base, dict) or isinstance(defaults, dict)): raise ValueError("Filter inputs must be dictionaries") result = {} result.update(defaults) result.update(base) return result
Merges two input dictionaries, returning the merged result. `input|dict_merge:defaults` The defaults are overridden by any key present in the `input` dict.
19,837
import django.utils.timezone from django.db import migrations, models import activities.models.post_types The provided code snippet includes necessary dependencies for implementing the `timelineevent_populate_published` function. Write a Python function `def timelineevent_populate_published(apps, schema_editor)` to solve the following problem: Populates all timeline events' published date with their created date Here is the function: def timelineevent_populate_published(apps, schema_editor): """ Populates all timeline events' published date with their created date """ TimelineEvent = apps.get_model("activities", "timelineevent") TimelineEvent.objects.update(published=models.F("created"))
Populates all timeline events' published date with their created date
19,838
import datetime import logging from typing import ClassVar from asgiref.sync import async_to_sync, iscoroutinefunction from django.db import models, transaction from django.db.models.signals import class_prepared from django.utils import timezone from django.utils.functional import classproperty from stator.exceptions import TryAgainLater from stator.graph import State, StateGraph class StatorModel(models.Model): """ A model base class that has a state machine backing it, with tasks to work out when to move the state to the next one. You need to provide a "state" field as an instance of StateField on the concrete model yourself. """ CLEAN_BATCH_SIZE = 1000 DELETE_BATCH_SIZE = 500 state: StateField # When the state last actually changed, or the date of instance creation state_changed = models.DateTimeField(auto_now_add=True) # When the next state change should be attempted (null means immediately) state_next_attempt = models.DateTimeField(blank=True, null=True) # If a lock is out on this row, when it is locked until # (we don't identify the lock owner, as there's no heartbeats) state_locked_until = models.DateTimeField(null=True, blank=True, db_index=True) # Collection of subclasses of us subclasses: ClassVar[list[type["StatorModel"]]] = [] class Meta: abstract = True def __init_subclass__(cls) -> None: if cls is not StatorModel: cls.subclasses.append(cls) def state_graph(cls) -> type[StateGraph]: return cls._meta.get_field("state").graph def state_age(self) -> float: return (timezone.now() - self.state_changed).total_seconds() def transition_get_with_lock( cls, number: int, lock_expiry: datetime.datetime ) -> list["StatorModel"]: """ Returns up to `number` tasks for execution, having locked them. """ with transaction.atomic(): # Query for `number` rows that: # - Have a next_attempt that's either null or in the past # - Have one of the states we care about # Then, sort them by next_attempt NULLS FIRST, so that we handle the # rows in a roughly FIFO order. selected = list( cls.objects.filter( models.Q(state_next_attempt__isnull=True) | models.Q(state_next_attempt__lte=timezone.now()), state__in=cls.state_graph.automatic_states, state_locked_until__isnull=True, )[:number].select_for_update() ) cls.objects.filter(pk__in=[i.pk for i in selected]).update( state_locked_until=lock_expiry ) return selected def transition_delete_due(cls) -> int | None: """ Finds instances of this model that need to be deleted and deletes them in small batches. Returns how many were deleted. """ if cls.state_graph.deletion_states: constraints = models.Q() for state in cls.state_graph.deletion_states: constraints |= models.Q( state=state, state_changed__lte=( timezone.now() - datetime.timedelta(seconds=state.delete_after) ), ) select_query = cls.objects.filter( models.Q(state_next_attempt__isnull=True) | models.Q(state_next_attempt__lte=timezone.now()), constraints, )[: cls.DELETE_BATCH_SIZE] return cls.objects.filter(pk__in=select_query).delete()[0] return None def transition_ready_count(cls) -> int: """ Returns how many instances are "queued" """ return cls.objects.filter( models.Q(state_next_attempt__isnull=True) | models.Q(state_next_attempt__lte=timezone.now()), state_locked_until__isnull=True, state__in=cls.state_graph.automatic_states, ).count() def transition_clean_locks(cls): """ Deletes stale locks (in batches, to avoid a giant query) """ select_query = cls.objects.filter(state_locked_until__lte=timezone.now())[ : cls.CLEAN_BATCH_SIZE ] cls.objects.filter(pk__in=select_query).update(state_locked_until=None) def transition_attempt(self) -> State | None: """ Attempts to transition the current state by running its handler(s). """ current_state: State = self.state_graph.states[self.state] # If it's a manual progression state don't even try # We shouldn't really be here in this case, but it could be a race condition if current_state.externally_progressed: logger.warning( f"Warning: trying to progress externally progressed state {self.state}!" ) return None # Try running its handler function try: if iscoroutinefunction(current_state.handler): next_state = async_to_sync(current_state.handler)(self) else: next_state = current_state.handler(self) except TryAgainLater: pass except BaseException as e: logger.exception(e) else: if next_state: # Ensure it's a State object if isinstance(next_state, str): next_state = self.state_graph.states[next_state] # Ensure it's a child if next_state not in current_state.children: raise ValueError( f"Cannot transition from {current_state} to {next_state} - not a declared transition" ) self.transition_perform(next_state) return next_state # See if it timed out since its last state change if ( current_state.timeout_value and current_state.timeout_value <= (timezone.now() - self.state_changed).total_seconds() ): self.transition_perform(current_state.timeout_state) # type: ignore return current_state.timeout_state # Nothing happened, set next execution and unlock it self.__class__.objects.filter(pk=self.pk).update( state_next_attempt=( timezone.now() + datetime.timedelta(seconds=current_state.try_interval) # type: ignore ), state_locked_until=None, ) return None def transition_perform(self, state: State | str): """ Transitions the instance to the given state name, forcibly. """ self.transition_perform_queryset( self.__class__.objects.filter(pk=self.pk), state, ) def transition_perform_queryset( cls, queryset: models.QuerySet, state: State | str, ): """ Transitions every instance in the queryset to the given state name, forcibly. """ # Really ensure we have the right state object if isinstance(state, State): state_obj = cls.state_graph.states[state.name] else: state_obj = cls.state_graph.states[state] # See if it's ready immediately (if not, delay until first try_interval) if state_obj.attempt_immediately or state_obj.try_interval is None: queryset.update( state=state_obj, state_changed=timezone.now(), state_next_attempt=None, state_locked_until=None, ) else: queryset.update( state=state_obj, state_changed=timezone.now(), state_next_attempt=( timezone.now() + datetime.timedelta(seconds=state_obj.try_interval) ), state_locked_until=None, ) The provided code snippet includes necessary dependencies for implementing the `add_stator_indexes` function. Write a Python function `def add_stator_indexes(sender, **kwargs)` to solve the following problem: Inject Indexes used by StatorModel in to any subclasses. This sidesteps the current Django inability to inherit indexes when the Model subclass defines its own indexes. Here is the function: def add_stator_indexes(sender, **kwargs): """ Inject Indexes used by StatorModel in to any subclasses. This sidesteps the current Django inability to inherit indexes when the Model subclass defines its own indexes. """ if issubclass(sender, StatorModel): indexes = [ models.Index( fields=["state", "state_next_attempt", "state_locked_until"], name=f"ix_{sender.__name__.lower()[:11]}_state_next", ), ] if not sender._meta.indexes: # Meta.indexes needs to not be None to trigger Django behaviors sender.Meta.indexes = [] sender._meta.indexes = [] for idx in indexes: sender._meta.indexes.append(idx)
Inject Indexes used by StatorModel in to any subclasses. This sidesteps the current Django inability to inherit indexes when the Model subclass defines its own indexes.
19,839
import datetime import logging import os import signal import time import uuid from concurrent.futures import Future, ThreadPoolExecutor from django.conf import settings from django.db import close_old_connections from django.utils import timezone from core import sentry from core.models import Config from stator.models import StatorModel, Stats logger = logging.getLogger(__name__) class StatorModel(models.Model): """ A model base class that has a state machine backing it, with tasks to work out when to move the state to the next one. You need to provide a "state" field as an instance of StateField on the concrete model yourself. """ CLEAN_BATCH_SIZE = 1000 DELETE_BATCH_SIZE = 500 state: StateField # When the state last actually changed, or the date of instance creation state_changed = models.DateTimeField(auto_now_add=True) # When the next state change should be attempted (null means immediately) state_next_attempt = models.DateTimeField(blank=True, null=True) # If a lock is out on this row, when it is locked until # (we don't identify the lock owner, as there's no heartbeats) state_locked_until = models.DateTimeField(null=True, blank=True, db_index=True) # Collection of subclasses of us subclasses: ClassVar[list[type["StatorModel"]]] = [] class Meta: abstract = True def __init_subclass__(cls) -> None: if cls is not StatorModel: cls.subclasses.append(cls) def state_graph(cls) -> type[StateGraph]: return cls._meta.get_field("state").graph def state_age(self) -> float: return (timezone.now() - self.state_changed).total_seconds() def transition_get_with_lock( cls, number: int, lock_expiry: datetime.datetime ) -> list["StatorModel"]: """ Returns up to `number` tasks for execution, having locked them. """ with transaction.atomic(): # Query for `number` rows that: # - Have a next_attempt that's either null or in the past # - Have one of the states we care about # Then, sort them by next_attempt NULLS FIRST, so that we handle the # rows in a roughly FIFO order. selected = list( cls.objects.filter( models.Q(state_next_attempt__isnull=True) | models.Q(state_next_attempt__lte=timezone.now()), state__in=cls.state_graph.automatic_states, state_locked_until__isnull=True, )[:number].select_for_update() ) cls.objects.filter(pk__in=[i.pk for i in selected]).update( state_locked_until=lock_expiry ) return selected def transition_delete_due(cls) -> int | None: """ Finds instances of this model that need to be deleted and deletes them in small batches. Returns how many were deleted. """ if cls.state_graph.deletion_states: constraints = models.Q() for state in cls.state_graph.deletion_states: constraints |= models.Q( state=state, state_changed__lte=( timezone.now() - datetime.timedelta(seconds=state.delete_after) ), ) select_query = cls.objects.filter( models.Q(state_next_attempt__isnull=True) | models.Q(state_next_attempt__lte=timezone.now()), constraints, )[: cls.DELETE_BATCH_SIZE] return cls.objects.filter(pk__in=select_query).delete()[0] return None def transition_ready_count(cls) -> int: """ Returns how many instances are "queued" """ return cls.objects.filter( models.Q(state_next_attempt__isnull=True) | models.Q(state_next_attempt__lte=timezone.now()), state_locked_until__isnull=True, state__in=cls.state_graph.automatic_states, ).count() def transition_clean_locks(cls): """ Deletes stale locks (in batches, to avoid a giant query) """ select_query = cls.objects.filter(state_locked_until__lte=timezone.now())[ : cls.CLEAN_BATCH_SIZE ] cls.objects.filter(pk__in=select_query).update(state_locked_until=None) def transition_attempt(self) -> State | None: """ Attempts to transition the current state by running its handler(s). """ current_state: State = self.state_graph.states[self.state] # If it's a manual progression state don't even try # We shouldn't really be here in this case, but it could be a race condition if current_state.externally_progressed: logger.warning( f"Warning: trying to progress externally progressed state {self.state}!" ) return None # Try running its handler function try: if iscoroutinefunction(current_state.handler): next_state = async_to_sync(current_state.handler)(self) else: next_state = current_state.handler(self) except TryAgainLater: pass except BaseException as e: logger.exception(e) else: if next_state: # Ensure it's a State object if isinstance(next_state, str): next_state = self.state_graph.states[next_state] # Ensure it's a child if next_state not in current_state.children: raise ValueError( f"Cannot transition from {current_state} to {next_state} - not a declared transition" ) self.transition_perform(next_state) return next_state # See if it timed out since its last state change if ( current_state.timeout_value and current_state.timeout_value <= (timezone.now() - self.state_changed).total_seconds() ): self.transition_perform(current_state.timeout_state) # type: ignore return current_state.timeout_state # Nothing happened, set next execution and unlock it self.__class__.objects.filter(pk=self.pk).update( state_next_attempt=( timezone.now() + datetime.timedelta(seconds=current_state.try_interval) # type: ignore ), state_locked_until=None, ) return None def transition_perform(self, state: State | str): """ Transitions the instance to the given state name, forcibly. """ self.transition_perform_queryset( self.__class__.objects.filter(pk=self.pk), state, ) def transition_perform_queryset( cls, queryset: models.QuerySet, state: State | str, ): """ Transitions every instance in the queryset to the given state name, forcibly. """ # Really ensure we have the right state object if isinstance(state, State): state_obj = cls.state_graph.states[state.name] else: state_obj = cls.state_graph.states[state] # See if it's ready immediately (if not, delay until first try_interval) if state_obj.attempt_immediately or state_obj.try_interval is None: queryset.update( state=state_obj, state_changed=timezone.now(), state_next_attempt=None, state_locked_until=None, ) else: queryset.update( state=state_obj, state_changed=timezone.now(), state_next_attempt=( timezone.now() + datetime.timedelta(seconds=state_obj.try_interval) ), state_locked_until=None, ) The provided code snippet includes necessary dependencies for implementing the `task_transition` function. Write a Python function `def task_transition(instance: StatorModel, in_thread: bool = True)` to solve the following problem: Runs one state transition/action. Here is the function: def task_transition(instance: StatorModel, in_thread: bool = True): """ Runs one state transition/action. """ task_name = f"stator.task_transition:{instance._meta.label_lower}#{{id}} from {instance.state}" started = time.monotonic() with sentry.start_transaction(op="task", name=task_name): sentry.set_context( "instance", { "model": instance._meta.label_lower, "pk": instance.pk, "state": instance.state, "state_age": instance.state_age, }, ) result = instance.transition_attempt() duration = time.monotonic() - started if result: logger.info( f"{instance._meta.label_lower}: {instance.pk}: {instance.state} -> {result} ({duration:.2f}s)" ) else: logger.info( f"{instance._meta.label_lower}: {instance.pk}: {instance.state} unchanged ({duration:.2f}s)" ) if in_thread: close_old_connections()
Runs one state transition/action.
19,840
import datetime import logging import os import signal import time import uuid from concurrent.futures import Future, ThreadPoolExecutor from django.conf import settings from django.db import close_old_connections from django.utils import timezone from core import sentry from core.models import Config from stator.models import StatorModel, Stats logger = logging.getLogger(__name__) class StatorModel(models.Model): """ A model base class that has a state machine backing it, with tasks to work out when to move the state to the next one. You need to provide a "state" field as an instance of StateField on the concrete model yourself. """ CLEAN_BATCH_SIZE = 1000 DELETE_BATCH_SIZE = 500 state: StateField # When the state last actually changed, or the date of instance creation state_changed = models.DateTimeField(auto_now_add=True) # When the next state change should be attempted (null means immediately) state_next_attempt = models.DateTimeField(blank=True, null=True) # If a lock is out on this row, when it is locked until # (we don't identify the lock owner, as there's no heartbeats) state_locked_until = models.DateTimeField(null=True, blank=True, db_index=True) # Collection of subclasses of us subclasses: ClassVar[list[type["StatorModel"]]] = [] class Meta: abstract = True def __init_subclass__(cls) -> None: if cls is not StatorModel: cls.subclasses.append(cls) def state_graph(cls) -> type[StateGraph]: return cls._meta.get_field("state").graph def state_age(self) -> float: return (timezone.now() - self.state_changed).total_seconds() def transition_get_with_lock( cls, number: int, lock_expiry: datetime.datetime ) -> list["StatorModel"]: """ Returns up to `number` tasks for execution, having locked them. """ with transaction.atomic(): # Query for `number` rows that: # - Have a next_attempt that's either null or in the past # - Have one of the states we care about # Then, sort them by next_attempt NULLS FIRST, so that we handle the # rows in a roughly FIFO order. selected = list( cls.objects.filter( models.Q(state_next_attempt__isnull=True) | models.Q(state_next_attempt__lte=timezone.now()), state__in=cls.state_graph.automatic_states, state_locked_until__isnull=True, )[:number].select_for_update() ) cls.objects.filter(pk__in=[i.pk for i in selected]).update( state_locked_until=lock_expiry ) return selected def transition_delete_due(cls) -> int | None: """ Finds instances of this model that need to be deleted and deletes them in small batches. Returns how many were deleted. """ if cls.state_graph.deletion_states: constraints = models.Q() for state in cls.state_graph.deletion_states: constraints |= models.Q( state=state, state_changed__lte=( timezone.now() - datetime.timedelta(seconds=state.delete_after) ), ) select_query = cls.objects.filter( models.Q(state_next_attempt__isnull=True) | models.Q(state_next_attempt__lte=timezone.now()), constraints, )[: cls.DELETE_BATCH_SIZE] return cls.objects.filter(pk__in=select_query).delete()[0] return None def transition_ready_count(cls) -> int: """ Returns how many instances are "queued" """ return cls.objects.filter( models.Q(state_next_attempt__isnull=True) | models.Q(state_next_attempt__lte=timezone.now()), state_locked_until__isnull=True, state__in=cls.state_graph.automatic_states, ).count() def transition_clean_locks(cls): """ Deletes stale locks (in batches, to avoid a giant query) """ select_query = cls.objects.filter(state_locked_until__lte=timezone.now())[ : cls.CLEAN_BATCH_SIZE ] cls.objects.filter(pk__in=select_query).update(state_locked_until=None) def transition_attempt(self) -> State | None: """ Attempts to transition the current state by running its handler(s). """ current_state: State = self.state_graph.states[self.state] # If it's a manual progression state don't even try # We shouldn't really be here in this case, but it could be a race condition if current_state.externally_progressed: logger.warning( f"Warning: trying to progress externally progressed state {self.state}!" ) return None # Try running its handler function try: if iscoroutinefunction(current_state.handler): next_state = async_to_sync(current_state.handler)(self) else: next_state = current_state.handler(self) except TryAgainLater: pass except BaseException as e: logger.exception(e) else: if next_state: # Ensure it's a State object if isinstance(next_state, str): next_state = self.state_graph.states[next_state] # Ensure it's a child if next_state not in current_state.children: raise ValueError( f"Cannot transition from {current_state} to {next_state} - not a declared transition" ) self.transition_perform(next_state) return next_state # See if it timed out since its last state change if ( current_state.timeout_value and current_state.timeout_value <= (timezone.now() - self.state_changed).total_seconds() ): self.transition_perform(current_state.timeout_state) # type: ignore return current_state.timeout_state # Nothing happened, set next execution and unlock it self.__class__.objects.filter(pk=self.pk).update( state_next_attempt=( timezone.now() + datetime.timedelta(seconds=current_state.try_interval) # type: ignore ), state_locked_until=None, ) return None def transition_perform(self, state: State | str): """ Transitions the instance to the given state name, forcibly. """ self.transition_perform_queryset( self.__class__.objects.filter(pk=self.pk), state, ) def transition_perform_queryset( cls, queryset: models.QuerySet, state: State | str, ): """ Transitions every instance in the queryset to the given state name, forcibly. """ # Really ensure we have the right state object if isinstance(state, State): state_obj = cls.state_graph.states[state.name] else: state_obj = cls.state_graph.states[state] # See if it's ready immediately (if not, delay until first try_interval) if state_obj.attempt_immediately or state_obj.try_interval is None: queryset.update( state=state_obj, state_changed=timezone.now(), state_next_attempt=None, state_locked_until=None, ) else: queryset.update( state=state_obj, state_changed=timezone.now(), state_next_attempt=( timezone.now() + datetime.timedelta(seconds=state_obj.try_interval) ), state_locked_until=None, ) The provided code snippet includes necessary dependencies for implementing the `task_deletion` function. Write a Python function `def task_deletion(model: type[StatorModel], in_thread: bool = True)` to solve the following problem: Runs one model deletion set. Here is the function: def task_deletion(model: type[StatorModel], in_thread: bool = True): """ Runs one model deletion set. """ # Loop, running deletions every second, until there are no more to do while True: deleted = model.transition_delete_due() if not deleted: break logger.info(f"{model._meta.label_lower}: Deleted {deleted} stale items") time.sleep(1) if in_thread: close_old_connections()
Runs one model deletion set.
19,841
import json from httpx import Response JSON_CONTENT_TYPES = [ "application/json", "application/ld+json", "application/activity+json", ] import json def json_from_response(response: Response) -> dict | None: content_type, *parameters = ( response.headers.get("Content-Type", "invalid").lower().split(";") ) if content_type not in JSON_CONTENT_TYPES: return None charset = None for parameter in parameters: key, value = parameter.split("=") if key.strip() == "charset": charset = value.strip() if charset: return json.loads(response.content.decode(charset)) else: # if no charset informed, default to # httpx json for encoding inference return response.json()
null
19,842
import os import secrets from typing import TYPE_CHECKING from django.utils import timezone from storages.backends.gcloud import GoogleCloudStorage from storages.backends.s3boto3 import S3Boto3Storage The provided code snippet includes necessary dependencies for implementing the `upload_namer` function. Write a Python function `def upload_namer(prefix, instance, filename)` to solve the following problem: Names uploaded images. By default, obscures the original name with a random UUID. Here is the function: def upload_namer(prefix, instance, filename): """ Names uploaded images. By default, obscures the original name with a random UUID. """ _, old_extension = os.path.splitext(filename) new_filename = secrets.token_urlsafe(20) now = timezone.now() return f"{prefix}/{now.year}/{now.month}/{now.day}/{new_filename}{old_extension}"
Names uploaded images. By default, obscures the original name with a random UUID.
19,843
import os import secrets from typing import TYPE_CHECKING from django.utils import timezone from storages.backends.gcloud import GoogleCloudStorage from storages.backends.s3boto3 import S3Boto3Storage The provided code snippet includes necessary dependencies for implementing the `upload_emoji_namer` function. Write a Python function `def upload_emoji_namer(prefix, instance: "Emoji", filename)` to solve the following problem: Names uploaded emoji per domain Here is the function: def upload_emoji_namer(prefix, instance: "Emoji", filename): """ Names uploaded emoji per domain """ _, old_extension = os.path.splitext(filename) if instance.domain is None: domain = "_default" else: domain = instance.domain.domain return f"{prefix}/{domain}/{instance.shortcode}{old_extension}"
Names uploaded emoji per domain
19,844
from django.template import Library, Template def email_body_content(context, content): template = Template(content) return {"content": template.render(context)}
null
19,845
from django.template import Library, Template def email_button(context, button_text, button_link): text_template = Template(button_text) link_template = Template(button_link) return { "button_text": text_template.render(context), "button_link": link_template.render(context), }
null
19,846
from django.template import Library, Template def email_footer(context, content): template = Template(content) return {"content": template.render(context)}
null
19,847
import io import blurhash import httpx from django.conf import settings from django.core.files import File from django.core.files.base import ContentFile from PIL import Image, ImageOps The provided code snippet includes necessary dependencies for implementing the `get_remote_file` function. Write a Python function `def get_remote_file( url: str, *, timeout: float = settings.SETUP.REMOTE_TIMEOUT, max_size: int | None = None, ) -> tuple[File | None, str | None]` to solve the following problem: Download a URL and return the File and content-type. Here is the function: def get_remote_file( url: str, *, timeout: float = settings.SETUP.REMOTE_TIMEOUT, max_size: int | None = None, ) -> tuple[File | None, str | None]: """ Download a URL and return the File and content-type. """ headers = { "User-Agent": settings.TAKAHE_USER_AGENT, } with httpx.Client(headers=headers) as client: with client.stream( "GET", url, timeout=timeout, follow_redirects=True ) as stream: allow_download = max_size is None if max_size: try: content_length = int(stream.headers["content-length"]) allow_download = content_length <= max_size except (KeyError, TypeError): pass if allow_download: file = ContentFile(stream.read(), name=url) return file, stream.headers.get( "content-type", "application/octet-stream" ) return None, None
Download a URL and return the File and content-type.
19,848
from collections.abc import Callable from functools import partial, wraps from typing import ParamSpecArgs, ParamSpecKwargs from django.http import HttpRequest from django.views.decorators.cache import cache_page as dj_cache_page from core.models import Config The provided code snippet includes necessary dependencies for implementing the `vary_by_ap_json` function. Write a Python function `def vary_by_ap_json(request, *args, **kwargs) -> str` to solve the following problem: Return a cache usable string token that is different based upon Accept header. Here is the function: def vary_by_ap_json(request, *args, **kwargs) -> str: """ Return a cache usable string token that is different based upon Accept header. """ if request.ap_json: return "ap_json" return "not_ap"
Return a cache usable string token that is different based upon Accept header.
19,849
from collections.abc import Callable from functools import partial, wraps from typing import ParamSpecArgs, ParamSpecKwargs from django.http import HttpRequest from django.views.decorators.cache import cache_page as dj_cache_page from core.models import Config VaryByFunc = Callable[[HttpRequest, ParamSpecArgs, ParamSpecKwargs], str] The provided code snippet includes necessary dependencies for implementing the `cache_page` function. Write a Python function `def cache_page( timeout: int | str = "cache_timeout_page_default", *, key_prefix: str = "", public_only: bool = False, vary_by: VaryByFunc | list[VaryByFunc] | None = None, )` to solve the following problem: Decorator for views that caches the page result. timeout can either be the number of seconds or the name of a SystemOptions value. If public_only is True, requests with an identity are not cached. Here is the function: def cache_page( timeout: int | str = "cache_timeout_page_default", *, key_prefix: str = "", public_only: bool = False, vary_by: VaryByFunc | list[VaryByFunc] | None = None, ): """ Decorator for views that caches the page result. timeout can either be the number of seconds or the name of a SystemOptions value. If public_only is True, requests with an identity are not cached. """ _timeout = timeout _prefix = key_prefix if callable(vary_by): vary_by = [vary_by] def decorator(function): @wraps(function) def inner(request, *args, **kwargs): if public_only: if request.user.is_authenticated: return function(request, *args, **kwargs) prefix = [_prefix] if isinstance(vary_by, list): prefix.extend([vfunc(request, *args, **kwargs) for vfunc in vary_by]) prefix = "".join(prefix) if isinstance(_timeout, str): timeout = getattr(Config.system, _timeout) else: timeout = _timeout return dj_cache_page(timeout=timeout, key_prefix=prefix)(function)( request, *args, **kwargs ) return inner return decorator
Decorator for views that caches the page result. timeout can either be the number of seconds or the name of a SystemOptions value. If public_only is True, requests with an identity are not cached.
19,850
from time import time from django.conf import settings from django.core.exceptions import MiddlewareNotUsed from core import sentry from core.models import Config The provided code snippet includes necessary dependencies for implementing the `show_toolbar` function. Write a Python function `def show_toolbar(request)` to solve the following problem: Determines whether to show the debug toolbar on a given page. Here is the function: def show_toolbar(request): """ Determines whether to show the debug toolbar on a given page. """ return settings.DEBUG and request.user.is_authenticated and request.user.admin
Determines whether to show the debug toolbar on a given page.
19,851
import datetime import logging import os import urllib.parse as urllib_parse from dateutil import parser from pyld import jsonld from core.exceptions import ActivityPubFormatError logger = logging.getLogger(__name__) schemas = { "unknown": { "contentType": "application/ld+json", "documentUrl": "unknown", "contextUrl": None, "document": { "@context": {}, }, }, "www.w3.org/ns/activitystreams": { "contentType": "application/ld+json", "documentUrl": "http://www.w3.org/ns/activitystreams", "contextUrl": None, "document": { "@context": { "@vocab": "_:", "xsd": "http://www.w3.org/2001/XMLSchema#", "as": "https://www.w3.org/ns/activitystreams#", "ldp": "http://www.w3.org/ns/ldp#", "vcard": "http://www.w3.org/2006/vcard/ns#", "id": "@id", "type": "@type", "Accept": "as:Accept", "Activity": "as:Activity", "IntransitiveActivity": "as:IntransitiveActivity", "Add": "as:Add", "Announce": "as:Announce", "Application": "as:Application", "Arrive": "as:Arrive", "Article": "as:Article", "Audio": "as:Audio", "Block": "as:Block", "Collection": "as:Collection", "CollectionPage": "as:CollectionPage", "Relationship": "as:Relationship", "Create": "as:Create", "Delete": "as:Delete", "Dislike": "as:Dislike", "Document": "as:Document", "Event": "as:Event", "Follow": "as:Follow", "Flag": "as:Flag", "Group": "as:Group", "Ignore": "as:Ignore", "Image": "as:Image", "Invite": "as:Invite", "Join": "as:Join", "Leave": "as:Leave", "Like": "as:Like", "Link": "as:Link", "Mention": "as:Mention", "Note": "as:Note", "Object": "as:Object", "Offer": "as:Offer", "OrderedCollection": "as:OrderedCollection", "OrderedCollectionPage": "as:OrderedCollectionPage", "Organization": "as:Organization", "Page": "as:Page", "Person": "as:Person", "Place": "as:Place", "Profile": "as:Profile", "Question": "as:Question", "Reject": "as:Reject", "Remove": "as:Remove", "Service": "as:Service", "TentativeAccept": "as:TentativeAccept", "TentativeReject": "as:TentativeReject", "Tombstone": "as:Tombstone", "Undo": "as:Undo", "Update": "as:Update", "Video": "as:Video", "View": "as:View", "Listen": "as:Listen", "Read": "as:Read", "Move": "as:Move", "Travel": "as:Travel", "IsFollowing": "as:IsFollowing", "IsFollowedBy": "as:IsFollowedBy", "IsContact": "as:IsContact", "IsMember": "as:IsMember", "subject": {"@id": "as:subject", "@type": "@id"}, "relationship": {"@id": "as:relationship", "@type": "@id"}, "actor": {"@id": "as:actor", "@type": "@id"}, "attributedTo": {"@id": "as:attributedTo", "@type": "@id"}, "attachment": {"@id": "as:attachment", "@type": "@id"}, "bcc": {"@id": "as:bcc", "@type": "@id"}, "bto": {"@id": "as:bto", "@type": "@id"}, "cc": {"@id": "as:cc", "@type": "@id"}, "context": {"@id": "as:context", "@type": "@id"}, "current": {"@id": "as:current", "@type": "@id"}, "first": {"@id": "as:first", "@type": "@id"}, "generator": {"@id": "as:generator", "@type": "@id"}, "icon": {"@id": "as:icon", "@type": "@id"}, "image": {"@id": "as:image", "@type": "@id"}, "inReplyTo": {"@id": "as:inReplyTo", "@type": "@id"}, "items": {"@id": "as:items", "@type": "@id"}, "instrument": {"@id": "as:instrument", "@type": "@id"}, "orderedItems": { "@id": "as:items", "@type": "@id", "@container": "@list", }, "last": {"@id": "as:last", "@type": "@id"}, "location": {"@id": "as:location", "@type": "@id"}, "next": {"@id": "as:next", "@type": "@id"}, "object": {"@id": "as:object", "@type": "@id"}, "oneOf": {"@id": "as:oneOf", "@type": "@id"}, "anyOf": {"@id": "as:anyOf", "@type": "@id"}, "closed": {"@id": "as:closed", "@type": "xsd:dateTime"}, "origin": {"@id": "as:origin", "@type": "@id"}, "accuracy": {"@id": "as:accuracy", "@type": "xsd:float"}, "prev": {"@id": "as:prev", "@type": "@id"}, "preview": {"@id": "as:preview", "@type": "@id"}, "replies": {"@id": "as:replies", "@type": "@id"}, "result": {"@id": "as:result", "@type": "@id"}, "audience": {"@id": "as:audience", "@type": "@id"}, "partOf": {"@id": "as:partOf", "@type": "@id"}, "tag": {"@id": "as:tag", "@type": "@id"}, "target": {"@id": "as:target", "@type": "@id"}, "to": {"@id": "as:to", "@type": "@id"}, "url": {"@id": "as:url", "@type": "@id"}, "altitude": {"@id": "as:altitude", "@type": "xsd:float"}, "content": "as:content", "contentMap": {"@id": "as:content", "@container": "@language"}, "name": "as:name", "nameMap": {"@id": "as:name", "@container": "@language"}, "duration": {"@id": "as:duration", "@type": "xsd:duration"}, "endTime": {"@id": "as:endTime", "@type": "xsd:dateTime"}, "height": {"@id": "as:height", "@type": "xsd:nonNegativeInteger"}, "href": {"@id": "as:href", "@type": "@id"}, "hreflang": "as:hreflang", "latitude": {"@id": "as:latitude", "@type": "xsd:float"}, "longitude": {"@id": "as:longitude", "@type": "xsd:float"}, "mediaType": "as:mediaType", "published": {"@id": "as:published", "@type": "xsd:dateTime"}, "radius": {"@id": "as:radius", "@type": "xsd:float"}, "rel": "as:rel", "startIndex": { "@id": "as:startIndex", "@type": "xsd:nonNegativeInteger", }, "startTime": {"@id": "as:startTime", "@type": "xsd:dateTime"}, "summary": "as:summary", "summaryMap": {"@id": "as:summary", "@container": "@language"}, "totalItems": { "@id": "as:totalItems", "@type": "xsd:nonNegativeInteger", }, "units": "as:units", "updated": {"@id": "as:updated", "@type": "xsd:dateTime"}, "width": {"@id": "as:width", "@type": "xsd:nonNegativeInteger"}, "describes": {"@id": "as:describes", "@type": "@id"}, "formerType": {"@id": "as:formerType", "@type": "@id"}, "deleted": {"@id": "as:deleted", "@type": "xsd:dateTime"}, "inbox": {"@id": "ldp:inbox", "@type": "@id"}, "outbox": {"@id": "as:outbox", "@type": "@id"}, "following": {"@id": "as:following", "@type": "@id"}, "followers": {"@id": "as:followers", "@type": "@id"}, "streams": {"@id": "as:streams", "@type": "@id"}, "preferredUsername": "as:preferredUsername", "endpoints": {"@id": "as:endpoints", "@type": "@id"}, "uploadMedia": {"@id": "as:uploadMedia", "@type": "@id"}, "proxyUrl": {"@id": "as:proxyUrl", "@type": "@id"}, "liked": {"@id": "as:liked", "@type": "@id"}, "oauthAuthorizationEndpoint": { "@id": "as:oauthAuthorizationEndpoint", "@type": "@id", }, "oauthTokenEndpoint": {"@id": "as:oauthTokenEndpoint", "@type": "@id"}, "provideClientKey": {"@id": "as:provideClientKey", "@type": "@id"}, "signClientKey": {"@id": "as:signClientKey", "@type": "@id"}, "sharedInbox": {"@id": "as:sharedInbox", "@type": "@id"}, "Public": {"@id": "as:Public", "@type": "@id"}, "source": "as:source", "likes": {"@id": "as:likes", "@type": "@id"}, "shares": {"@id": "as:shares", "@type": "@id"}, "alsoKnownAs": {"@id": "as:alsoKnownAs", "@type": "@id"}, } }, }, "w3id.org/security/v1": { "contentType": "application/ld+json", "documentUrl": "http://w3id.org/security/v1", "contextUrl": None, "document": { "@context": { "id": "@id", "type": "@type", "dc": "http://purl.org/dc/terms/", "sec": "https://w3id.org/security#", "xsd": "http://www.w3.org/2001/XMLSchema#", "EcdsaKoblitzSignature2016": "sec:EcdsaKoblitzSignature2016", "Ed25519Signature2018": "sec:Ed25519Signature2018", "EncryptedMessage": "sec:EncryptedMessage", "GraphSignature2012": "sec:GraphSignature2012", "LinkedDataSignature2015": "sec:LinkedDataSignature2015", "LinkedDataSignature2016": "sec:LinkedDataSignature2016", "CryptographicKey": "sec:Key", "authenticationTag": "sec:authenticationTag", "canonicalizationAlgorithm": "sec:canonicalizationAlgorithm", "cipherAlgorithm": "sec:cipherAlgorithm", "cipherData": "sec:cipherData", "cipherKey": "sec:cipherKey", "created": {"@id": "dc:created", "@type": "xsd:dateTime"}, "creator": {"@id": "dc:creator", "@type": "@id"}, "digestAlgorithm": "sec:digestAlgorithm", "digestValue": "sec:digestValue", "domain": "sec:domain", "encryptionKey": "sec:encryptionKey", "expiration": {"@id": "sec:expiration", "@type": "xsd:dateTime"}, "expires": {"@id": "sec:expiration", "@type": "xsd:dateTime"}, "initializationVector": "sec:initializationVector", "iterationCount": "sec:iterationCount", "nonce": "sec:nonce", "normalizationAlgorithm": "sec:normalizationAlgorithm", "owner": {"@id": "sec:owner", "@type": "@id"}, "password": "sec:password", "privateKey": {"@id": "sec:privateKey", "@type": "@id"}, "privateKeyPem": "sec:privateKeyPem", "publicKey": {"@id": "sec:publicKey", "@type": "@id"}, "publicKeyBase58": "sec:publicKeyBase58", "publicKeyPem": "sec:publicKeyPem", "publicKeyWif": "sec:publicKeyWif", "publicKeyService": {"@id": "sec:publicKeyService", "@type": "@id"}, "revoked": {"@id": "sec:revoked", "@type": "xsd:dateTime"}, "salt": "sec:salt", "signature": "sec:signature", "signatureAlgorithm": "sec:signingAlgorithm", "signatureValue": "sec:signatureValue", } }, }, "w3id.org/identity/v1": { "contentType": "application/ld+json", "documentUrl": "http://w3id.org/identity/v1", "contextUrl": None, "document": { "@context": { "id": "@id", "type": "@type", "cred": "https://w3id.org/credentials#", "dc": "http://purl.org/dc/terms/", "identity": "https://w3id.org/identity#", "perm": "https://w3id.org/permissions#", "ps": "https://w3id.org/payswarm#", "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdfs": "http://www.w3.org/2000/01/rdf-schema#", "sec": "https://w3id.org/security#", "schema": "http://schema.org/", "xsd": "http://www.w3.org/2001/XMLSchema#", "Group": "https://www.w3.org/ns/activitystreams#Group", "claim": {"@id": "cred:claim", "@type": "@id"}, "credential": {"@id": "cred:credential", "@type": "@id"}, "issued": {"@id": "cred:issued", "@type": "xsd:dateTime"}, "issuer": {"@id": "cred:issuer", "@type": "@id"}, "recipient": {"@id": "cred:recipient", "@type": "@id"}, "Credential": "cred:Credential", "CryptographicKeyCredential": "cred:CryptographicKeyCredential", "about": {"@id": "schema:about", "@type": "@id"}, "address": {"@id": "schema:address", "@type": "@id"}, "addressCountry": "schema:addressCountry", "addressLocality": "schema:addressLocality", "addressRegion": "schema:addressRegion", "comment": "rdfs:comment", "created": {"@id": "dc:created", "@type": "xsd:dateTime"}, "creator": {"@id": "dc:creator", "@type": "@id"}, "description": "schema:description", "email": "schema:email", "familyName": "schema:familyName", "givenName": "schema:givenName", "image": {"@id": "schema:image", "@type": "@id"}, "label": "rdfs:label", "name": "schema:name", "postalCode": "schema:postalCode", "streetAddress": "schema:streetAddress", "title": "dc:title", "url": {"@id": "schema:url", "@type": "@id"}, "Person": "schema:Person", "PostalAddress": "schema:PostalAddress", "Organization": "schema:Organization", "identityService": {"@id": "identity:identityService", "@type": "@id"}, "idp": {"@id": "identity:idp", "@type": "@id"}, "Identity": "identity:Identity", "paymentProcessor": "ps:processor", "preferences": {"@id": "ps:preferences", "@type": "@vocab"}, "cipherAlgorithm": "sec:cipherAlgorithm", "cipherData": "sec:cipherData", "cipherKey": "sec:cipherKey", "digestAlgorithm": "sec:digestAlgorithm", "digestValue": "sec:digestValue", "domain": "sec:domain", "expires": {"@id": "sec:expiration", "@type": "xsd:dateTime"}, "initializationVector": "sec:initializationVector", "member": {"@id": "schema:member", "@type": "@id"}, "memberOf": {"@id": "schema:memberOf", "@type": "@id"}, "nonce": "sec:nonce", "normalizationAlgorithm": "sec:normalizationAlgorithm", "owner": {"@id": "sec:owner", "@type": "@id"}, "password": "sec:password", "privateKey": {"@id": "sec:privateKey", "@type": "@id"}, "privateKeyPem": "sec:privateKeyPem", "publicKey": {"@id": "sec:publicKey", "@type": "@id"}, "publicKeyPem": "sec:publicKeyPem", "publicKeyService": {"@id": "sec:publicKeyService", "@type": "@id"}, "revoked": {"@id": "sec:revoked", "@type": "xsd:dateTime"}, "signature": "sec:signature", "signatureAlgorithm": "sec:signatureAlgorithm", "signatureValue": "sec:signatureValue", "CryptographicKey": "sec:Key", "EncryptedMessage": "sec:EncryptedMessage", "GraphSignature2012": "sec:GraphSignature2012", "LinkedDataSignature2015": "sec:LinkedDataSignature2015", "accessControl": {"@id": "perm:accessControl", "@type": "@id"}, "writePermission": {"@id": "perm:writePermission", "@type": "@id"}, } }, }, "www.w3.org/ns/did/v1": { "contentType": "application/ld+json", "documentUrl": "www.w3.org/ns/did/v1", "contextUrl": None, "document": { "@context": { "@protected": True, "id": "@id", "type": "@type", "alsoKnownAs": { "@id": "https://www.w3.org/ns/activitystreams#alsoKnownAs", "@type": "@id", }, "assertionMethod": { "@id": "https://w3id.org/security#assertionMethod", "@type": "@id", "@container": "@set", }, "authentication": { "@id": "https://w3id.org/security#authenticationMethod", "@type": "@id", "@container": "@set", }, "capabilityDelegation": { "@id": "https://w3id.org/security#capabilityDelegationMethod", "@type": "@id", "@container": "@set", }, "capabilityInvocation": { "@id": "https://w3id.org/security#capabilityInvocationMethod", "@type": "@id", "@container": "@set", }, "controller": { "@id": "https://w3id.org/security#controller", "@type": "@id", }, "keyAgreement": { "@id": "https://w3id.org/security#keyAgreementMethod", "@type": "@id", "@container": "@set", }, "service": { "@id": "https://www.w3.org/ns/did#service", "@type": "@id", "@context": { "@protected": True, "id": "@id", "type": "@type", "serviceEndpoint": { "@id": "https://www.w3.org/ns/did#serviceEndpoint", "@type": "@id", }, }, }, "verificationMethod": { "@id": "https://w3id.org/security#verificationMethod", "@type": "@id", }, } }, }, "w3id.org/security/data-integrity/v1": { "contentType": "application/ld+json", "documentUrl": "https://w3id.org/security/data-integrity/v1", "contextUrl": None, "document": { "@context": { "id": "@id", "type": "@type", "@protected": True, "proof": { "@id": "https://w3id.org/security#proof", "@type": "@id", "@container": "@graph", }, "DataIntegrityProof": { "@id": "https://w3id.org/security#DataIntegrityProof", "@context": { "@protected": True, "id": "@id", "type": "@type", "challenge": "https://w3id.org/security#challenge", "created": { "@id": "http://purl.org/dc/terms/created", "@type": "http://www.w3.org/2001/XMLSchema#dateTime", }, "domain": "https://w3id.org/security#domain", "expires": { "@id": "https://w3id.org/security#expiration", "@type": "http://www.w3.org/2001/XMLSchema#dateTime", }, "nonce": "https://w3id.org/security#nonce", "proofPurpose": { "@id": "https://w3id.org/security#proofPurpose", "@type": "@vocab", "@context": { "@protected": True, "id": "@id", "type": "@type", "assertionMethod": { "@id": "https://w3id.org/security#assertionMethod", "@type": "@id", "@container": "@set", }, "authentication": { "@id": "https://w3id.org/security#authenticationMethod", "@type": "@id", "@container": "@set", }, "capabilityInvocation": { "@id": "https://w3id.org/security#capabilityInvocationMethod", "@type": "@id", "@container": "@set", }, "capabilityDelegation": { "@id": "https://w3id.org/security#capabilityDelegationMethod", "@type": "@id", "@container": "@set", }, "keyAgreement": { "@id": "https://w3id.org/security#keyAgreementMethod", "@type": "@id", "@container": "@set", }, }, }, "cryptosuite": "https://w3id.org/security#cryptosuite", "proofValue": { "@id": "https://w3id.org/security#proofValue", "@type": "https://w3id.org/security#multibase", }, "verificationMethod": { "@id": "https://w3id.org/security#verificationMethod", "@type": "@id", }, }, }, } }, }, "w3id.org/security/multikey/v1": { "contentType": "application/ld+json", "documentUrl": "https://w3id.org/security/multikey/v1", "contextUrl": None, "document": { "@context": { "id": "@id", "type": "@type", "@protected": True, "Multikey": { "@id": "https://w3id.org/security#Multikey", "@context": { "@protected": True, "id": "@id", "type": "@type", "controller": { "@id": "https://w3id.org/security#controller", "@type": "@id", }, "revoked": { "@id": "https://w3id.org/security#revoked", "@type": "http://www.w3.org/2001/XMLSchema#dateTime", }, "expires": { "@id": "https://w3id.org/security#expiration", "@type": "http://www.w3.org/2001/XMLSchema#dateTime", }, "publicKeyMultibase": { "@id": "https://w3id.org/security#publicKeyMultibase", "@type": "https://w3id.org/security#multibase", }, "secretKeyMultibase": { "@id": "https://w3id.org/security#secretKeyMultibase", "@type": "https://w3id.org/security#multibase", }, }, }, }, }, }, "*/schemas/litepub-0.1.jsonld": { "contentType": "application/ld+json", "documentUrl": "http://w3id.org/security/v1", "contextUrl": None, "document": { "@context": [ "https://www.w3.org/ns/activitystreams", "https://w3id.org/security/v1", { "Emoji": "toot:Emoji", "Hashtag": "as:Hashtag", "PropertyValue": "schema:PropertyValue", "atomUri": "ostatus:atomUri", "conversation": {"@id": "ostatus:conversation", "@type": "@id"}, "discoverable": "toot:discoverable", "manuallyApprovesFollowers": "as:manuallyApprovesFollowers", "capabilities": "litepub:capabilities", "ostatus": "http://ostatus.org#", "schema": "http://schema.org#", "toot": "http://joinmastodon.org/ns#", "misskey": "https://misskey-hub.net/ns#", "fedibird": "http://fedibird.com/ns#", "value": "schema:value", "sensitive": "as:sensitive", "litepub": "http://litepub.social/ns#", "invisible": "litepub:invisible", "directMessage": "litepub:directMessage", "listMessage": {"@id": "litepub:listMessage", "@type": "@id"}, "quoteUrl": "as:quoteUrl", "quoteUri": "fedibird:quoteUri", "oauthRegistrationEndpoint": { "@id": "litepub:oauthRegistrationEndpoint", "@type": "@id", }, "EmojiReact": "litepub:EmojiReact", "ChatMessage": "litepub:ChatMessage", "alsoKnownAs": {"@id": "as:alsoKnownAs", "@type": "@id"}, "vcard": "http://www.w3.org/2006/vcard/ns#", "formerRepresentations": "litepub:formerRepresentations", }, ] }, }, "joinmastodon.org/ns": { "contentType": "application/ld+json", "documentUrl": "http://joinmastodon.org/ns", "contextUrl": None, "document": { "@context": { "toot": "http://joinmastodon.org/ns#", "discoverable": "toot:discoverable", "devices": "toot:devices", "featured": "toot:featured", "featuredTags": "toot:featuredTags", }, }, }, "funkwhale.audio/ns": { "contentType": "application/ld+json", "documentUrl": "http://funkwhale.audio/ns", "contextUrl": None, "document": { "@context": { "id": "@id", "type": "@type", "as": "https://www.w3.org/ns/activitystreams#", "schema": "http://schema.org#", "fw": "https://funkwhale.audio/ns#", "xsd": "http://www.w3.org/2001/XMLSchema#", "Album": "fw:Album", "Track": "fw:Track", "Artist": "fw:Artist", "Library": "fw:Library", "bitrate": {"@id": "fw:bitrate", "@type": "xsd:nonNegativeInteger"}, "size": {"@id": "fw:size", "@type": "xsd:nonNegativeInteger"}, "position": {"@id": "fw:position", "@type": "xsd:nonNegativeInteger"}, "disc": {"@id": "fw:disc", "@type": "xsd:nonNegativeInteger"}, "library": {"@id": "fw:library", "@type": "@id"}, "track": {"@id": "fw:track", "@type": "@id"}, "cover": {"@id": "fw:cover", "@type": "as:Link"}, "album": {"@id": "fw:album", "@type": "@id"}, "artists": {"@id": "fw:artists", "@type": "@id", "@container": "@list"}, "released": {"@id": "fw:released", "@type": "xsd:date"}, "musicbrainzId": "fw:musicbrainzId", "license": {"@id": "fw:license", "@type": "@id"}, "copyright": "fw:copyright", "category": "sc:category", "language": "sc:inLanguage", } }, }, "schema.org": { "contentType": "application/ld+json", "documentUrl": "https://schema.org/docs/jsonldcontext.json", "contextUrl": None, "document": { "@context": { "schema": "http://schema.org/", "PropertyValue": {"@id": "schema:PropertyValue"}, "value": {"@id": "schema:value"}, }, }, }, "purl.org/wytchspace/ns/ap/1.0": { "contentType": "application/ld+json", "documentUrl": "https://purl.org/wytchspace/ns/ap/1.0", "contextUrl": None, "document": { "@context": { "wytch": "https://ns.wytch.space/ap/1.0.jsonld", }, }, }, } def builtin_document_loader(url: str, options={}): # Get URL without scheme pieces = urllib_parse.urlparse(url) if pieces.hostname is None: logger.info(f"No host name for json-ld schema: {url!r}") return schemas["unknown"] key = pieces.hostname + pieces.path.rstrip("/") try: return schemas[key] except KeyError: try: key = "*" + pieces.path.rstrip("/") return schemas[key] except KeyError: # return an empty context instead of throwing an error logger.info(f"Ignoring unknown json-ld schema: {url!r}") return schemas["unknown"]
null
19,852
import datetime import logging import os import urllib.parse as urllib_parse from dateutil import parser from pyld import jsonld from core.exceptions import ActivityPubFormatError The provided code snippet includes necessary dependencies for implementing the `canonicalise` function. Write a Python function `def canonicalise(json_data: dict, include_security: bool = False) -> dict` to solve the following problem: Given an ActivityPub JSON-LD document, round-trips it through the LD systems to end up in a canonicalised, compacted format. If no context is provided, supplies one automatically. For most well-structured incoming data this won't actually do anything, but it's probably good to abide by the spec. Here is the function: def canonicalise(json_data: dict, include_security: bool = False) -> dict: """ Given an ActivityPub JSON-LD document, round-trips it through the LD systems to end up in a canonicalised, compacted format. If no context is provided, supplies one automatically. For most well-structured incoming data this won't actually do anything, but it's probably good to abide by the spec. """ if not isinstance(json_data, dict): raise ValueError("Pass decoded JSON data into LDDocument") context = json_data.get("@context", []) if not isinstance(context, list): context = [context] if not context: context.append("https://www.w3.org/ns/activitystreams") context.append( { "blurhash": "toot:blurhash", "Emoji": "toot:Emoji", "focalPoint": {"@container": "@list", "@id": "toot:focalPoint"}, "Hashtag": "as:Hashtag", "manuallyApprovesFollowers": "as:manuallyApprovesFollowers", "sensitive": "as:sensitive", "toot": "http://joinmastodon.org/ns#", "votersCount": "toot:votersCount", "featured": {"@id": "toot:featured", "@type": "@id"}, } ) if include_security: context.append("https://w3id.org/security/v1") json_data["@context"] = context return jsonld.compact(jsonld.expand(json_data), context)
Given an ActivityPub JSON-LD document, round-trips it through the LD systems to end up in a canonicalised, compacted format. If no context is provided, supplies one automatically. For most well-structured incoming data this won't actually do anything, but it's probably good to abide by the spec.
19,853
import datetime import logging import os import urllib.parse as urllib_parse from dateutil import parser from pyld import jsonld from core.exceptions import ActivityPubFormatError The provided code snippet includes necessary dependencies for implementing the `get_list` function. Write a Python function `def get_list(container, key) -> list` to solve the following problem: Given a JSON-LD value (that can be either a list, or a dict if it's just one item), always returns a list Here is the function: def get_list(container, key) -> list: """ Given a JSON-LD value (that can be either a list, or a dict if it's just one item), always returns a list""" if key not in container: return [] value = container[key] if not isinstance(value, list): return [value] return value
Given a JSON-LD value (that can be either a list, or a dict if it's just one item), always returns a list
19,854
import datetime import logging import os import urllib.parse as urllib_parse from dateutil import parser from pyld import jsonld from core.exceptions import ActivityPubFormatError The provided code snippet includes necessary dependencies for implementing the `get_str_or_id` function. Write a Python function `def get_str_or_id(value: str | dict | None, key: str = "id") -> str | None` to solve the following problem: Given a value that could be a str or {"id": str}, return the str Here is the function: def get_str_or_id(value: str | dict | None, key: str = "id") -> str | None: """ Given a value that could be a str or {"id": str}, return the str """ if isinstance(value, str): return value elif isinstance(value, dict): return value.get(key) return None
Given a value that could be a str or {"id": str}, return the str
19,855
import datetime import logging import os import urllib.parse as urllib_parse from dateutil import parser from pyld import jsonld from core.exceptions import ActivityPubFormatError DATETIME_MS_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" def format_ld_date(value: datetime.datetime) -> str: # We chop the timestamp to be identical to the timestamps returned by # Mastodon's API, because some clients like Toot! (for iOS) are especially # picky about timestamp parsing. return f"{value.strftime(DATETIME_MS_FORMAT)[:-4]}Z"
null
19,856
import datetime import logging import os import urllib.parse as urllib_parse from dateutil import parser from pyld import jsonld from core.exceptions import ActivityPubFormatError def parse_ld_date(value: str | None) -> datetime.datetime | None: if value is None: return None return parser.isoparse(value).replace(microsecond=0)
null
19,857
import datetime import logging import os import urllib.parse as urllib_parse from dateutil import parser from pyld import jsonld from core.exceptions import ActivityPubFormatError The provided code snippet includes necessary dependencies for implementing the `get_first_image_url` function. Write a Python function `def get_first_image_url(data) -> str | None` to solve the following problem: 'icon' and 'image' fields might be a dict or a list. Return the first 'url' for something that looks to be for an image. Here is the function: def get_first_image_url(data) -> str | None: """ 'icon' and 'image' fields might be a dict or a list. Return the first 'url' for something that looks to be for an image. """ if isinstance(data, list): for itm in data: if isinstance(itm, dict) and "url" in itm: return itm["url"] elif isinstance(data, dict): return data.get("url") return None
'icon' and 'image' fields might be a dict or a list. Return the first 'url' for something that looks to be for an image.
19,858
import datetime import logging import os import urllib.parse as urllib_parse from dateutil import parser from pyld import jsonld from core.exceptions import ActivityPubFormatError class ActivityPubFormatError(ActivityPubError): """ A problem with an ActivityPub message's format/keys """ The provided code snippet includes necessary dependencies for implementing the `get_value_or_map` function. Write a Python function `def get_value_or_map(data, key, map_key)` to solve the following problem: Retrieves a value that can either be a top level key (like "name") or an entry in a map (like nameMap). Here is the function: def get_value_or_map(data, key, map_key): """ Retrieves a value that can either be a top level key (like "name") or an entry in a map (like nameMap). """ if key in data: return data[key] if map_key in data: if "und" in map_key: return data[map_key]["und"] return list(data[map_key].values())[0] raise ActivityPubFormatError(f"Cannot find {key} or {map_key}")
Retrieves a value that can either be a top level key (like "name") or an entry in a map (like nameMap).
19,859
import datetime import logging import os import urllib.parse as urllib_parse from dateutil import parser from pyld import jsonld from core.exceptions import ActivityPubFormatError def media_type_from_filename(filename): _, extension = os.path.splitext(filename) if extension == ".png": return "image/png" elif extension in [".jpg", ".jpeg"]: return "image/jpeg" elif extension == ".gif": return "image/gif" elif extension == ".apng": return "image/apng" elif extension == ".webp": return "image/webp" else: return "application/octet-stream"
null
19,860
from contextlib import contextmanager from django.conf import settings def noop(*args, **kwargs): pass
null
19,861
from contextlib import contextmanager from django.conf import settings def noop_context(*args, **kwargs): yield
null
19,862
from contextlib import contextmanager from django.conf import settings def set_takahe_app(name: str): set_tag("takahe.app", name)
null
19,863
from contextlib import contextmanager from django.conf import settings def scope_clear(scope): if scope: scope.clear()
null
19,864
from contextlib import contextmanager from django.conf import settings def set_transaction_name(scope, name: str): if scope: scope.set_transaction_name(name)
null
19,865
from django.conf import settings from core.models import Config def config_context(request): return { "config": Config.system, "allow_migration": settings.SETUP.ALLOW_USER_MIGRATION, "top_section": request.path.strip("/").split("/")[0], "opengraph_defaults": { "og:site_name": Config.system.site_name, "og:type": "website", "og:title": Config.system.site_name, "og:url": request.build_absolute_uri(), }, }
null
19,866
from typing import ClassVar import markdown_it from django.conf import settings from django.http import HttpResponse from django.shortcuts import redirect from django.utils.decorators import method_decorator from django.utils.safestring import mark_safe from django.views.generic import TemplateView, View from django.views.static import serve from activities.services.timeline import TimelineService from activities.views.timelines import Home from core.decorators import cache_page from core.models import Config class About(TemplateView): template_name = "about.html" def get_context_data(self): service = TimelineService(None) return { "current_page": "about", "content": mark_safe( markdown_it.MarkdownIt().render(Config.system.site_about) ), "posts": service.local()[:10], } class Home(TemplateView): """ Homepage for logged-in users - shows identities primarily. """ template_name = "activities/home.html" def get_context_data(self): return { "identities": Identity.objects.filter( users__pk=self.request.user.pk ).order_by("created"), } cache_page("cache_timeout_page_timeline", public_only=True), name="dispatch" ) def homepage(request): if request.user.is_authenticated: return Home.as_view()(request) elif request.domain and request.domain.config_domain.single_user: return redirect(f"/@{request.domain.config_domain.single_user}/") else: return About.as_view()(request)
null
19,867
from typing import ClassVar import markdown_it from django.conf import settings from django.http import HttpResponse from django.shortcuts import redirect from django.utils.decorators import method_decorator from django.utils.safestring import mark_safe from django.views.generic import TemplateView, View from django.views.static import serve from activities.services.timeline import TimelineService from activities.views.timelines import Home from core.decorators import cache_page from core.models import Config The provided code snippet includes necessary dependencies for implementing the `custom_static_serve` function. Write a Python function `def custom_static_serve(*args, **keywords)` to solve the following problem: Set the correct `Content-Type` header for static WebP images since Django cannot guess the MIME type of WebP images. Here is the function: def custom_static_serve(*args, **keywords): """ Set the correct `Content-Type` header for static WebP images since Django cannot guess the MIME type of WebP images. """ response = serve(*args, **keywords) if keywords["path"].endswith(".webp"): response.headers["Content-Type"] = "image/webp" return response
Set the correct `Content-Type` header for static WebP images since Django cannot guess the MIME type of WebP images.
19,868
import os import secrets import sys import urllib.parse from pathlib import Path from typing import Literal import dj_database_url import django_cache_url import httpx import sentry_sdk from corsheaders.defaults import default_headers from pydantic import AnyUrl, BaseSettings, EmailStr, Field, validator from takahe import __version__ def as_bool(v: str | list[str] | None): if v is None: return False if isinstance(v, str): v = [v] return v[0].lower() in ("true", "yes", "t", "1")
null
19,869
from django.contrib.auth.decorators import user_passes_test def moderator_required(function): return user_passes_test( lambda user: user.is_authenticated and (user.admin or user.moderator) )(function)
null
19,870
from django.contrib.auth.decorators import user_passes_test def admin_required(function): return user_passes_test(lambda user: user.is_authenticated and user.admin)(function)
null
19,871
from django.http import Http404 from users.models import Domain, Identity def by_handle_or_404(request, handle, local=True, fetch=False) -> Identity: """ Retrieves an Identity by its long or short handle. Domain-sensitive, so it will understand short handles on alternate domains. """ if "@" not in handle: if "host" not in request.headers: raise Http404("No hostname available") username = handle domain_instance = Domain.get_domain(request.headers["host"]) if domain_instance is None: raise Http404("No matching domains found") domain = domain_instance.domain else: username, domain = handle.split("@", 1) if not Domain.is_valid_domain(domain): raise Http404("Invalid domain") # Resolve the domain to the display domain domain_instance = Domain.get_domain(domain) if domain_instance is None: domain_instance = Domain.get_remote_domain(domain) domain = domain_instance.domain identity = Identity.by_username_and_domain( username, domain_instance, local=local, fetch=fetch, ) if identity is None: raise Http404(f"No identity for handle {handle}") if identity.blocked: raise Http404("Blocked user") return identity The provided code snippet includes necessary dependencies for implementing the `by_handle_for_user_or_404` function. Write a Python function `def by_handle_for_user_or_404(request, handle)` to solve the following problem: Retrieves an identity the local user can control via their handle, or raises a 404. Here is the function: def by_handle_for_user_or_404(request, handle): """ Retrieves an identity the local user can control via their handle, or raises a 404. """ identity = by_handle_or_404(request, handle, local=True, fetch=False) if not identity.users.filter(id=request.user.id).exists(): raise Http404("Current user does not own identity") return identity
Retrieves an identity the local user can control via their handle, or raises a 404.
19,872
from users.services import AnnouncementService def user_context(request): return { "announcements": ( AnnouncementService(request.user).visible() if request.user.is_authenticated else AnnouncementService.visible_anonymous() ) }
null
19,873
import json import logging import re import ssl from functools import cached_property from typing import Optional import httpx import pydantic import urlman from django.conf import settings from django.core.exceptions import ValidationError from django.db import models from core.models import Config from stator.models import State, StateField, StateGraph, StatorModel from users.schemas import NodeInfo class Domain(StatorModel): """ Represents a domain that a user can have an account on. For protocol reasons, if we want to allow custom usernames per domain, each "display" domain (the one in the handle) must either let us serve on it directly, or have a "service" domain that maps to it uniquely that we can serve on that. That way, someone coming in with just an Actor URI as their entrypoint can still try to webfinger preferredUsername@actorDomain and we can return an appropriate response. It's possible to just have one domain do both jobs, of course. This model also represents _other_ servers' domains, which we treat as display domains for now, until we start doing better probing. """ domain = models.CharField( max_length=250, primary_key=True, validators=[_domain_validator] ) service_domain = models.CharField( max_length=250, null=True, blank=True, db_index=True, unique=True, ) state = StateField(DomainStates) # nodeinfo 2.0 detail about the remote server nodeinfo = models.JSONField(null=True, blank=True) # If we own this domain local = models.BooleanField() # If we have blocked this domain from interacting with us blocked = models.BooleanField(default=False) # Domains can be joinable by any user of the instance (as the default one # should) public = models.BooleanField(default=False) # If this is the default domain (shown as the default entry for new users) default = models.BooleanField(default=False) # Domains can also be linked to one or more users for their private use # This should be display domains ONLY users = models.ManyToManyField("users.User", related_name="domains", blank=True) # Free-form notes field for admins notes = models.TextField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class urls(urlman.Urls): root = "/admin/domains/" create = "/admin/domains/create/" edit = "/admin/domains/{self.domain}/" delete = "{edit}delete/" root_federation = "/admin/federation/" edit_federation = "/admin/federation/{self.domain}/" class Meta: indexes: list = [] def is_valid_domain(cls, domain: str) -> bool: """ Check if a domain is valid, domain must be lowercase """ return ( re.match( r"^(?:[a-z0-9](?:[a-z0-9-_]{0,61}[a-z0-9])?\.)+[a-z0-9][a-z0-9-_]{0,61}[a-z]$", domain, ) is not None ) def get_remote_domain(cls, domain: str) -> "Domain": return cls.objects.get_or_create(domain=domain.lower(), local=False)[0] def get_domain(cls, domain: str) -> Optional["Domain"]: try: return cls.objects.get( models.Q(domain=domain.lower()) | models.Q(service_domain=domain.lower()) ) except cls.DoesNotExist: return None def uri_domain(self) -> str: if self.service_domain: return self.service_domain return self.domain def available_for_user(cls, user): """ Returns domains that are available for the user to put an identity on """ return cls.objects.filter( models.Q(public=True) | models.Q(users__id=user.id), local=True, ).order_by("-default", "domain") def __str__(self): return self.domain def save(self, *args, **kwargs): # Ensure that we are not conflicting with other domains if Domain.objects.filter(service_domain=self.domain).exists(): raise ValueError( f"Domain {self.domain} is already a service domain elsewhere!" ) if self.service_domain: if Domain.objects.filter(domain=self.service_domain).exists(): raise ValueError( f"Service domain {self.service_domain} is already a domain elsewhere!" ) super().save(*args, **kwargs) def fetch_nodeinfo(self) -> NodeInfo | None: """ Fetch the /NodeInfo/2.0 for the domain """ nodeinfo20_url = f"https://{self.domain}/nodeinfo/2.0" with httpx.Client( timeout=settings.SETUP.REMOTE_TIMEOUT, headers={"User-Agent": settings.TAKAHE_USER_AGENT}, ) as client: try: response = client.get( f"https://{self.domain}/.well-known/nodeinfo", follow_redirects=True, headers={"Accept": "application/json"}, ) except httpx.HTTPError: pass except (ssl.SSLCertVerificationError, ssl.SSLError): return None else: try: for link in response.json().get("links", []): if ( link.get("rel") == "http://nodeinfo.diaspora.software/ns/schema/2.0" ): nodeinfo20_url = link.get("href", nodeinfo20_url) break except json.JSONDecodeError: pass try: response = client.get( nodeinfo20_url, follow_redirects=True, headers={"Accept": "application/json"}, ) response.raise_for_status() except (httpx.HTTPError, ssl.SSLCertVerificationError) as ex: response = getattr(ex, "response", None) if ( response and response.status_code < 500 and response.status_code not in [401, 403, 404, 406, 410] ): logger.warning( "Client error fetching nodeinfo: %d %s %s", response.status_code, nodeinfo20_url, ex, extra={ "content": response.content, "domain": self.domain, }, ) return None try: info = NodeInfo(**response.json()) except (json.JSONDecodeError, pydantic.ValidationError) as ex: logger.warning( "Client error decoding nodeinfo: %s %s", nodeinfo20_url, ex, extra={ "domain": self.domain, }, ) return None return info def software(self): if self.nodeinfo: software = self.nodeinfo.get("software", {}) name = software.get("name", "unknown") version = software.get("version", "unknown") return f"{name:.10} - {version:.10}" return None def recursively_blocked(self) -> bool: """ Checks for blocks on all right subsets of this domain, except the very last part of the TLD. Yes, I know this weirdly lets you block ".co.uk" or whatever, but people can do that if they want I guess. """ # Efficient short-circuit if self.blocked: return True # Build domain list domain_parts = [self.domain] while "." in domain_parts[-1]: domain_parts.append(domain_parts[-1].split(".", 1)[1]) # See if any of those are blocked return Domain.objects.filter(domain__in=domain_parts, blocked=True).exists() ### Config ### def config_domain(self) -> Config.DomainOptions: return Config.load_domain(self) def _domain_validator(value: str): if not Domain.is_valid_domain(value): raise ValidationError( "%(value)s is not a valid domain", params={"value": value}, )
null
19,874
import re from typing import Set from prompt_toolkit import prompt from prompt_toolkit import PromptSession from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion import WordCompleter from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.key_binding import KeyBindings bindings = KeyBindings() The provided code snippet includes necessary dependencies for implementing the `create_keybindings` function. Write a Python function `def create_keybindings(key: str = "c-@") -> KeyBindings` to solve the following problem: Create keybindings for prompt_toolkit. Default key is ctrl+space. For possible keybindings, see: https://python-prompt-toolkit.readthedocs.io/en/stable/pages/advanced_topics/key_bindings.html#list-of-special-keys Here is the function: def create_keybindings(key: str = "c-@") -> KeyBindings: """ Create keybindings for prompt_toolkit. Default key is ctrl+space. For possible keybindings, see: https://python-prompt-toolkit.readthedocs.io/en/stable/pages/advanced_topics/key_bindings.html#list-of-special-keys """ @bindings.add(key) def _(event: dict) -> None: event.app.exit(result=event.app.current_buffer.text) return bindings
Create keybindings for prompt_toolkit. Default key is ctrl+space. For possible keybindings, see: https://python-prompt-toolkit.readthedocs.io/en/stable/pages/advanced_topics/key_bindings.html#list-of-special-keys
19,875
import re from typing import Set from prompt_toolkit import prompt from prompt_toolkit import PromptSession from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion import WordCompleter from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.key_binding import KeyBindings def create_session() -> PromptSession: return PromptSession(history=InMemoryHistory())
null