elogbook.py 4.19 KB
Newer Older
1
2
3
4
5
6
from enum import Enum
from datetime import datetime
import requests
import logging
import base64
import mimetypes
7
import socket
8
from bliss.icat.client.url import normalize_url
9
from bliss import __version__
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

logger = logging.getLogger(__name__)

MessageCategory = Enum("MessageCategory", "debug info error commandLine comment")
MessageType = Enum("MessageType", "annotation notification")

MessageCategoryMapping = {
    "debug": MessageCategory.debug,
    "info": MessageCategory.info,
    "warning": MessageCategory.error,
    "warn": MessageCategory.error,
    "error": MessageCategory.error,
    "critical": MessageCategory.error,
    "fatal": MessageCategory.error,
    "command": MessageCategory.commandLine,
    "comment": MessageCategory.comment,
}

MessageTypeMapping = {
    MessageCategory.debug: MessageType.notification,
    MessageCategory.info: MessageType.notification,
    MessageCategory.error: MessageType.notification,
    MessageCategory.commandLine: MessageType.notification,
    MessageCategory.comment: MessageType.annotation,
}


class IcatElogbookClient:
    """Client for the e-logbook part of the ICAT+ REST API.

    REST API docs:
    https://icatplus.esrf.fr/api-docs/

    The ICAT+ server project:
    https://gitlab.esrf.fr/icat/icat-plus/-/blob/master/README.md
    """

    DEFAULT_SCHEME = "https"

    def __init__(
        self, url: str, api_key: str = "elogbook-00000000-0000-0000-0000-000000000000"
    ):
        url = normalize_url(url, default_scheme=self.DEFAULT_SCHEME)
        self._message_url = f"{url}/logbook/{api_key}/investigation/name/{{proposal}}/instrument/name/{{beamline}}/event"
        self._data_url = f"{url}/logbook/{api_key}/investigation/name/{{proposal}}/instrument/name/{{beamline}}/event/createFrombase64"
55
56
57
58
        self._client_id = {
            "machine": socket.getfqdn(),
            "software": "Bliss_v" + __version__,
        }
59
60
        self.timeout = 0.5

61
62
63
64
    def _add_default_payload(self, payload):
        payload.update(self._client_id)
        payload["creationDate"] = datetime.now().isoformat()

65
66
67
68
69
    def send_message(
        self, message: str, category: str, proposal: str, beamline: str, dataset: str
    ):
        url = self._message_url.format(proposal=proposal, beamline=beamline)
        payload = self.encode_message(message, category, dataset)
70
        self._add_default_payload(payload)
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
        requests.post(url, json=payload, timeout=self.timeout)

    def send_text_file(self, filename: str, proposal: str, beamline: str, dataset: str):
        with open(filename, "r") as f:
            message = f.read()
        self.send_message(
            message,
            category="comment",
            proposal=proposal,
            beamline=beamline,
            dataset=dataset,
        )

    def send_data(self, data: bytes, mimetype: str, proposal: str, beamline: str):
        url = self._data_url.format(proposal=proposal, beamline=beamline)
        payload = self.encode_mime_data(data, mimetype)
87
        self._add_default_payload(payload)
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
        requests.post(url, json=payload, timeout=self.timeout)

    def send_binary_file(self, filename: str, proposal: str, beamline: str):
        with open(filename, "rb") as f:
            data = f.read()
        mimetype, _ = mimetypes.guess_type(filename, strict=True)
        self.send_data(data, mimetype=mimetype, proposal=proposal, beamline=beamline)

    @staticmethod
    def encode_mime_data(data: bytes, mimetype: str) -> str:
        if not mimetype:
            # arbitrary binary data
            mimetype = "application/octet-stream"
        data_header = f"data:{mimetype};base64,"
        data_blob = base64.b64encode(data).decode("latin-1")
103
        return {"base64": data_header + data_blob}
104
105
106
107
108
109
110
111
112
113
114
115
116
117

    @staticmethod
    def encode_message(message: str, category: str, dataset: str) -> str:
        try:
            category = MessageCategoryMapping[category.lower()]
        except KeyError:
            raise ValueError(category, "Not a valid e-logbook category") from None
        message_type = MessageTypeMapping[category]
        return {
            "type": message_type.name,
            "datasetName": dataset,
            "category": category.name,
            "content": [{"format": "plainText", "text": message}],
        }