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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions server/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,22 +121,20 @@ The server can be accessed at http://localhost:8080/api/v3.1/ from your host sys
## Currently Unimplemented
Several features and routes are currently not supported:

1. Correlation ID: Not implemented because it was deemed unnecessary for this server.
- Correlation ID: Not implemented because it was deemed unnecessary for this server.

2. Extent Parameter (`withBlobValue/withoutBlobValue`):
- Extent Parameter (`withBlobValue/withoutBlobValue`):
Not implemented due to the lack of support in JSON/XML serialization.

3. Route `/shells/{aasIdentifier}/asset-information/thumbnail`: Not implemented because the specification lacks clarity.

4. Serialization and Description Routes:
- Serialization and Description Routes:
- `/serialization`
- `/description`
These routes are not implemented at this time.

5. Value, Path, and PATCH Routes:
- Value, Path, and PATCH Routes:
- All `/…/value$`, `/…/path$`, and `PATCH` routes are currently not implemented.

6. Operation Invocation Routes: The following routes are not implemented because operation invocation
- Operation Invocation Routes: The following routes are not implemented because operation invocation
is not yet supported by the `basyx-python-sdk`:
- `POST /submodels/{submodelIdentifier}/submodel-elements/{idShortPath}/invoke`
- `POST /submodels/{submodelIdentifier}/submodel-elements/{idShortPath}/invoke/$value`
Expand Down
84 changes: 82 additions & 2 deletions server/app/interfaces/repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,18 @@ def __init__(
),
Rule(
"/asset-information/thumbnail",
methods=["GET", "PUT", "DELETE"],
endpoint=self.not_implemented,
methods=["GET"],
endpoint=self.get_aas_thumbnail,
),
Rule(
"/asset-information/thumbnail",
methods=["PUT"],
endpoint=self.put_aas_thumbnail,
),
Rule(
"/asset-information/thumbnail",
methods=["DELETE"],
endpoint=self.delete_aas_thumbnail,
),
Rule("/submodel-refs", methods=["GET"], endpoint=self.get_aas_submodel_refs),
Rule("/submodel-refs", methods=["POST"], endpoint=self.post_aas_submodel_refs),
Expand Down Expand Up @@ -587,6 +597,76 @@ def put_aas_asset_information(
self.object_store.commit(aas)
return response_t()

def get_aas_thumbnail(
self, request: Request, url_args: Dict, response_t: Type[APIResponse], **_kwargs
) -> Response:
shell = self._get_shell(url_args)
thumbnail = shell.asset_information.default_thumbnail
if thumbnail is None or not thumbnail.path:
raise NotFound(f"{shell!r} has no default thumbnail set!")
if not thumbnail.path.startswith("/"):
raise BadRequest(f"{shell!r} references an external thumbnail: {thumbnail.path}")
bytes_io = io.BytesIO()
try:
self.file_store.write_file(thumbnail.path, bytes_io)
except KeyError:
raise NotFound(f"No thumbnail file found at path: {thumbnail.path}")
return Response(bytes_io.getvalue(), content_type=thumbnail.content_type or "application/octet-stream")

def put_aas_thumbnail(
self, request: Request, url_args: Dict, response_t: Type[APIResponse], **_kwargs
) -> Response:
shell = self._get_shell(url_args)
filename = request.form.get("fileName")
if filename is None:
raise BadRequest("No 'fileName' specified!")
elif not filename.startswith("/"):
raise BadRequest(f"Given 'fileName' doesn't start with a slash (/): {filename}")

file_storage: Optional[FileStorage] = request.files.get("file")
if file_storage is None:
raise BadRequest("Missing file to upload")

# A part without a Content-Type header has an empty mimetype, but an empty ContentType is invalid
content_type = file_storage.mimetype or None
# Validate before the file store changes, so that invalid input leaves the current thumbnail intact
try:
thumbnail = model.Resource(filename, content_type)
except ValueError as e:
raise BadRequest(str(e)) from e
thumbnail.path = self.file_store.add_file(
filename, file_storage.stream, content_type or "application/octet-stream"
)

old_thumbnail = shell.asset_information.default_thumbnail
shell.asset_information.default_thumbnail = thumbnail
self.object_store.commit(shell)
# Delete the previous file only once the shell no longer references it
if old_thumbnail is not None and old_thumbnail.path and old_thumbnail.path.startswith("/") \
and old_thumbnail.path != thumbnail.path:
try:
self.file_store.delete_file(old_thumbnail.path)
except KeyError:
pass
return response_t()
Comment on lines +616 to +651

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should check, for empty strings in mimetype == ''.
If the mimetype is an empty string, the resulting contentType also becomes an empty stirng, when it should be None.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed: an empty mimetype is now stored as None. In fact, the empty string didn't even get stored.
ContentType rejects it, so the request failed with 500, after the previous thumbnail file had already been deleted.
PUT now validates its input first and deletes the old file only once the shell points to the new one.
test_shell_thumbnail_put_without_content_type_stores_none covers this.


def delete_aas_thumbnail(
self, request: Request, url_args: Dict, response_t: Type[APIResponse], **_kwargs
) -> Response:
shell = self._get_shell(url_args)
thumbnail = shell.asset_information.default_thumbnail
if thumbnail is None or not thumbnail.path:
raise NotFound(f"{shell!r} has no default thumbnail set!")
if not thumbnail.path.startswith("/"):
raise BadRequest(f"{shell!r} references an external thumbnail: {thumbnail.path}")
try:
self.file_store.delete_file(thumbnail.path)
except KeyError:
pass
shell.asset_information.default_thumbnail = None
self.object_store.commit(shell)
return response_t()

def get_aas_submodel_refs(
self, request: Request, url_args: Dict, response_t: Type[APIResponse], **_kwargs
) -> Response:
Expand Down
182 changes: 182 additions & 0 deletions server/test/interfaces/repository/test_shells.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
# SPDX-License-Identifier: MIT

import base64
import io
import json
from typing import Iterable
from unittest import mock

from app.util.converters import base64url_encode
from basyx.aas import model
Expand Down Expand Up @@ -436,6 +438,186 @@ def test_shell_asset_information_put(self, format_client: FormatClient):
retrieved_shell.asset_information.global_asset_id,
)

# ------------------------------------------------------------------ /shells/<aas_id>/asset-information/thumbnail

def _shell_with_thumbnail(self, path: str = "/thumbnail.png") -> model.AssetAdministrationShell:
shell = create_example_asset_administration_shell()
shell.asset_information.default_thumbnail = (
model.Resource(path, "image/png") if path else None
)
self.object_store.add(shell)
return shell

def _stored_shell(self, shell_id: str) -> model.AssetAdministrationShell:
shell = self.object_store.get(shell_id)
assert isinstance(shell, model.AssetAdministrationShell)
return shell

@staticmethod
def thumbnail_path(shell: model.AssetAdministrationShell) -> str:
return f"/shells/{base64url_encode(shell.id)}/asset-information/thumbnail"

def test_shell_thumbnail_get(self):
shell = self._shell_with_thumbnail()
self.file_store.write_file.side_effect = lambda name, stream: stream.write(b"png-bytes")

response = self.client.get(self.thumbnail_path(shell))

self.assertEqual(200, response.status_code)
self.assertEqual("image/png", response.content_type)
self.assertEqual(b"png-bytes", response.data)
self.file_store.write_file.assert_called_once_with("/thumbnail.png", mock.ANY)

def test_shell_thumbnail_get_without_thumbnail_returns_404(self):
shell = self._shell_with_thumbnail(path="")

self.assert_error(self.client.get(self.thumbnail_path(shell)), 404)

def test_shell_thumbnail_get_external_thumbnail_returns_400(self):
shell = self._shell_with_thumbnail(path="https://example.org/thumbnail.png")

self.assert_error(self.client.get(self.thumbnail_path(shell)), 400)

def test_shell_thumbnail_get_missing_file_returns_404(self):
shell = self._shell_with_thumbnail()
self.file_store.write_file.side_effect = KeyError

self.assert_error(self.client.get(self.thumbnail_path(shell)), 404)

def test_shell_thumbnail_get_unknown_shell_returns_404(self):
response = self.client.get(
f"/shells/{base64url_encode('https://example.org/unknown')}/asset-information/thumbnail"
)

self.assert_error(response, 404)

def test_shell_thumbnail_put_success(self):
shell = self._shell_with_thumbnail(path="")
self.file_store.add_file.return_value = "/thumbnail.png"

response = self.client.put(
self.thumbnail_path(shell),
data={"fileName": "/thumbnail.png", "file": (io.BytesIO(b"png-bytes"), "thumbnail.png", "image/png")},
content_type="multipart/form-data",
)

self.assertEqual(204, response.status_code)
self.file_store.add_file.assert_called_once_with("/thumbnail.png", mock.ANY, "image/png")
thumbnail = self._stored_shell(shell.id).asset_information.default_thumbnail
assert thumbnail is not None
self.assertEqual("/thumbnail.png", thumbnail.path)
self.assertEqual("image/png", thumbnail.content_type)

def test_shell_thumbnail_put_replaces_the_previous_file(self):
shell = self._shell_with_thumbnail(path="/old.png")
self.file_store.add_file.return_value = "/new.png"

response = self.client.put(
self.thumbnail_path(shell),
data={"fileName": "/new.png", "file": (io.BytesIO(b"png-bytes"), "new.png", "image/png")},
content_type="multipart/form-data",
)

self.assertEqual(204, response.status_code)
self.file_store.delete_file.assert_called_once_with("/old.png")
thumbnail = self._stored_shell(shell.id).asset_information.default_thumbnail
assert thumbnail is not None
self.assertEqual("/new.png", thumbnail.path)

def test_shell_thumbnail_put_without_content_type_stores_none(self):
# A multipart part without a Content-Type header, as some clients send it
shell = self._shell_with_thumbnail(path="/old.png")
self.file_store.add_file.return_value = "/thumbnail.png"
body = (
b"--boundary\r\n"
b'Content-Disposition: form-data; name="fileName"\r\n\r\n'
b"/thumbnail.png\r\n"
b"--boundary\r\n"
b'Content-Disposition: form-data; name="file"; filename="thumbnail.png"\r\n\r\n'
b"png-bytes\r\n"
b"--boundary--\r\n"
)

response = self.client.put(
self.thumbnail_path(shell), data=body, content_type="multipart/form-data; boundary=boundary"
)

self.assertEqual(204, response.status_code)
thumbnail = self._stored_shell(shell.id).asset_information.default_thumbnail
assert thumbnail is not None
self.assertEqual("/thumbnail.png", thumbnail.path)
self.assertIsNone(thumbnail.content_type)
self.file_store.add_file.assert_called_once_with("/thumbnail.png", mock.ANY, "application/octet-stream")

def test_shell_thumbnail_put_invalid_file_name_keeps_the_previous_thumbnail(self):
# Longer than the 2048 characters a PathType may have
shell = self._shell_with_thumbnail(path="/old.png")
file_name = "/" + "a" * 2048

response = self.client.put(
self.thumbnail_path(shell),
data={"fileName": file_name, "file": (io.BytesIO(b"png-bytes"), "new.png", "image/png")},
content_type="multipart/form-data",
)

self.assert_error(response, 400)
self.file_store.add_file.assert_not_called()
self.file_store.delete_file.assert_not_called()
thumbnail = self._stored_shell(shell.id).asset_information.default_thumbnail
assert thumbnail is not None
self.assertEqual("/old.png", thumbnail.path)

def test_shell_thumbnail_put_missing_file_name_returns_400(self):
shell = self._shell_with_thumbnail(path="")

response = self.client.put(
self.thumbnail_path(shell),
data={"file": (io.BytesIO(b"png-bytes"), "thumbnail.png", "image/png")},
content_type="multipart/form-data",
)

self.assert_error(response, 400)

def test_shell_thumbnail_put_relative_file_name_returns_400(self):
shell = self._shell_with_thumbnail(path="")

response = self.client.put(
self.thumbnail_path(shell),
data={"fileName": "thumbnail.png", "file": (io.BytesIO(b"png-bytes"), "thumbnail.png", "image/png")},
content_type="multipart/form-data",
)

self.assert_error(response, 400)

def test_shell_thumbnail_put_missing_file_returns_400(self):
shell = self._shell_with_thumbnail(path="")

response = self.client.put(
self.thumbnail_path(shell), data={"fileName": "/thumbnail.png"}, content_type="multipart/form-data"
)

self.assert_error(response, 400)

def test_shell_thumbnail_delete(self):
shell = self._shell_with_thumbnail()

response = self.client.delete(self.thumbnail_path(shell))

self.assertEqual(204, response.status_code)
self.file_store.delete_file.assert_called_once_with("/thumbnail.png")
self.assertIsNone(self._stored_shell(shell.id).asset_information.default_thumbnail)

def test_shell_thumbnail_delete_without_thumbnail_returns_404(self):
shell = self._shell_with_thumbnail(path="")

self.assert_error(self.client.delete(self.thumbnail_path(shell)), 404)

def test_shell_thumbnail_delete_external_thumbnail_returns_400(self):
shell = self._shell_with_thumbnail(path="https://example.org/thumbnail.png")

self.assert_error(self.client.delete(self.thumbnail_path(shell)), 400)
self.file_store.delete_file.assert_not_called()

# ------------------------------------------------------------------ GET /shells/<aas_id>/submodel-refs

@with_json_client
Expand Down