-
Notifications
You must be signed in to change notification settings - Fork 502
Feat: Outline import #1478
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Feat: Outline import #1478
Changes from 17 commits
6dbd910
1fd4406
becc514
9f4fb06
4f3b62d
fa65c45
cce6c96
6146a48
453b153
b7a7663
06d9c2b
95fa210
68e58b2
538c641
619b624
e1f5a13
7d6f055
1d65ca3
600672d
be6a2cb
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| """Import endpoints for Outline (zip upload).""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import io | ||
| import zipfile | ||
|
|
||
| import rest_framework as drf | ||
|
|
||
| from core.services.outline_import import OutlineImportError, process_outline_zip | ||
|
|
||
|
|
||
| # ---------- Outline (Zip Upload) ---------- | ||
|
|
||
|
|
||
| class OutlineImportUploadView(drf.views.APIView): | ||
| parser_classes = [drf.parsers.MultiPartParser] | ||
| permission_classes = [drf.permissions.IsAuthenticated] | ||
|
|
||
| def post(self, request): | ||
| uploaded = request.FILES.get("file") | ||
| if not uploaded: | ||
| raise drf.exceptions.ValidationError({"file": "File is required"}) | ||
|
|
||
| name = getattr(uploaded, "name", "") | ||
| if not name.endswith(".zip"): | ||
| raise drf.exceptions.ValidationError({"file": "Must be a .zip file"}) | ||
|
|
||
| try: | ||
| content = uploaded.read() | ||
| # Fail fast if the upload is not a valid zip archive | ||
| with zipfile.ZipFile(io.BytesIO(content)): | ||
| pass | ||
| created_ids = process_outline_zip(request.user, content) | ||
|
||
| except zipfile.BadZipFile as exc: | ||
| raise drf.exceptions.ValidationError({"file": "Invalid zip archive"}) from exc | ||
| except OutlineImportError as exc: | ||
| raise drf.exceptions.ValidationError({"file": str(exc)}) from exc | ||
|
|
||
| return drf.response.Response( | ||
| {"created_document_ids": created_ids}, status=drf.status.HTTP_201_CREATED | ||
| ) | ||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,205 @@ | ||||||||||||||||||||
| """Service to import an Outline export (.zip) into Docs documents.""" | ||||||||||||||||||||
|
|
||||||||||||||||||||
| from __future__ import annotations | ||||||||||||||||||||
|
|
||||||||||||||||||||
| import io | ||||||||||||||||||||
| import mimetypes | ||||||||||||||||||||
| import re | ||||||||||||||||||||
| import uuid | ||||||||||||||||||||
| import zipfile | ||||||||||||||||||||
| from typing import Iterable | ||||||||||||||||||||
| import posixpath | ||||||||||||||||||||
|
|
||||||||||||||||||||
| from django.conf import settings | ||||||||||||||||||||
| from django.core.files.storage import default_storage | ||||||||||||||||||||
|
|
||||||||||||||||||||
| from lasuite.malware_detection import malware_detection | ||||||||||||||||||||
|
|
||||||||||||||||||||
| from core import enums, models | ||||||||||||||||||||
| from core.services.converter_services import YdocConverter | ||||||||||||||||||||
|
|
||||||||||||||||||||
|
|
||||||||||||||||||||
| class OutlineImportError(Exception): | ||||||||||||||||||||
| """Raised when the Outline archive is invalid or unsafe.""" | ||||||||||||||||||||
|
|
||||||||||||||||||||
|
|
||||||||||||||||||||
| def _ensure_dir_documents(user, dir_path: str, dir_docs: dict[str, models.Document]) -> models.Document | None: | ||||||||||||||||||||
| """Ensure each path segment in dir_path has a container document. | ||||||||||||||||||||
|
|
||||||||||||||||||||
| Returns the deepest parent document or None when dir_path is empty. | ||||||||||||||||||||
| """ | ||||||||||||||||||||
| if not dir_path: | ||||||||||||||||||||
| return None | ||||||||||||||||||||
|
|
||||||||||||||||||||
| parts = [p for p in dir_path.split("/") if p] | ||||||||||||||||||||
| parent: models.Document | None = None | ||||||||||||||||||||
| current = "" | ||||||||||||||||||||
| for part in parts: | ||||||||||||||||||||
| current = f"{current}/{part}" if current else part | ||||||||||||||||||||
| if current in dir_docs: | ||||||||||||||||||||
| parent = dir_docs[current] | ||||||||||||||||||||
| continue | ||||||||||||||||||||
|
|
||||||||||||||||||||
| if parent is None: | ||||||||||||||||||||
| doc = models.Document.add_root( | ||||||||||||||||||||
| depth=1, | ||||||||||||||||||||
| creator=user, | ||||||||||||||||||||
| title=part, | ||||||||||||||||||||
| link_reach=models.LinkReachChoices.RESTRICTED, | ||||||||||||||||||||
| ) | ||||||||||||||||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||||||||||||
| else: | ||||||||||||||||||||
| doc = parent.add_child(creator=user, title=part) | ||||||||||||||||||||
|
|
||||||||||||||||||||
| models.DocumentAccess.objects.update_or_create( | ||||||||||||||||||||
| document=doc, | ||||||||||||||||||||
| user=user, | ||||||||||||||||||||
| defaults={"role": models.RoleChoices.OWNER}, | ||||||||||||||||||||
| ) | ||||||||||||||||||||
|
||||||||||||||||||||
| models.DocumentAccess.objects.update_or_create( | |
| document=doc, | |
| user=user, | |
| defaults={"role": models.RoleChoices.OWNER}, | |
| ) |
You have to define an owner access for the user only on the root document. Then the children will inherit from this access.
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is the library underneath using? Mimetype guessing is not always stable (even when using libmagic it can differ from version/environment).
I would suggest good testing, preferably in different environments if possible.
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| "status": enums.DocumentAttachmentStatus.READY, | |
| "status": enums.DocumentAttachmentStatus.PROCESSING, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
With the previous comment made, asking to save the file on the bucket, you can transform this function in a celery task and execute it asynchronously
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this always unsafe or only when .. goes beyond the root you are iterating over?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| if parent_doc is None: | |
| doc = models.Document.add_root( | |
| depth=1, | |
| creator=user, | |
| title=title, | |
| link_reach=models.LinkReachChoices.RESTRICTED, | |
| ) | |
| else: | |
| doc = parent_doc.add_child(creator=user, title=title) |
This is managed in _ensure_dir_documents function. You will probably have duplicated docs at the end
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
| models.DocumentAccess.objects.update_or_create( | |
| document=doc, | |
| user=user, | |
| defaults={"role": models.RoleChoices.OWNER}, | |
| ) |
Managed in the _ensure_dir_documents function
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,127 @@ | ||
| """Tests for the Outline zip import API endpoint.""" | ||
|
|
||
| import io | ||
| import zipfile | ||
| from unittest.mock import patch | ||
|
|
||
| from django.core.files.uploadedfile import SimpleUploadedFile | ||
|
|
||
| import pytest | ||
| from rest_framework.test import APIClient | ||
|
|
||
| from core import factories | ||
| from core.api.viewsets import malware_detection | ||
| from core.services.outline_import import OutlineImportError | ||
|
|
||
|
|
||
| pytestmark = pytest.mark.django_db | ||
|
|
||
|
|
||
| def make_zip_with_markdown_and_image(md_path: str, md_content: str, img_path: str, img_bytes: bytes) -> bytes: | ||
| buf = io.BytesIO() | ||
| with zipfile.ZipFile(buf, mode="w") as zf: | ||
| zf.writestr(md_path, md_content) | ||
| zf.writestr(img_path, img_bytes) | ||
| return buf.getvalue() | ||
|
|
||
|
|
||
| def test_outline_import_upload_anonymous_forbidden(): | ||
| """Anonymous users must not be able to use the import endpoint.""" | ||
| client = APIClient() | ||
|
|
||
| # Minimal empty zip | ||
| buf = io.BytesIO() | ||
| with zipfile.ZipFile(buf, mode="w"): | ||
| pass | ||
| upload = SimpleUploadedFile(name="export.zip", content=buf.getvalue(), content_type="application/zip") | ||
|
|
||
| response = client.post("/api/v1.0/imports/outline/upload", {"file": upload}, format="multipart") | ||
|
|
||
| assert response.status_code == 401 | ||
| assert response.json()["detail"] == "Authentication credentials were not provided." | ||
|
|
||
|
|
||
| @patch("core.services.converter_services.YdocConverter.convert", return_value="YmFzZTY0Y29udGVudA==") | ||
| def test_outline_import_upload_authenticated_success(mock_convert): | ||
| """Authenticated users can upload an Outline export zip and create documents.""" | ||
| user = factories.UserFactory() | ||
| client = APIClient() | ||
| client.force_login(user) | ||
|
|
||
| # Markdown referencing a local image in the same directory | ||
| md = "# Imported Title\n\nSome text.\n\n\n" | ||
| img = ( | ||
| b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00" | ||
| b"\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\xf8\xff\xff?\x00\x05\xfe\x02\xfe" | ||
| b"\xa7V\xbd\xfa\x00\x00\x00\x00IEND\xaeB`\x82" | ||
| ) | ||
| zip_bytes = make_zip_with_markdown_and_image( | ||
| md_path="Folder1/page.md", | ||
| md_content=md, | ||
| img_path="Folder1/image.png", | ||
| img_bytes=img, | ||
| ) | ||
|
|
||
| upload = SimpleUploadedFile(name="export.zip", content=zip_bytes, content_type="application/zip") | ||
|
|
||
| with patch.object(malware_detection, "analyse_file") as mock_analyse_file: | ||
| response = client.post("/api/v1.0/imports/outline/upload", {"file": upload}, format="multipart") | ||
|
|
||
| assert response.status_code == 201 | ||
| data = response.json() | ||
| assert "created_document_ids" in data | ||
| # Only the markdown-backed document ids are returned (container folders are not listed) | ||
| assert len(data["created_document_ids"]) == 1 | ||
|
|
||
| # The converter must have been called once per markdown file | ||
| mock_convert.assert_called_once() | ||
| # An antivirus scan is run for the uploaded image | ||
| assert mock_analyse_file.called | ||
|
|
||
|
|
||
| def test_outline_import_upload_invalid_zip_returns_validation_error(): | ||
| """Invalid archives are rejected with a validation error instead of crashing.""" | ||
| user = factories.UserFactory() | ||
| client = APIClient() | ||
| client.force_login(user) | ||
|
|
||
| upload = SimpleUploadedFile( | ||
| name="export.zip", | ||
| content=b"not-a-zip", | ||
| content_type="application/zip", | ||
| ) | ||
|
|
||
| response = client.post( | ||
| "/api/v1.0/imports/outline/upload", | ||
| {"file": upload}, | ||
| format="multipart", | ||
| ) | ||
|
|
||
| assert response.status_code == 400 | ||
| assert response.json() == {"file": ["Invalid zip archive"]} | ||
|
|
||
|
|
||
| @patch("core.api.imports.process_outline_zip", side_effect=OutlineImportError("boom")) | ||
| def test_outline_import_upload_outline_error_returns_validation_error(mock_process_outline): | ||
| """Service-level Outline import errors are surfaced as validation errors.""" | ||
| user = factories.UserFactory() | ||
| client = APIClient() | ||
| client.force_login(user) | ||
|
|
||
| zip_bytes = make_zip_with_markdown_and_image( | ||
| md_path="doc.md", | ||
| md_content="# Title", | ||
| img_path="", | ||
| img_bytes=b"", | ||
| ) | ||
| upload = SimpleUploadedFile(name="export.zip", content=zip_bytes, content_type="application/zip") | ||
|
|
||
| response = client.post( | ||
| "/api/v1.0/imports/outline/upload", | ||
| {"file": upload}, | ||
| format="multipart", | ||
| ) | ||
|
|
||
| assert response.status_code == 400 | ||
| assert response.json() == {"file": ["boom"]} | ||
| mock_process_outline.assert_called_once() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You should rely on a drf serializer here to validate the input instead of doing it in the view. You can maybe reused the
FileUploadSerializerpresent in the serializer module (src/backend/core/api/serializers.py)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Then once the input validated you have to rely on the malware_detection feature to validate the zip content. But we have to imagine a workflow, this process is async. Once the malware detection ended, the
process_outile_zipshould start.