pyAS4 0.1.19__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pyAS4/AS4Client.py ADDED
@@ -0,0 +1,327 @@
1
+ import base64
2
+ import logging
3
+ import uuid
4
+ from io import BytesIO
5
+ from typing import Generator
6
+
7
+ from pymtom_xop import MtomAttachment, MtomTransport
8
+ from zeep import Client, Settings, Transport
9
+ from zeep.exceptions import Fault
10
+ from zeep.plugins import HistoryPlugin
11
+
12
+ from pyAS4.header import Header, get_dict_header
13
+
14
+ _logger = logging.getLogger(__name__)
15
+
16
+
17
+ def _open_io(content: bytes | str | None, encoding_b64: bool = False) -> BytesIO:
18
+ """Повертає `BytesIO` для payload; за потреби кодує вміст у base64."""
19
+ _logger.debug(f"open_io - > {type(content)}")
20
+
21
+ if content is None:
22
+ raise ValueError("Content cannot be None")
23
+
24
+ if isinstance(content, str):
25
+ return BytesIO(content.encode("utf-8"))
26
+
27
+ if encoding_b64:
28
+ return BytesIO(base64.b64encode(content))
29
+
30
+ return BytesIO(content)
31
+
32
+
33
+ def _norm_cid(cid: str | bytes) -> str:
34
+ """Нормалізує Content-ID для використання в SOAP payloadId."""
35
+ # CID у payloadId має бути без кутових дужок і без префікса `cid:`.
36
+ cid = cid.decode() if isinstance(cid, bytes) else cid
37
+
38
+ if not cid:
39
+ return ""
40
+ cid = cid.strip().strip("<>").strip()
41
+ if cid.lower().startswith("cid:"):
42
+ cid = cid[4:]
43
+ return cid
44
+
45
+
46
+ def attachment(
47
+ files: list[dict[str, str | bytes]], attachments: list[MtomAttachment] | None = None
48
+ ) -> list[MtomAttachment]:
49
+ """
50
+ Додає вкладення до списку `attachments` на основі переданих файлів.
51
+ Кожен файл у списку `files` повинен бути словником з ключами
52
+ `content`, `content_type` та необов'язковим `cid`.
53
+ :param files:
54
+ :param attachments:
55
+ :return:
56
+ """
57
+ if attachments is None:
58
+ attachments = []
59
+ for file in files:
60
+ attachments.append(
61
+ MtomAttachment(
62
+ file=_open_io(file.get("content")),
63
+ content_type=file.get("content_type"),
64
+ cid=f"<{_norm_cid(file.get('cid', str(uuid.uuid4())))}>",
65
+ )
66
+ )
67
+ return attachments
68
+
69
+
70
+ def get_payload(user_message: dict, body) -> list[dict[str, str]]:
71
+ """
72
+ Перетворює частини повідомлення та payload на список словників для зручності обробки.
73
+ :param user_message:
74
+ :param body:
75
+ :return:
76
+ """
77
+
78
+ payloads = body.payload
79
+ if isinstance(payloads, list):
80
+ _logger.info(f"Received {len(payloads)} payloads in part")
81
+ else:
82
+ payloads = [payloads]
83
+ _logger.info("Received a single payload in part, wrapping in lists")
84
+
85
+ meta_parts = []
86
+ for part in user_message.get("PayloadInfo", []):
87
+ m = {"href": part.get("href", "").strip('"')}
88
+
89
+ for proporty in part.get("PartProperties", {}).get("Property", []):
90
+ m.update({proporty.get("name"): proporty.get("_value_1")})
91
+
92
+ for payload in payloads:
93
+ if payload.payloadId == part.get("href", "").strip('"'):
94
+ m.update({"content": payload.value.decode()})
95
+ if not m.get("content"):
96
+ _logger.error(f"Part {part.get('href', '')} has no content, skipping")
97
+ continue
98
+ meta_parts.append(m)
99
+ return meta_parts
100
+
101
+
102
+ class AS4Client:
103
+ """
104
+ Summary of what the class does.
105
+
106
+ The AS4Client class is responsible for creating and managing an AS4 client
107
+ instance. It initializes the necessary elements such as WSDL, transport,
108
+ plugins, and header to set up the client properly. This class serves to
109
+ facilitate communication in the context of AS4-based message exchange by
110
+ leveraging the provided configuration data.
111
+
112
+ :ivar wsdl: The URL or path to the WSDL describing the service. This is a
113
+ critical component for initializing the client.
114
+ :type wsdl: str
115
+ :ivar transport: The transport object that handles the communication layer for
116
+ the AS4 client.
117
+ :type transport: Transport
118
+ :ivar plugins: A list of plugins, such as HistoryPlugin, used for message
119
+ handling, logging, or other custom processing needs.
120
+ :type plugins: list[HistoryPlugin]
121
+ :ivar header: The AS4-specific header required for processing and transmitting
122
+ requests through the client.
123
+ :type header: Header
124
+ """
125
+
126
+ def __init__(
127
+ self,
128
+ wsdl: str,
129
+ transport: Transport,
130
+ plugins: list[HistoryPlugin],
131
+ header: Header,
132
+ ):
133
+ self.wsdl = wsdl
134
+ self.transport: Transport = transport
135
+ self.plugins = plugins
136
+ self.header = header
137
+
138
+ self.settings = Settings(strict=False, xml_huge_tree=True)
139
+ self.client: Client | None = None
140
+
141
+
142
+ class MtomTransportProtocol(Transport):
143
+ def add_files(self, files: list[MtomAttachment]) -> None: ...
144
+
145
+
146
+ class AS4Send(AS4Client):
147
+ def __init__(
148
+ self,
149
+ wsdl: str,
150
+ transport: MtomTransportProtocol,
151
+ plugins: list[HistoryPlugin],
152
+ header: Header,
153
+ ):
154
+ """
155
+ Initializes the client with a specific WSDL, transport, plugin list, and header.
156
+ The transport must be an instance of MtomTransport. This class is a specialized
157
+ client designed for handling SOAP requests with MTOM support by extending the
158
+ base client functionality.
159
+
160
+ :param wsdl: WSDL file location as a string for constructing the SOAP client.
161
+ :param transport: Transport layer used for communication, which must be an
162
+ instance of MtomTransport.
163
+ :param plugins: List of `HistoryPlugin` used to capture and manipulate outgoing
164
+ or incoming messages within the client.
165
+ :param header: SOAP request header to include in all outgoing requests.
166
+ :raises TypeError: If the provided `transport` is not an instance of
167
+ `MtomTransport`.
168
+ """
169
+ if not isinstance(transport, MtomTransport):
170
+ raise TypeError("Transport must be an instance of MtomTransport")
171
+
172
+ super().__init__(wsdl, transport, plugins, header)
173
+ self.transport = transport
174
+
175
+ def send_message(self, payload: list[dict]):
176
+ """
177
+ Sends a message by preparing and attaching payload data to the transport, then
178
+ initializing a SOAP client for further communication.
179
+
180
+ This method prepares the provided payload, converts it into attachments, and
181
+ adds these attachments to the transport mechanism. The SOAP client is then
182
+ initialized utilizing the configured WSDL, transport, settings, and plugins.
183
+
184
+ :param payload: A list of dictionaries, where each dictionary contains the
185
+ necessary data to be sent as part of the operation.
186
+ :type payload: list[dict]
187
+ """
188
+ attach = attachment(payload)
189
+ self.transport.add_files(files=attach) # type: ignore
190
+
191
+ self.client = Client(
192
+ wsdl=self.wsdl,
193
+ transport=self.transport,
194
+ settings=self.settings,
195
+ plugins=self.plugins,
196
+ )
197
+ PayloadType = self.client.get_type("ns0:LargePayloadType")
198
+ bodyload_obj = None
199
+ payload_objs = []
200
+
201
+ for idx, file in enumerate(attach):
202
+ payload_id = f"cid:{_norm_cid(file.get_cid())}"
203
+ obj = PayloadType(
204
+ value=file.get_cid(),
205
+ payloadId=payload_id,
206
+ contentType=file.content_type,
207
+ )
208
+ self.header.payload_append(
209
+ [{"href": payload_id, "mimetype": file.content_type}]
210
+ )
211
+ payload_objs.append(obj)
212
+ try:
213
+ response = self.client.service.submitMessage(
214
+ _soapheaders=[self.header.element],
215
+ body=payload_objs,
216
+ bodyload=bodyload_obj,
217
+ )
218
+ except Fault:
219
+ _logger.exception("SOAP Fault occurred while sending message")
220
+ raise
221
+ except Exception:
222
+ _logger.exception("Error sending message")
223
+ raise
224
+ _logger.info(f"Message sent successfully: {response}")
225
+ return response
226
+
227
+
228
+ class AS4Receive(AS4Client):
229
+ def __init__(
230
+ self,
231
+ wsdl: str,
232
+ transport: Transport,
233
+ plugins: list[HistoryPlugin],
234
+ header: Header,
235
+ ):
236
+ """
237
+ Initializes a new instance of the class.
238
+
239
+ This constructor establishes the core components required for the proper
240
+ functioning of the object by accepting necessary parameters including WSDL
241
+ configuration, transport layer, plugins, and header data. These components
242
+ are essential for initializing the client object which enables interaction
243
+ with specified SOAP endpoints.
244
+
245
+ :param wsdl: WSDL URL or file path to be used for client configuration.
246
+ Represents the Web Services Description Language definition for the SOAP
247
+ service.
248
+ :type wsdl: str
249
+ :param transport: A transport instance that handles HTTP requests and responses
250
+ for the SOAP client.
251
+ :type transport: Transport
252
+ :param plugins: A list of plugins to be used by the SOAP client for functionalities
253
+ such as logging or request/response alterations.
254
+ :type plugins: list[HistoryPlugin]
255
+ :param header: The header object used to define additional metadata or
256
+ authentication details for SOAP requests.
257
+ :type header: Header
258
+ """
259
+ super().__init__(wsdl, transport, plugins, header)
260
+
261
+ self.client = Client(
262
+ wsdl=self.wsdl,
263
+ transport=self.transport,
264
+ settings=self.settings,
265
+ plugins=self.plugins,
266
+ )
267
+
268
+ def _get_pending(self) -> list:
269
+ try:
270
+ if self.client is None:
271
+ raise RuntimeError("Client not initialized")
272
+ response = self.client.service.listPendingMessages(
273
+ finalRecipient=self.header.c4_party_id
274
+ )
275
+ _logger.info(f"Received message: {len(response)}")
276
+ return response
277
+ except Fault:
278
+ _logger.exception("SOAP Fault occurred")
279
+ raise
280
+ except Exception:
281
+ _logger.exception("Error receiving message")
282
+ raise
283
+
284
+ def receive_message(self) -> Generator[dict, None, None]:
285
+ """
286
+ Retrieve and process messages.
287
+
288
+ Iterates over pending items and attempts to retrieve their corresponding messages via a SOAP service.
289
+ Each retrieved message is processed, extracting its header and payload. Log messages are generated for success,
290
+ warnings, and errors during the process.
291
+
292
+ :raises Fault: If a SOAP fault occurs while attempting to retrieve a message.
293
+ :raises Exception: If an unexpected error occurs during message retrieval.
294
+ :return: A generator yielding dictionaries containing retrieved message details including message ID,
295
+ header, and payload.
296
+ :rtype: Generator[dict, None, None]
297
+ """
298
+
299
+ for item in self._get_pending():
300
+ message_id = getattr(item, "messageId", None) or str(item)
301
+ if not message_id:
302
+ _logger.warning("Message ID not found in pending item")
303
+ continue
304
+
305
+ try:
306
+ if self.client is None:
307
+ raise RuntimeError("Client not initialized")
308
+ retrieved = self.client.service.retrieveMessage(messageID=message_id)
309
+ except Fault:
310
+ _logger.exception(
311
+ f"SOAP Fault occurred while retrieving message {message_id}"
312
+ )
313
+ continue
314
+ except Exception:
315
+ _logger.exception(f"Error retrieving message {message_id}")
316
+ continue
317
+
318
+ message = {"messageId": message_id}
319
+ header_data = get_dict_header(
320
+ retrieved.header.ebMSHeaderInfo.UserMessage
321
+ )
322
+ message["header"] = header_data
323
+ message["payload"] = get_payload(header_data, retrieved.body)
324
+
325
+ _logger.debug(f"Retrieved message: {message}")
326
+ yield message
327
+ _logger.info("No more messages to retrieve")
pyAS4/__init__.py ADDED
File without changes
pyAS4/header.py ADDED
@@ -0,0 +1,265 @@
1
+ import logging
2
+ import uuid
3
+
4
+ from lxml import etree
5
+
6
+ _logger = logging.getLogger(__name__)
7
+
8
+ _NS = {
9
+ "query": "urn:oasis:names:tc:ebxml-regrep:xsd:query:4.0",
10
+ "rs": "urn:oasis:names:tc:ebxml-regrep:xsd:rs:4.0",
11
+ "rim": "urn:oasis:names:tc:ebxml-regrep:xsd:rim:4.0",
12
+ "xsi": "http://www.w3.org/2001/XMLSchema-instance",
13
+ "sdg": "http://data.europa.eu/sdg#", # NOSONAR
14
+ "s12": "http://www.w3.org/2003/05/soap-envelope",
15
+ "eu": "http://eu.domibus.wsplugin/", # NOSONAR
16
+ "eb3": "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/",
17
+ }
18
+
19
+
20
+ def _nsmap(ns: str, tag: str) -> str:
21
+ return f"{{{_NS[ns]}}}{tag}"
22
+
23
+
24
+ class Header:
25
+ """
26
+ Represents an ebXML-compatible messaging header, allowing for configuration of
27
+ various party identifiers, service/action details, and payload-related data.
28
+
29
+ This class is designed to facilitate the construction and management of an
30
+ ebXML AS4-compliant messaging XML, including functionality to dynamically
31
+ append payload information. The primary purpose of this class is to support
32
+ eDelivery-compliant systems by structuring the metadata and delivering
33
+ message-based document exchange.
34
+
35
+ :ivar c1_party_id: Identifier for Party 1 involved in the message exchange.
36
+ :ivar c1_party_id_type: The type of the identifier used for Party 1.
37
+ :ivar c2_party_id: Identifier for Party 2 involved in the message exchange.
38
+ :ivar c2_party_id_type: The type of the identifier used for Party 2.
39
+ :ivar c3_party_id: Identifier for Party 3 involved in the message exchange.
40
+ :ivar c3_party_id_type: The type of the identifier used for Party 3.
41
+ :ivar c4_party_id: Identifier for Party 4 involved in the message exchange.
42
+ :ivar c4_party_id_type: The type of the identifier used for Party 4.
43
+ :ivar conversationid: Unique identifier for the conversation thread.
44
+ :ivar service: Service URL to describe the functionality invoked.
45
+ :ivar service_type: Specific type of the service provided.
46
+ :ivar action: Action URL defining the invoked operation.
47
+ :ivar role: Role URL describing the role of the communicating party.
48
+ """
49
+
50
+ def __init__(self,
51
+ c1_party_id: str,
52
+ c1_party_id_type: str,
53
+ c2_party_id: str,
54
+ c2_party_id_type: str,
55
+ c3_party_id: str,
56
+ c3_party_id_type: str,
57
+ c4_party_id: str,
58
+ c4_party_id_type: str,
59
+ conversationid: str = str(uuid.uuid4()),
60
+ service: str = "http://docs.oasis-open.org/ebxml-msg/as4/200902/service", #NOSONAR
61
+ service_type: str = "urn:oasis:names:tc:ebcore:ebrs:ebms:binding:1.0",
62
+ action: str = "http://docs.oasis-open.org/ebxml-msg/as4/200902/action", #NOSONAR
63
+ role: str = "http://sdg.europa.eu/edelivery/gateway" #NOSONAR
64
+ ):
65
+ """
66
+ Initializes an instance of the class with required and optional attributes to configure
67
+ a messaging context as per the specified standards. It validates non-None constraints
68
+ for mandatory parameters.
69
+
70
+ :param c1_party_id: Identifier for Party 1 involved in the message exchange.
71
+ :param c1_party_id_type: The type of the identifier used for Party 1.
72
+ :param c2_party_id: Identifier for Party 2 involved in the message exchange.
73
+ :param c2_party_id_type: The type of the identifier used for Party 2.
74
+ :param c3_party_id: Identifier for Party 3 involved in the message exchange.
75
+ :param c3_party_id_type: The type of the identifier used for Party 3.
76
+ :param c4_party_id: Identifier for Party 4 involved in the message exchange.
77
+ :param c4_party_id_type: The type of the identifier used for Party 4.
78
+ :param conversationid: (Optional) Unique identifier for the conversation thread.
79
+ Defaults to a random UUID.
80
+ :param service: (Optional) Service URL to describe the functionality invoked.
81
+ Defaults to "http://docs.oasis-open.org/ebxml-msg/as4/200902/service".
82
+ :param service_type: (Optional) Specific type of the service provided.
83
+ Defaults to "urn:oasis:names:tc:ebcore:ebrs:ebms:binding:1.0".
84
+ :param action: (Optional) Action URL defining the invoked operation.
85
+ Defaults to "http://docs.oasis-open.org/ebxml-msg/as4/200902/action".
86
+ :param role: (Optional) Role URL describing the role of the communicating party.
87
+ Defaults to "http://sdg.europa.eu/edelivery/gateway".
88
+ :raises ValueError: If any of the mandatory `c1_party_id`, `c2_party_id`,
89
+ `c3_party_id`, or `c4_party_id` parameters are None.
90
+ """
91
+ if None in (c1_party_id, c2_party_id, c3_party_id, c4_party_id):
92
+ raise ValueError("Parameters must not be None")
93
+
94
+ self._xml = etree.Element(_nsmap('eb3', 'Messaging'), nsmap=_NS)
95
+
96
+ self.c1_party_id = c1_party_id
97
+ self.c1_party_id_type = c1_party_id_type
98
+ self.c2_party_id = c2_party_id
99
+ self.c2_party_id_type = c2_party_id_type
100
+ self.c3_party_id = c3_party_id
101
+ self.c3_party_id_type = c3_party_id_type
102
+ self.c4_party_id = c4_party_id
103
+ self.c4_party_id_type = c4_party_id_type
104
+ self.service = service
105
+ self.service_type = service_type
106
+ self.action = action
107
+ self.conversationid = conversationid
108
+ self.role = role
109
+ self.pay_load_info = self.__toxml()
110
+
111
+ def __toxml(self) -> etree._Element:
112
+ """
113
+ Generates and returns an XML element representing a `PayloadInfo` node with nested
114
+ structure for UserMessage, PartyInfo, CollaborationInfo, and MessageProperties
115
+ based on the provided instance attributes.
116
+
117
+ This method uses the lxml.etree library to structure an XML tree,
118
+ populating the sub-elements with instance-specific data.
119
+
120
+ :return: An XML element 'PayloadInfo' with the nested structure.
121
+ :rtype: etree._Element
122
+ """
123
+
124
+ user_message = etree.SubElement(self._xml, _nsmap('eb3', 'UserMessage'))
125
+
126
+ party_info = etree.SubElement(user_message, _nsmap('eb3', 'PartyInfo'))
127
+ froms = etree.SubElement(party_info, _nsmap('eb3', 'From'))
128
+ etree.SubElement(froms, _nsmap('eb3', 'PartyId'),
129
+ attrib={'type': self.c2_party_id_type},
130
+ ).text=self.c2_party_id
131
+ etree.SubElement(froms, _nsmap('eb3', 'Role'),
132
+ ).text=self.role
133
+
134
+ to = etree.SubElement(party_info, _nsmap('eb3', 'To'))
135
+ etree.SubElement(to, _nsmap('eb3', 'PartyId'),
136
+ attrib={'type': self.c3_party_id_type},
137
+ ).text=self.c3_party_id
138
+ etree.SubElement(to, _nsmap('eb3', 'Role'),
139
+ ).text=self.role
140
+
141
+ collaboration_info = etree.SubElement(user_message, _nsmap('eb3', 'CollaborationInfo'))
142
+ etree.SubElement(collaboration_info, _nsmap('eb3', 'Service'),
143
+ type="urn:oasis:names:tc:ebcore:ebrs:ebms:binding:1.0",
144
+ ).text=self.service
145
+ etree.SubElement(collaboration_info, _nsmap('eb3', 'Action'),
146
+ ).text=self.action
147
+ etree.SubElement(collaboration_info, _nsmap('eb3', 'ConversationId'),
148
+ ).text=self.conversationid
149
+
150
+ message_proportis = etree.SubElement(user_message, _nsmap('eb3', 'MessageProperties'))
151
+ etree.SubElement(message_proportis, _nsmap('eb3', 'Property'),
152
+ attrib={
153
+ 'name': 'originalSender',
154
+ 'type': self.c1_party_id_type},
155
+ ).text=self.c1_party_id
156
+ etree.SubElement(message_proportis, _nsmap('eb3', 'Property'),
157
+ attrib={
158
+ 'name': 'finalRecipient',
159
+ 'type': self.c4_party_id_type},
160
+ ).text=self.c4_party_id
161
+
162
+ pay_load_info = etree.SubElement(user_message, _nsmap('eb3', 'PayloadInfo'))
163
+
164
+ return pay_load_info
165
+
166
+ def payload_append(self, payloads: list[dict[str, str]]):
167
+ """
168
+ Appends payload information to the internal XML structure.
169
+
170
+ This method processes a list of payload dictionaries and appends their
171
+ information into an internal XML structure represented by `self.pay_load_info`.
172
+ Each dictionary in the input list contains details about a single payload, such
173
+ as its `href`, `mimetype`, and optionally its `CompressionType`.
174
+
175
+ :param payloads: List of dictionaries, where each dictionary represents a
176
+ payload with at least the keys `href` (str) and `mimetype` (str). The key
177
+ `CompressionType` (str) is optional.
178
+ :return: None
179
+ """
180
+ for payload in payloads:
181
+ pl = etree.SubElement(self.pay_load_info, _nsmap('eb3', 'PartInfo'),
182
+ attrib={'href': payload['href']})
183
+ pp = etree.SubElement(pl, _nsmap('eb3', 'PartProperties'),)
184
+ etree.SubElement(pp, _nsmap('eb3', 'Property'),
185
+ attrib={'name': "MimeType"},
186
+ ).text=payload['mimetype']
187
+ if payload.get('CompressionType', None):
188
+ etree.SubElement(pp, _nsmap('eb3', 'Property'),
189
+ attrib={'name': "CompressionType"},
190
+ ).text=payload['CompressionType']
191
+
192
+ @property
193
+ def element(self) -> etree._Element:
194
+ """
195
+ Returns the underlying XML element associated with this object.
196
+
197
+ This property provides access to the root XML element, enabling direct
198
+ manipulation or query of the XML structure represented by it.
199
+
200
+ :return: The root XML element of the object.
201
+ :rtype: etree._Element
202
+ """
203
+ return self._xml
204
+
205
+ @property
206
+ def xml(self) -> bytes:
207
+ """
208
+ Provides a property to retrieve the XML representation of an element.
209
+
210
+ This property generates and returns the XML content of the associated
211
+ element in a byte string format with pretty-print formatting applied.
212
+
213
+ :return: A byte string containing the XML representation of the element
214
+ with pretty-print formatting.
215
+ :rtype: Bytes
216
+ """
217
+ return etree.tostring(self.element, pretty_print=True)
218
+
219
+
220
+ def get_dict_header(source_message) -> dict:
221
+ """
222
+ Перетворює заголовок повідомлення на словник для зручності обробки.
223
+ :param source_message:
224
+ :return:
225
+ """
226
+ headers = {
227
+ "messageId": source_message.MessageInfo.MessageId,
228
+ "timestamp": source_message.MessageInfo.Timestamp,
229
+ "Party": {
230
+ "From": {
231
+ "name": source_message.PartyInfo.From.PartyId._value_1,
232
+ "type": source_message.PartyInfo.From.PartyId.type,
233
+ "role": source_message.PartyInfo.From.Role,
234
+ },
235
+ "To": {
236
+ "name": source_message.PartyInfo.To.PartyId._value_1,
237
+ "type": source_message.PartyInfo.To.PartyId.type,
238
+ "role": source_message.PartyInfo.To.Role,
239
+ },
240
+ },
241
+ "CollaborationInfo": {
242
+ "service": source_message.CollaborationInfo.Service._value_1,
243
+ "serviceType": source_message.CollaborationInfo.Service.type,
244
+ "action": source_message.CollaborationInfo.Action,
245
+ "conversationId": source_message.CollaborationInfo.ConversationId,
246
+ },
247
+ }
248
+ parts = source_message.PayloadInfo.PartInfo
249
+ if isinstance(parts, list):
250
+ _logger.info(f"Received {len(parts)} parts in message")
251
+ else:
252
+ parts = [parts]
253
+ _logger.info("Received a single part in a message, wrapping in lists")
254
+
255
+ meta_parts = []
256
+ for part in parts:
257
+ m = {"href": part.href.strip('"')}
258
+
259
+ for proporty in part.PartProperties.Property:
260
+ m.update({proporty.name: proporty._value_1})
261
+
262
+ meta_parts.append(m)
263
+
264
+ headers["PayloadInfo"] = meta_parts
265
+ return headers
@@ -0,0 +1,222 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyAS4
3
+ Version: 0.1.19
4
+ Summary: Python бібліотека для роботи з AS4 (OASIS ebXML AS4) протоколом обміну повідомленнями
5
+ Author: Andriy Shapovalov
6
+ Requires-Python: >=3.12
7
+ Description-Content-Type: text/x-rst
8
+ License-File: LICENSE
9
+ Requires-Dist: lxml>=6.1.1
10
+ Requires-Dist: zeep>=4.3.3
11
+ Requires-Dist: pymtom-xop-fork>=0.0.3
12
+ Provides-Extra: dev
13
+ Requires-Dist: mypy>=1.11.0; extra == "dev"
14
+ Requires-Dist: pyrefly>=0.60.0; extra == "dev"
15
+ Requires-Dist: pytest>=8.2.0; extra == "dev"
16
+ Requires-Dist: pytest-asyncio>=0.23.7; extra == "dev"
17
+ Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
18
+ Requires-Dist: ruff>=0.6.0; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ pyAS4
22
+ =====
23
+
24
+ Бібліотека Python для роботи з AS4 (OASIS ebXML AS4) протоколом обміну повідомленнями.
25
+
26
+ **pyAS4** - це дружелюбна обгортка навколо ZEEP та MTOM/XOP транспорту, яка спрощує створення та управління
27
+ AS4-сумісними повідомленнями для систем електронної доставки та B2B комунікацій.
28
+
29
+ Опис
30
+ ----
31
+
32
+ pyAS4 надає удосконалений клієнт для роботи з AS4 веб-сервісами, включаючи:
33
+
34
+ - **AS4Send** - клієнт для відправлення AS4-повідомлень
35
+ - **AS4Receive** - клієнт для отримання AS4-повідомлень
36
+ - **Header** - конструктор заголовків AS4 для керування метаданими повідомлень
37
+ - Підтримка MTOM/XOP для передачі великих файлів
38
+ - Управління party identifiers та service/action деталями
39
+ - Обробка вхідних та вихідних повідомлень
40
+
41
+ Вимоги
42
+ ------
43
+
44
+ - Python >= 3.12
45
+ - lxml >= 6.1.1
46
+ - zeep >= 4.3.3
47
+
48
+ Встановлення
49
+ ------------
50
+
51
+ За допомогою uv::
52
+
53
+ uv sync --extra dev
54
+
55
+ Або з вихідного коду::
56
+
57
+ git clone <repository-url>
58
+ cd pyAS4
59
+ uv sync --extra dev
60
+
61
+ Використання
62
+ ------------
63
+
64
+ Основний приклад
65
+ ^^^^^^^^^^^^^^^^
66
+
67
+ .. code-block:: python
68
+
69
+ from zeep.plugins import HistoryPlugin
70
+ from pymtom_xop import MtomTransport
71
+
72
+ from pyAS4.AS4Client import AS4Send
73
+ from pyAS4.header import Header
74
+
75
+ # Створіть транспорт та заголовок
76
+ transport = MtomTransport()
77
+ header = Header(
78
+ c1_party_id="party1-id",
79
+ c1_party_id_type="urn:fdc:peppol.eu:2017:identifiers:C1",
80
+ c2_party_id="party2-id",
81
+ c2_party_id_type="urn:fdc:peppol.eu:2017:identifiers:C2",
82
+ c3_party_id="party3-id",
83
+ c3_party_id_type="urn:fdc:peppol.eu:2017:identifiers:C3",
84
+ c4_party_id="party4-id",
85
+ c4_party_id_type="urn:fdc:peppol.eu:2017:identifiers:C4",
86
+ service_type="urn:oasis:names:tc:ebcore:ebrs:ebms:binding:1.0",
87
+ conversationid="my-conversation-id",
88
+ )
89
+
90
+ # Ініціалізуйте клієнт відправлення
91
+ client = AS4Send(
92
+ wsdl="http://example.com/as4-service?wsdl",
93
+ transport=transport,
94
+ plugins=[HistoryPlugin()],
95
+ header=header,
96
+ )
97
+
98
+ Відправлення повідомлень
99
+ ^^^^^^^^^^^^^^^^^^^^^^^^
100
+
101
+ .. code-block:: python
102
+
103
+ # Відправте повідомлення з вказаними корисними навантаженнями
104
+ payloads = [
105
+ {
106
+ "content": b"<xml>payload content</xml>",
107
+ "content_type": "application/xml",
108
+ }
109
+ ]
110
+
111
+ client.send_message(payloads)
112
+
113
+ Отримання очікуючих повідомлень
114
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
115
+
116
+ .. code-block:: python
117
+
118
+ from pyAS4.AS4Client import AS4Receive
119
+
120
+ receiver = AS4Receive(
121
+ wsdl="http://example.com/as4-service?wsdl",
122
+ transport=transport,
123
+ plugins=[HistoryPlugin()],
124
+ header=header,
125
+ )
126
+
127
+ # Отримайте очікуючі повідомлення
128
+ for message in receiver.receive_message():
129
+ print(message)
130
+
131
+ Робота з заголовками AS4
132
+ ^^^^^^^^^^^^^^^^^^^^^^^^
133
+
134
+ .. code-block:: python
135
+
136
+ from pyAS4.header import Header
137
+
138
+ # Створіть заголовок AS4
139
+ header = Header(
140
+ c1_party_id="sender-id",
141
+ c1_party_id_type="urn:fdc:peppol.eu:2017:identifiers:C1",
142
+ c2_party_id="recipient-id",
143
+ c2_party_id_type="urn:fdc:peppol.eu:2017:identifiers:C2",
144
+ c3_party_id="intermediary-id",
145
+ c3_party_id_type="urn:fdc:peppol.eu:2017:identifiers:C3",
146
+ c4_party_id="carrier-id",
147
+ c4_party_id_type="urn:fdc:peppol.eu:2017:identifiers:C4",
148
+ conversationid="unique-conversation-id",
149
+ service="http://docs.oasis-open.org/ebxml-msg/as4/200902/service",
150
+ service_type="urn:oasis:names:tc:ebcore:ebrs:ebms:binding:1.0",
151
+ action="http://docs.oasis-open.org/ebxml-msg/as4/200902/action"
152
+ )
153
+
154
+ Структура проєкту
155
+ -----------------
156
+
157
+ ::
158
+
159
+ pyAS4/
160
+ ├── pyAS4/
161
+ │ ├── __init__.py # Точка входу бібліотеки
162
+ │ ├── AS4Client.py # AS4Client, AS4Send та AS4Receive
163
+ │ ├── header.py # Header клас для керування AS4 заголовками
164
+ │ └── py.typed # Маркер для типізованої бібліотеки
165
+ ├── README.rst # Цей файл
166
+ ├── pyproject.toml # Конфігурація проєкту (PEP 517/518)
167
+ └── uv.lock # Зафіксовані залежності для uv
168
+
169
+ Архітектура
170
+ -----------
171
+
172
+ **AS4Send / AS4Receive**
173
+ Базові клієнти для відправлення й отримання AS4-повідомлень через WSDL,
174
+ транспорт і AS4-заголовок.
175
+
176
+ **Header**
177
+ Клас для конструювання та керування ebXML AS4 заголовками повідомлень.
178
+ Генерує коректний XML на основі стандартів OASIS ebXML.
179
+
180
+ **MtomTransport**
181
+ Транспорт з підтримкою MTOM/XOP для обробки великих бінарних вкладень.
182
+
183
+ Стандарти та протоколи
184
+ ----------------------
185
+
186
+ Проєкт реалізує наступні стандарти:
187
+
188
+ - **OASIS ebXML AS4 v3.0** - Асинхронна обробка SOAP повідомлень
189
+ - **PEPPOL** - Pan-European Public Procurement Online (ідентифікатори сторін)
190
+ - **MTOM/XOP** - SOAP з вкладеннями (передача великих файлів)
191
+
192
+ Автор
193
+ -----
194
+
195
+ Andrey Shapovalov (mt.andrey@gmail.com)
196
+
197
+ Ліцензія
198
+ --------
199
+
200
+ EUPL v1.2
201
+
202
+ Поточна версія
203
+ --------------
204
+
205
+ 9
206
+
207
+ Внески
208
+ ------
209
+
210
+ Поточна версія розробляється в приватному репозиторії.
211
+
212
+ Контакти
213
+ --------
214
+
215
+ Для питань та пропозицій звертайтесь до:
216
+ - Email: mt.andrey@gmail.com
217
+
218
+ ----
219
+
220
+ Примітка: Бібліотека розроблена для роботи з системами електронної доставки,
221
+ що відповідають стандартам OASIS ebXML AS4, та особливо для проєктів,
222
+ що використовують PEPPOL мережу.
@@ -0,0 +1,8 @@
1
+ pyAS4/AS4Client.py,sha256=34c6mBTkkUHvsw3wcVdr0PUTskx2hAyV7Tb3EwbzsYU,12332
2
+ pyAS4/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ pyAS4/header.py,sha256=suxG0ZXovuE6UriysscwdxhvkChf3CHH2dXPqjhV4Ic,12226
4
+ pyas4-0.1.19.dist-info/licenses/LICENSE,sha256=ki5-O-jt9WSvTvj8NrFtB82sv4uCY9lwvPb-DuBZKIc,13957
5
+ pyas4-0.1.19.dist-info/METADATA,sha256=swLOXAed-hpqA4Z8quaroDWasHodQD-Ufxnbn1tHKUk,7552
6
+ pyas4-0.1.19.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
7
+ pyas4-0.1.19.dist-info/top_level.txt,sha256=vCujoNeUocyhJQzT1AUJNPbQKEf_oplo9UnmK5o_eFw,6
8
+ pyas4-0.1.19.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,190 @@
1
+ EUROPEAN UNION PUBLIC LICENCE v. 1.2
2
+ EUPL © the European Union 2007, 2016
3
+
4
+ This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined below) which is provided under the
5
+ terms of this Licence. Any use of the Work, other than as authorised under this Licence is prohibited (to the extent such
6
+ use is covered by a right of the copyright holder of the Work).
7
+ The Work is provided under the terms of this Licence when the Licensor (as defined below) has placed the following
8
+ notice immediately following the copyright notice for the Work:
9
+ Licensed under the EUPL
10
+ or has expressed by any other means his willingness to license under the EUPL.
11
+
12
+ 1.Definitions
13
+ In this Licence, the following terms have the following meaning:
14
+ — ‘The Licence’:this Licence.
15
+ — ‘The Original Work’:the work or software distributed or communicated by the Licensor under this Licence, available
16
+ as Source Code and also as Executable Code as the case may be.
17
+ — ‘Derivative Works’:the works or software that could be created by the Licensee, based upon the Original Work or
18
+ modifications thereof. This Licence does not define the extent of modification or dependence on the Original Work
19
+ required in order to classify a work as a Derivative Work; this extent is determined by copyright law applicable in
20
+ the country mentioned in Article 15.
21
+ — ‘The Work’:the Original Work or its Derivative Works.
22
+ — ‘The Source Code’:the human-readable form of the Work which is the most convenient for people to study and
23
+ modify.
24
+ — ‘The Executable Code’:any code which has generally been compiled and which is meant to be interpreted by
25
+ a computer as a program.
26
+ — ‘The Licensor’:the natural or legal person that distributes or communicates the Work under the Licence.
27
+ — ‘Contributor(s)’:any natural or legal person who modifies the Work under the Licence, or otherwise contributes to
28
+ the creation of a Derivative Work.
29
+ — ‘The Licensee’ or ‘You’:any natural or legal person who makes any usage of the Work under the terms of the
30
+ Licence.
31
+ — ‘Distribution’ or ‘Communication’:any act of selling, giving, lending, renting, distributing, communicating,
32
+ transmitting, or otherwise making available, online or offline, copies of the Work or providing access to its essential
33
+ functionalities at the disposal of any other natural or legal person.
34
+
35
+ 2.Scope of the rights granted by the Licence
36
+ The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, sublicensable licence to do the following, for
37
+ the duration of copyright vested in the Original Work:
38
+ — use the Work in any circumstance and for all usage,
39
+ — reproduce the Work,
40
+ — modify the Work, and make Derivative Works based upon the Work,
41
+ — communicate to the public, including the right to make available or display the Work or copies thereof to the public
42
+ and perform publicly, as the case may be, the Work,
43
+ — distribute the Work or copies thereof,
44
+ — lend and rent the Work or copies thereof,
45
+ — sublicense rights in the Work or copies thereof.
46
+ Those rights can be exercised on any media, supports and formats, whether now known or later invented, as far as the
47
+ applicable law permits so.
48
+ In the countries where moral rights apply, the Licensor waives his right to exercise his moral right to the extent allowed
49
+ by law in order to make effective the licence of the economic rights here above listed.
50
+ The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to any patents held by the Licensor, to the
51
+ extent necessary to make use of the rights granted on the Work under this Licence.
52
+
53
+ 3.Communication of the Source Code
54
+ The Licensor may provide the Work either in its Source Code form, or as Executable Code. If the Work is provided as
55
+ Executable Code, the Licensor provides in addition a machine-readable copy of the Source Code of the Work along with
56
+ each copy of the Work that the Licensor distributes or indicates, in a notice following the copyright notice attached to
57
+ the Work, a repository where the Source Code is easily and freely accessible for as long as the Licensor continues to
58
+ distribute or communicate the Work.
59
+
60
+ 4.Limitations on copyright
61
+ Nothing in this Licence is intended to deprive the Licensee of the benefits from any exception or limitation to the
62
+ exclusive rights of the rights owners in the Work, of the exhaustion of those rights or of other applicable limitations
63
+ thereto.
64
+
65
+ 5.Obligations of the Licensee
66
+ The grant of the rights mentioned above is subject to some restrictions and obligations imposed on the Licensee. Those
67
+ obligations are the following:
68
+
69
+ Attribution right: The Licensee shall keep intact all copyright, patent or trademarks notices and all notices that refer to
70
+ the Licence and to the disclaimer of warranties. The Licensee must include a copy of such notices and a copy of the
71
+ Licence with every copy of the Work he/she distributes or communicates. The Licensee must cause any Derivative Work
72
+ to carry prominent notices stating that the Work has been modified and the date of modification.
73
+
74
+ Copyleft clause: If the Licensee distributes or communicates copies of the Original Works or Derivative Works, this
75
+ Distribution or Communication will be done under the terms of this Licence or of a later version of this Licence unless
76
+ the Original Work is expressly distributed only under this version of the Licence — for example by communicating
77
+ ‘EUPL v. 1.2 only’. The Licensee (becoming Licensor) cannot offer or impose any additional terms or conditions on the
78
+ Work or Derivative Work that alter or restrict the terms of the Licence.
79
+
80
+ Compatibility clause: If the Licensee Distributes or Communicates Derivative Works or copies thereof based upon both
81
+ the Work and another work licensed under a Compatible Licence, this Distribution or Communication can be done
82
+ under the terms of this Compatible Licence. For the sake of this clause, ‘Compatible Licence’ refers to the licences listed
83
+ in the appendix attached to this Licence. Should the Licensee's obligations under the Compatible Licence conflict with
84
+ his/her obligations under this Licence, the obligations of the Compatible Licence shall prevail.
85
+
86
+ Provision of Source Code: When distributing or communicating copies of the Work, the Licensee will provide
87
+ a machine-readable copy of the Source Code or indicate a repository where this Source will be easily and freely available
88
+ for as long as the Licensee continues to distribute or communicate the Work.
89
+ Legal Protection: This Licence does not grant permission to use the trade names, trademarks, service marks, or names
90
+ of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and
91
+ reproducing the content of the copyright notice.
92
+
93
+ 6.Chain of Authorship
94
+ The original Licensor warrants that the copyright in the Original Work granted hereunder is owned by him/her or
95
+ licensed to him/her and that he/she has the power and authority to grant the Licence.
96
+ Each Contributor warrants that the copyright in the modifications he/she brings to the Work are owned by him/her or
97
+ licensed to him/her and that he/she has the power and authority to grant the Licence.
98
+ Each time You accept the Licence, the original Licensor and subsequent Contributors grant You a licence to their contributions
99
+ to the Work, under the terms of this Licence.
100
+
101
+ 7.Disclaimer of Warranty
102
+ The Work is a work in progress, which is continuously improved by numerous Contributors. It is not a finished work
103
+ and may therefore contain defects or ‘bugs’ inherent to this type of development.
104
+ For the above reason, the Work is provided under the Licence on an ‘as is’ basis and without warranties of any kind
105
+ concerning the Work, including without limitation merchantability, fitness for a particular purpose, absence of defects or
106
+ errors, accuracy, non-infringement of intellectual property rights other than copyright as stated in Article 6 of this
107
+ Licence.
108
+ This disclaimer of warranty is an essential part of the Licence and a condition for the grant of any rights to the Work.
109
+
110
+ 8.Disclaimer of Liability
111
+ Except in the cases of wilful misconduct or damages directly caused to natural persons, the Licensor will in no event be
112
+ liable for any direct or indirect, material or moral, damages of any kind, arising out of the Licence or of the use of the
113
+ Work, including without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, loss
114
+ of data or any commercial damage, even if the Licensor has been advised of the possibility of such damage. However,
115
+ the Licensor will be liable under statutory product liability laws as far such laws apply to the Work.
116
+
117
+ 9.Additional agreements
118
+ While distributing the Work, You may choose to conclude an additional agreement, defining obligations or services
119
+ consistent with this Licence. However, if accepting obligations, You may act only on your own behalf and on your sole
120
+ responsibility, not on behalf of the original Licensor or any other Contributor, and only if You agree to indemnify,
121
+ defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against such Contributor by
122
+ the fact You have accepted any warranty or additional liability.
123
+
124
+ 10.Acceptance of the Licence
125
+ The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ placed under the bottom of a window
126
+ displaying the text of this Licence or by affirming consent in any other similar way, in accordance with the rules of
127
+ applicable law. Clicking on that icon indicates your clear and irrevocable acceptance of this Licence and all of its terms
128
+ and conditions.
129
+ Similarly, you irrevocably accept this Licence and all of its terms and conditions by exercising any rights granted to You
130
+ by Article 2 of this Licence, such as the use of the Work, the creation by You of a Derivative Work or the Distribution
131
+ or Communication by You of the Work or copies thereof.
132
+
133
+ 11.Information to the public
134
+ In case of any Distribution or Communication of the Work by means of electronic communication by You (for example,
135
+ by offering to download the Work from a remote location) the distribution channel or media (for example, a website)
136
+ must at least provide to the public the information requested by the applicable law regarding the Licensor, the Licence
137
+ and the way it may be accessible, concluded, stored and reproduced by the Licensee.
138
+
139
+ 12.Termination of the Licence
140
+ The Licence and the rights granted hereunder will terminate automatically upon any breach by the Licensee of the terms
141
+ of the Licence.
142
+ Such a termination will not terminate the licences of any person who has received the Work from the Licensee under
143
+ the Licence, provided such persons remain in full compliance with the Licence.
144
+
145
+ 13.Miscellaneous
146
+ Without prejudice of Article 9 above, the Licence represents the complete agreement between the Parties as to the
147
+ Work.
148
+ If any provision of the Licence is invalid or unenforceable under applicable law, this will not affect the validity or
149
+ enforceability of the Licence as a whole. Such provision will be construed or reformed so as necessary to make it valid
150
+ and enforceable.
151
+ The European Commission may publish other linguistic versions or new versions of this Licence or updated versions of
152
+ the Appendix, so far this is required and reasonable, without reducing the scope of the rights granted by the Licence.
153
+ New versions of the Licence will be published with a unique version number.
154
+ All linguistic versions of this Licence, approved by the European Commission, have identical value. Parties can take
155
+ advantage of the linguistic version of their choice.
156
+
157
+ 14.Jurisdiction
158
+ Without prejudice to specific agreement between parties,
159
+ — any litigation resulting from the interpretation of this License, arising between the European Union institutions,
160
+ bodies, offices or agencies, as a Licensor, and any Licensee, will be subject to the jurisdiction of the Court of Justice
161
+ of the European Union, as laid down in article 272 of the Treaty on the Functioning of the European Union,
162
+ — any litigation arising between other parties and resulting from the interpretation of this License, will be subject to
163
+ the exclusive jurisdiction of the competent court where the Licensor resides or conducts its primary business.
164
+
165
+ 15.Applicable Law
166
+ Without prejudice to specific agreement between parties,
167
+ — this Licence shall be governed by the law of the European Union Member State where the Licensor has his seat,
168
+ resides or has his registered office,
169
+ — this licence shall be governed by Belgian law if the Licensor has no seat, residence or registered office inside
170
+ a European Union Member State.
171
+
172
+
173
+ Appendix
174
+
175
+ ‘Compatible Licences’ according to Article 5 EUPL are:
176
+ — GNU General Public License (GPL) v. 2, v. 3
177
+ — GNU Affero General Public License (AGPL) v. 3
178
+ — Open Software License (OSL) v. 2.1, v. 3.0
179
+ — Eclipse Public License (EPL) v. 1.0
180
+ — CeCILL v. 2.0, v. 2.1
181
+ — Mozilla Public Licence (MPL) v. 2
182
+ — GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
183
+ — Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for works other than software
184
+ — European Union Public Licence (EUPL) v. 1.1, v. 1.2
185
+ — Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong Reciprocity (LiLiQ-R+).
186
+
187
+ The European Commission may update this Appendix to later versions of the above licences without producing
188
+ a new version of the EUPL, as long as they provide the rights granted in Article 2 of this Licence and protect the
189
+ covered Source Code from exclusive appropriation.
190
+ All other changes or additions to this Appendix require the production of a new EUPL version.
@@ -0,0 +1 @@
1
+ pyAS4