Skip to content

Commit

Permalink
Merge branch 'main' of github.com:laws-africa/peachjam
Browse files Browse the repository at this point in the history
  • Loading branch information
nickmwangemi committed Aug 10, 2023
2 parents 0cf6b05 + a9b3590 commit 0be59ce
Show file tree
Hide file tree
Showing 13 changed files with 247 additions and 8 deletions.
6 changes: 3 additions & 3 deletions peachjam/js/locale/fr/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@
"Delete": "Supprimez",
"Document nature": "Type de document",
"Document type": "Type de document",
"Edit": "Edit",
"Edit": "Modifier",
"Enter end date": "Entrez la date de fin",
"Enter start date": "Entrez la date de début",
"Expand all": "Développer tout",
"Filters": "Filtres",
"Judges": "Juges",
"Jurisdiction": "Juridiction",
"Language": "Langue",
"Link citation": "Link citation",
"Link citation": "Citation de lien",
"Loading": "En cours de chargement",
"Locality": "Localité",
"Matter type": "Type de matière",
Expand All @@ -48,7 +48,7 @@
"Relevance": "Pertinence",
"Search": "Recherche",
"Search {{appName}}": {
"": "Search {{appName}}..."
"": "Rechercher dans {{appName}}..."
},
"Search document content": "Rechercher le contenu du document",
"Search documents": "Rechercher des documents",
Expand Down
5 changes: 5 additions & 0 deletions peachjam/js/locale/pt/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,15 @@
"Delete": "Excluir",
"Document nature": "Natureza do documento",
"Document type": "Tipo de documento",
"Edit": "Editar",
"Enter end date": "Digite a data final",
"Enter start date": "Digite a data inicial",
"Expand all": "Expandir tudo",
"Filters": "Filtros",
"Judges": "Juízes",
"Jurisdiction": "Jurisdição",
"Language": "Idioma",
"Link citation": "Citação de link",
"Loading": "Carregando...",
"Locality": "Localidade",
"Matter type": "Tipo de matéria",
Expand All @@ -45,6 +47,9 @@
"Regional body": "Corpo regional",
"Relevance": "Relevância",
"Search": "Pesquisa",
"Search {{appName}}": {
"": "Pesquisar {{appName}}..."
},
"Search document content": "Pesquisar conteúdo de documento",
"Search documents": "Pesquisar documentos",
"Search table of contents": "Pesquisar na tabela de conteúdos",
Expand Down
6 changes: 3 additions & 3 deletions peachjam/js/locale/sw/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@
"Delete": "Futa",
"Document nature": "Asili ya hati",
"Document type": "Aina ya hati",
"Edit": "Edit",
"Edit": "Hariri",
"Enter end date": "Weka tarehe ya mwisho",
"Enter start date": "Weka tarehe ya kuanza",
"Expand all": "Panua zote",
"Filters": "Vichujio",
"Judges": "Majaji",
"Jurisdiction": "Mamlaka ya kisheria",
"Language": "Lugha",
"Link citation": "Link citation",
"Link citation": "Nukuu ya kiungo",
"Loading": "Inapakia",
"Locality": "Eneo",
"Matter type": "Aina ya jambo",
Expand All @@ -48,7 +48,7 @@
"Relevance": "Muhimu",
"Search": "Tafuta",
"Search {{appName}}": {
"": "Search {{appName}}..."
"": "Tafuta {{appName}}..."
},
"Search document content": "Tafuta yaliyomo kwenye waraka",
"Search documents": "Tafuta nyaraka",
Expand Down
1 change: 1 addition & 0 deletions peachjam/models/gazette.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ class Gazette(CoreDocument):
class Meta(CoreDocument.Meta):
verbose_name = _("gazette")
verbose_name_plural = _("gazettes")
permissions = [("api_gazette", "API gazette access")]

def pre_save(self):
self.frbr_uri_doctype = "officialGazette"
Expand Down
1 change: 1 addition & 0 deletions peachjam/models/judgment.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,7 @@ class Meta(CoreDocument.Meta):
ordering = ["title"]
verbose_name = _("judgment")
verbose_name_plural = _("judgments")
permissions = [("api_judgment", "API judgment access")]

def __str__(self):
return self.title
Expand Down
14 changes: 13 additions & 1 deletion peachjam/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
"background_task",
"ckeditor",
"polymorphic",
"drf_spectacular",
]

MIDDLEWARE = [
Expand Down Expand Up @@ -267,9 +268,20 @@
"rest_framework.authentication.TokenAuthentication",
],
"DEFAULT_PERMISSION_CLASSES": ["rest_framework.permissions.DjangoModelPermissions"],
"DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"],
"DEFAULT_FILTER_BACKENDS": [
"django_filters.rest_framework.DjangoFilterBackend",
"rest_framework.filters.OrderingFilter",
],
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination",
"PAGE_SIZE": 10,
"DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema",
}

SPECTACULAR_SETTINGS = {
"TITLE": f'{PEACHJAM["APP_NAME"]} API',
"DESCRIPTION": "Read-only API for this website.",
"VERSION": "v1",
"SCHEMA_PATH_PREFIX_INSERT": "/api",
}

# Sentry
Expand Down
2 changes: 1 addition & 1 deletion peachjam/static/js/app-prod.js

Large diffs are not rendered by default.

21 changes: 21 additions & 0 deletions peachjam_api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Peach Jam API

This Django application is the Peach Jam API. It has two components:

1. an internal API for use by frontend components
2. a public-facing API for external consumption.

## Public API

The public API is read-only. Users must authenticate and require a specific permission to access a particular
document type through the API.

Full documentation of the API is available in OpenAPI format from these endpoints:

* `/api/v1/schema`: in [OpenAPI](https://swagger.io/specification/) format
* `/api/v1/schema/redoc`: in [Redoc](https://github.com/Redocly/redoc) format
* `/api/v1/schema/swagger-ui`: in [Swagger UI](https://swagger.io/tools/swagger-ui/) format

### Authentication

Authenticate with an `Authorization: Token <token>` header that includes your authentication token.
95 changes: 95 additions & 0 deletions peachjam_api/public_views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
from django.http import Http404, HttpResponse
from drf_spectacular.utils import OpenApiTypes, extend_schema
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.permissions import BasePermission, DjangoModelPermissions

from peachjam.models import Gazette, Judgment
from peachjam_api.serializers import GazetteSerializer, JudgmentSerializer


class JudgmentAPIPermission(BasePermission):
permission_name = "peachjam.api_judgment"

def has_permission(self, request, view):
# user must have perms to access judgments through the api
return (
request.user
and request.user.is_authenticated
and request.user.has_perm(self.permission_name)
)


class GazetteAPIPermission(JudgmentAPIPermission):
permission_name = "peachjam.api_gazette"


class BaseDocumentViewSet(viewsets.ReadOnlyModelViewSet):
permission_classes = [DjangoModelPermissions]
filterset_fields = {
"jurisdiction": ["exact"],
"work_frbr_uri": ["exact"],
"title": ["exact", "icontains"],
"date": ["exact", "gte", "lte"],
"updated_at": ["exact", "gte", "lte"],
"created_at": ["exact", "gte", "lte"],
}
ordering_fields = ["title", "date", "updated_at", "created_at"]
ordering = ["updated_at"]

@extend_schema(responses={(200, "text/plain"): OpenApiTypes.STR})
@action(detail=True, url_path="source.txt")
def source_txt(self, request, pk=None):
"""Source document in text form (if available)."""
obj = self.get_object()
# we only allow certain formats
try:
content = getattr(obj, "document_content")
except AttributeError:
raise Http404()

# return content.content_text as a normal drf response object
return HttpResponse(content.content_text, content_type="text/plain")

@extend_schema(responses={(200, "application/pdf"): OpenApiTypes.BINARY})
@action(detail=True, url_path="source.pdf")
def source_pdf(self, request, pk=None):
"""Source document in PDF form (if available)."""
obj = self.get_object()
# we only allow certain formats
try:
source_file = getattr(obj, "source_file")
except AttributeError:
raise Http404()

if not source_file.file or source_file.mimetype != "application/pdf":
raise Http404()

return self.make_response(
source_file.file, source_file.mimetype, source_file.filename_for_download()
)

def make_response(self, f, content_type, fname):
file_bytes = f.read()
response = HttpResponse(file_bytes, content_type=content_type)
response["Content-Disposition"] = f"inline; filename={fname}"
response["Content-Length"] = str(len(file_bytes))
return response


class GazettesViewSet(BaseDocumentViewSet):
permission_classes = [
GazetteAPIPermission,
DjangoModelPermissions,
]
queryset = Gazette.objects.all()
serializer_class = GazetteSerializer


class JudgmentsViewSet(BaseDocumentViewSet):
permission_classes = [
JudgmentAPIPermission,
DjangoModelPermissions,
]
queryset = Judgment.objects.select_related("court").all()
serializer_class = JudgmentSerializer
59 changes: 59 additions & 0 deletions peachjam_api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
from peachjam.models import (
CitationLink,
CoreDocument,
Court,
Gazette,
Judgment,
Label,
Legislation,
Predicate,
Expand Down Expand Up @@ -137,3 +140,59 @@ class LabelSerializer(serializers.ModelSerializer):
class Meta:
model = Label
exclude = []


class CourtSerializer(serializers.ModelSerializer):
class Meta:
model = Court
fields = ["id", "name", "code"]


class BaseSerializerMixin:
def get_url(self, instance):
# TODO: check https
return self.context["request"].build_absolute_uri(instance.get_absolute_url())


class JudgmentSerializer(BaseSerializerMixin, serializers.ModelSerializer):
court = CourtSerializer(read_only=True)
url = serializers.SerializerMethodField()

class Meta:
model = Judgment
fields = (
"citation",
"court",
"created_at",
"date",
"expression_frbr_uri",
"jurisdiction",
"language",
"locality",
"mnc",
"id",
"title",
"updated_at",
"url",
"work_frbr_uri",
)


class GazetteSerializer(BaseSerializerMixin, serializers.ModelSerializer):
url = serializers.SerializerMethodField()

class Meta:
model = Gazette
fields = (
"created_at",
"date",
"expression_frbr_uri",
"jurisdiction",
"language",
"locality",
"id",
"title",
"updated_at",
"url",
"work_frbr_uri",
)
23 changes: 23 additions & 0 deletions peachjam_api/urls.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
from django.urls import include, path
from drf_spectacular.views import (
SpectacularAPIView,
SpectacularRedocView,
SpectacularSwaggerView,
)
from rest_framework import routers

from . import views
Expand All @@ -9,10 +14,28 @@
router.register(r"citation-links", views.CitationLinkViewSet, basename="citation-links")

urlpatterns = [
# internal API
path("", include(router.urls)),
# semi-public
path(
"v1/ingestors/<int:ingestor_id>/webhook",
views.IngestorWebhookView.as_view(),
name="ingestor_webhook",
),
# public-facing API
path("v1/", include("peachjam_api.urls_public")),
# schema browsing
path(
"v1/schema",
SpectacularAPIView.as_view(urlconf="peachjam_api.urls_public"),
name="schema",
),
path(
"v1/schema/swagger-ui",
SpectacularSwaggerView.as_view(url_name="schema"),
name="swagger-ui",
),
path(
"v1/schema/redoc", SpectacularRedocView.as_view(url_name="schema"), name="redoc"
),
]
21 changes: 21 additions & 0 deletions peachjam_api/urls_public.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from django.urls import include, path
from rest_framework import routers

from . import public_views

router = routers.DefaultRouter(trailing_slash=False)
router.register(
r"judgments",
public_views.JudgmentsViewSet,
basename="judgments",
)
router.register(
r"gazettes",
public_views.GazettesViewSet,
basename="gazettes",
)

urlpatterns = [
# public-facing API
path("v1/", include(router.urls)),
]
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ dependencies = [
"django-storages>=1.12.3",
"django-treebeard>=4.5.1",
"djangorestframework>=3.13.1",
"drf-spectacular>=0.26.0",
"docpipe @ git+https://github.com/laws-africa/docpipe.git@97c371fd7e28041481581a1d43952b401bb6b119",
"elasticsearch>=7.17.1",
"elasticsearch-dsl>=7.4.0",
Expand Down

0 comments on commit 0be59ce

Please sign in to comment.