-
Notifications
You must be signed in to change notification settings - Fork 1
/
requester.py
683 lines (587 loc) · 21.1 KB
/
requester.py
1
2
3
4
5
6
7
8
9
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
#
# Copyright (c) 2022-2023 Geosiris.
# SPDX-License-Identifier: Apache-2.0
#
import re
from zipfile import ZipFile
from lxml import etree
from io import BytesIO
from lxml.etree import (
Element,
ElementTree,
fromstring,
XPath,
)
from typing import List
from etptypes.energistics.etp.v12.datatypes.supported_protocol import (
SupportedProtocol,
)
from etptypes.energistics.etp.v12.datatypes.supported_data_object import (
SupportedDataObject,
)
from etptypes.energistics.etp.v12.datatypes.version import Version
import uuid
from datetime import datetime
from etpproto.messages import Message
from etptypes.energistics.etp.v12.datatypes.object.context_info import (
ContextInfo,
)
from etptypes.energistics.etp.v12.datatypes.object.context_scope_kind import (
ContextScopeKind,
)
from etptypes.energistics.etp.v12.datatypes.object.active_status_kind import (
ActiveStatusKind,
)
from etptypes.energistics.etp.v12.datatypes.object.relationship_kind import (
RelationshipKind,
)
from etptypes.energistics.etp.v12.protocol.dataspace.get_dataspaces import (
GetDataspaces,
)
from etptypes.energistics.etp.v12.protocol.dataspace.delete_dataspaces import (
DeleteDataspaces,
)
from etptypes.energistics.etp.v12.protocol.dataspace.put_dataspaces import (
PutDataspaces,
)
from etptypes.energistics.etp.v12.protocol.core.request_session import (
RequestSession,
)
from etptypes.energistics.etp.v12.protocol.core.close_session import (
CloseSession,
)
from etptypes.energistics.etp.v12.protocol.discovery.get_resources import (
GetResources,
)
from etptypes.energistics.etp.v12.protocol.discovery.get_deleted_resources import (
GetDeletedResources,
)
from etptypes.energistics.etp.v12.protocol.store.put_data_objects import (
PutDataObjects,
)
from etptypes.energistics.etp.v12.protocol.store.get_data_objects import (
GetDataObjects,
)
from etptypes.energistics.etp.v12.protocol.store.get_data_objects_response import (
GetDataObjectsResponse,
)
from etptypes.energistics.etp.v12.protocol.store.delete_data_objects import (
DeleteDataObjects,
)
from etptypes.energistics.etp.v12.datatypes.object.data_object import (
DataObject,
)
from etptypes.energistics.etp.v12.datatypes.data_array_types.data_array_identifier import (
DataArrayIdentifier,
)
from etptypes.energistics.etp.v12.datatypes.data_array_types.get_data_subarrays_type import (
GetDataSubarraysType,
)
from etptypes.energistics.etp.v12.protocol.data_array.get_data_arrays import (
GetDataArrays,
)
from etptypes.energistics.etp.v12.protocol.data_array.get_data_subarrays import (
GetDataSubarrays,
)
from etptypes.energistics.etp.v12.protocol.data_array.get_data_array_metadata import (
GetDataArrayMetadata,
)
from etptypes.energistics.etp.v12.protocol.supported_types.get_supported_types import (
GetSupportedTypes,
)
from etptypes.energistics.etp.v12.protocol.supported_types.get_supported_types_response import (
GetSupportedTypesResponse,
)
from etptypes.energistics.etp.v12.datatypes.data_value import DataValue
from etptypes.energistics.etp.v12.datatypes.object.resource import Resource
from etptypes.energistics.etp.v12.datatypes.object.dataspace import Dataspace
# from etptypes.energistics.etp.v12.datatypes.uuid import to_Uuid, to_UUID
from etpproto.uri import *
from etpproto.connection import ETPConnection, CommunicationProtocol
from etpproto.uri import parse_uri
from etpclient.etp.h5_handler import generate_put_data_arrays
from etpclient.utils import (
xml_get_type,
get_xml_tree_string,
)
ENERGYML_NAMESPACES = {
"eml": "http://www.energistics.org/energyml/data/commonv2",
"prodml": "http://www.energistics.org/energyml/data/prodmlv2",
"witsml": "http://www.energistics.org/energyml/data/witsmlv2",
"resqml": "http://www.energistics.org/energyml/data/resqmlv2",
}
def energyml_xpath(tree: Element, xpath: str) -> Optional[list]:
"""A xpath research that knows energyml namespaces"""
try:
return XPath(xpath, namespaces=ENERGYML_NAMESPACES)(tree)
except TypeError:
return None
etp_version = Version(major=1, minor=2, revision=0, patch=0)
local_protocols = [
SupportedProtocol(
protocol=CommunicationProtocol.CORE.value,
protocolVersion=etp_version,
role="server",
protocolCapabilities={},
),
SupportedProtocol(
protocol=CommunicationProtocol.DISCOVERY.value,
protocolVersion=etp_version,
role="store",
protocolCapabilities={},
),
SupportedProtocol(
protocol=CommunicationProtocol.STORE.value,
protocolVersion=etp_version,
role="store",
protocolCapabilities={},
),
SupportedProtocol(
protocol=CommunicationProtocol.DATASPACE.value,
protocolVersion=etp_version,
role="store",
protocolCapabilities={},
),
]
supported_objects = [
# SupportedDataObject(
# qualifiedType="resqml20", dataObjectCapabilities={} # ["resqml20"]
# )
SupportedDataObject(
qualified_type="eml20.*",
data_object_capabilities={
"SupportsDelete": DataValue(item=True),
"SupportsPut": DataValue(item=True),
"SupportsGet": DataValue(item=True),
},
),
SupportedDataObject(
qualified_type="resqml20.*",
data_object_capabilities={
"SupportsDelete": DataValue(item=True),
"SupportsPut": DataValue(item=True),
"SupportsGet": DataValue(item=True),
},
),
]
def findUuid(input: str) -> Optional[str]:
p = re.compile(UUID_REGEX)
result = p.search(input)
if result is not None:
return result.group() if result else None
else:
return None
def find_uuid_in_elt(root: Element) -> str:
_uuids = energyml_xpath(root, "@uuid")
if len(_uuids) <= 0:
_uuids = energyml_xpath(root, "@UUID")
return _uuids[0] if len(_uuids) > 0 else None
def find_uuid_in_xml(xml_content: bytes) -> str:
try:
tree = ElementTree(fromstring(xml_content))
root = tree.getroot()
return find_uuid_in_elt(root)
except etree.XMLSyntaxError:
print("Error reading xml")
return None
def get_root_type_in_xml(xml_content: bytes) -> str:
try:
tree = ElementTree(fromstring(xml_content))
root = tree.getroot()
return root.tag
except etree.XMLSyntaxError:
print("Error reading xml")
return None
def request_session():
return RequestSession(
applicationName="Geosiris etp client",
applicationVersion="0.0.1",
clientInstanceId=uuid.uuid4(),
requestedProtocols=local_protocols, # ETPConnection.server_capabilities.supported_protocols
supportedDataObjects=ETPConnection.server_capabilities.supported_data_objects,
supportedCompression=ETPConnection.server_capabilities.supported_compression,
supportedFormats=ETPConnection.server_capabilities.supported_formats,
currentDateTime=int(datetime.utcnow().timestamp()),
endpointCapabilities={},
earliest_retained_change_time=0,
)
def get_scope(scope: str):
if scope is not None:
scope_lw = scope.lower()
if "target" in scope_lw:
if "self" in scope_lw:
return ContextScopeKind.TARGETS_OR_SELF
else:
return ContextScopeKind.TARGETS
elif "source" in scope_lw:
if "self" in scope_lw:
return ContextScopeKind.SOURCES_OR_SELF
else:
return ContextScopeKind.SOURCES
return ContextScopeKind.SELF
def get_resouces(uri: str = "eml:///", depth: int = 1, scope=None):
if uri is not None:
if not uri.startswith("eml:///"):
uri = f"eml:///dataspace('{uri}')"
else:
uri = "eml:///"
return GetResources(
context=ContextInfo(
uri=uri,
depth=depth,
dataObjectTypes=[],
navigableEdges=RelationshipKind.PRIMARY,
),
scope=get_scope(scope),
countObjects=False,
storeLastWriteFilter=None,
activeStatusFilter=ActiveStatusKind.INACTIVE,
includeEdges=False,
)
def get_dataspaces():
return GetDataspaces()
async def extractResqmlUuid(content: str):
return await findUuid(content)
XML_TYPE_REGXP = r"<([\w]+:)?([\w]+)"
def extractResqmlURI(content: str, dataspace_name: str = None):
pattern = re.compile(XML_TYPE_REGXP)
# print("PATT ", pattern)
result = pattern.search(content)
# print("result ", result)
return (
"eml:///"
+ (
"dataspace('" + dataspace_name + "')/"
if dataspace_name is not None
else ""
)
+ "resqml20."
+ result.group(2)
+ "("
+ extractResqmlUuid(content)
+ ")"
)
def put_dataspace(dataspace_names: list):
ds_map = {}
for ds_name in dataspace_names:
ds_map[str(len(ds_map))] = Dataspace(
uri="eml:///dataspace('" + ds_name + "')"
if "eml:///" not in ds_name
else ds_name,
store_last_write=0,
store_created=0,
)
return PutDataspaces(dataspaces=ds_map)
def delete_dataspace(dataspace_names: list):
ds_map = {}
for ds_name in dataspace_names:
ds_map[str(len(ds_map))] = (
"eml:///dataspace('" + ds_name + "')"
if "eml:///" not in ds_name
else ds_name
)
return DeleteDataspaces(uris=ds_map)
def delete_data_object(uris: list):
print(
"Sending delete_data_object : ", {i: uris[i] for i in range(len(uris))}
)
return DeleteDataObjects(
uris={i: uris[i] for i in range(len(uris))},
prune_contained_objects=False,
)
def get_deleted_resources(
dataspace_names: str,
delete_time_filter: int = None,
data_object_types: list = [],
):
ds_uri = (
"eml:///dataspace('" + dataspace_names + "')"
if "eml:///" not in dataspace_names
else dataspace_names
)
return GetDeletedResources(
dataspace_uri=ds_uri,
delete_time_filter=delete_time_filter,
data_object_types=data_object_types,
)
def put_data_object_by_path(
path: str, dataspace_name: str = None, uuids_filter: list = None
):
result = []
# try:
if path.endswith(".xml"):
f = open(path)
f_content = f.read()
result.append(put_data_object(f_content, dataspace_name))
f.close()
elif path.endswith(".epc"):
do_lst = {}
try:
with zipfile.ZipFile(path, "r") as zfile:
for zinfo in zfile.infolist():
if zinfo.filename.endswith(".xml"):
# print('%s (%s --> %s)' % (zinfo.filename, zinfo.file_size, zinfo.compress_size))
with zfile.open(zinfo.filename) as myfile:
file_content = myfile.read()
uuid = findUuid(zinfo.filename)
if uuid is None:
uuid = find_uuid_in_xml(file_content)
print(f"UUID {uuid}")
if uuid is not None and (
uuids_filter is None
or len(uuids_filter) == 0
or uuid in uuids_filter
):
do_lst[len(do_lst)] = _create_data_object(
file_content.decode("utf-8"),
dataspace_name,
)
else:
print(f"Ignoring file : {zinfo.filename}")
except FileNotFoundError:
print(f"File {path} not found")
result.append(PutDataObjects(data_objects=do_lst))
else:
print("Unkown file type")
# except Exception as e:
# print("Except : ", e)
return result
def _create_data_object(f_content: str, dataspace_name: str = None):
uri = extractResqmlURI(f_content, dataspace_name)
print("Sending data object at uri ", uri)
real_uuid = uuid.UUID(extractResqmlUuid(f_content)).hex
ressource = Resource(
uri=uri,
name=uri, # + ".xml",
source_count=0,
target_count=0,
last_changed=0,
store_last_write=0,
store_created=0,
active_status=ActiveStatusKind.INACTIVE,
alternate_uris=[],
custom_data=[],
)
return DataObject(blob_id=real_uuid, resource=ressource, data=f_content)
def put_data_object(f_content: str, dataspace_name: str = None):
uri = extractResqmlURI(f_content, dataspace_name)
print("Sending data object at uri ", uri)
real_uuid = uuid.UUID(extractResqmlUuid(f_content)).hex
ressource = Resource(
uri=uri,
name=uri, # + ".xml",
source_count=0,
target_count=0,
last_changed=0,
store_last_write=0,
store_created=0,
active_status=ActiveStatusKind.INACTIVE,
alternate_uris=[],
custom_data=[],
)
do = DataObject(blob_id=real_uuid, resource=ressource, data=f_content)
return PutDataObjects(data_objects={"0": do})
def get_data_object(uris: List[str], format: str = "xml"):
uris_dict = {}
for num, u in enumerate(uris, start=1):
uris_dict[num] = u
return GetDataObjects(uris=uris_dict, format_=format)
def get_close_session(reason="We have finished"):
return CloseSession(reason=reason)
# _____ __ ________
# / ___/__ ______ ____ ____ _____/ /____ ____/ /_ __/_ ______ ___ _____
# \__ \/ / / / __ \/ __ \/ __ \/ ___/ __/ _ \/ __ / / / / / / / __ \/ _ \/ ___/
# ___/ / /_/ / /_/ / /_/ / /_/ / / / /_/ __/ /_/ / / / / /_/ / /_/ / __(__ )
# /____/\__,_/ .___/ .___/\____/_/ \__/\___/\__,_/ /_/ \__, / .___/\___/____/
# /_/ /_/ /____/_/
def get_supported_types(
uri: str,
count: bool = True,
return_empty_types: bool = True,
scope: str = "self",
):
if not uri.startswith("eml:///"):
uri = f"eml:///dataspace('{uri}')"
if isinstance(count, str):
count = count.lower() == "true"
if isinstance(return_empty_types, str):
return_empty_types = return_empty_types.lower() == "true"
print(
f"==> uri={uri}, count={count}, return_empty_types={return_empty_types}"
)
return GetSupportedTypes(
uri=uri,
count_objects=count,
return_empty_types=return_empty_types,
scope=get_scope(scope),
)
# ____ __ ___
# / __ \____ _/ /_____ _/ | ______________ ___ __
# / / / / __ `/ __/ __ `/ /| | / ___/ ___/ __ `/ / / /
# / /_/ / /_/ / /_/ /_/ / ___ |/ / / / / /_/ / /_/ /
# /_____/\__,_/\__/\__,_/_/ |_/_/ /_/ \__,_/\__, /
# /____/
def get_data_array_metadata(uri: str, path_in_res: str):
return GetDataArrayMetadata(
data_arrays={
"0": DataArrayIdentifier(uri=uri, path_in_resource=path_in_res)
}
)
def get_data_array(
uri: str, path_in_res: str, start: int = None, count: int = None
):
if start is not None and count is not None:
return GetDataSubarrays(
data_subarrays={
"0": GetDataSubarraysType(
uid=DataArrayIdentifier(
uri=uri, path_in_resource=path_in_res
),
starts=[start],
counts=[count],
)
}
)
else:
return GetDataArrays(
data_arrays={
"0": DataArrayIdentifier(uri=uri, path_in_resource=path_in_res)
}
)
def put_data_array(
uuids_filter: list,
epc_or_xml_file_path: str,
h5_file_path: str,
dataspace_name: str,
):
print("FILE ", epc_or_xml_file_path)
result = []
if epc_or_xml_file_path.endswith(".epc"):
zfile = zipfile.ZipFile(epc_or_xml_file_path, "r")
for zinfo in zfile.infolist():
if (
zinfo.filename.endswith(".xml")
and findUuid(zinfo.filename) is not None
):
uuid = findUuid(zinfo.filename)
if (
uuids_filter is None
or len(uuids_filter) == 0
or uuid in uuids_filter
):
print("> Uuid filtered: ", uuid)
# with zfile.open(zinfo.filename) as myfile:
# result += generate_put_data_arrays(
# myfile.read().decode("utf-8"),
# h5_file_path,
# dataspace_name,
# )
else:
pass
# print("Not imported ", uuid)
zfile.close()
else:
with open(epc_or_xml_file_path) as f:
result += generate_put_data_arrays(
f.read().decode("utf-8"), h5_file_path, dataspace_name
)
return result
async def put_data_array_sender(
websocket,
uuids_filter: list,
epc_or_xml_file_path: str,
h5_file_path: str,
dataspace_name: str,
type_filter: str = None,
):
print(
f"uuids_filter : {uuids_filter} epc_or_xml_file_path : {epc_or_xml_file_path} h5_file_path : {h5_file_path} dataspace_name : {dataspace_name} type_filter : {type_filter} "
)
if epc_or_xml_file_path.endswith(".epc"):
zfile = zipfile.ZipFile(epc_or_xml_file_path, "r")
for zinfo in zfile.infolist():
if (
zinfo.filename.endswith(".xml")
and findUuid(zinfo.filename) is not None
):
uuid = findUuid(zinfo.filename)
accept_file = (
uuids_filter is None
or len(uuids_filter) == 0
or uuid in uuids_filter
)
if type_filter is not None:
with zfile.open(zinfo.filename) as myfile:
file_content = myfile.read()
file_type = xml_get_type(
get_xml_tree_string(file_content)
)
accept_file = accept_file or re.match(
type_filter, file_type
)
if accept_file:
print(" > accept_file Uuid : ", uuid)
with zfile.open(zinfo.filename) as myfile:
for pda in generate_put_data_arrays(
myfile.read().decode("utf-8"),
h5_file_path,
dataspace_name,
):
# print(type(pda), pda)
try:
yield await websocket.send_no_wait(pda)
except Exception as e:
print("ERROR : ", e)
else:
print("Not imported ", uuid, " -- ", uuid in uuids_filter)
pass
zfile.close()
else:
with open(epc_or_xml_file_path) as f:
for pda in generate_put_data_arrays(
f.read().decode("utf-8"), h5_file_path, dataspace_name
):
try:
yield await websocket.send_no_wait(pda)
except Exception as e:
print(e)
async def download_dataspace(
ws, output_file_path: str, dataspace_name: str = None
):
get_res = get_resouces(uri=dataspace_name, depth=1, scope="sources")
result_get_res = await ws.send_and_wait(get_res)
# print("===>", result_get_res)
uri_list = []
for msg in result_get_res:
try:
uri_list += list(map(lambda r: r.uri, msg.body.resources))
except Exception as e:
print("Err ", {type(e).__name__}, e)
print(f"URIS to download : {uri_list}")
if len(uri_list) <= 0:
print("No Object to download")
return
all_in_one = False
result_get_do = []
if all_in_one:
get_do = get_data_object(uri_list, format="xml")
result_get_do = result_get_do + await ws.send_and_wait(get_do)
else:
for uri in uri_list:
get_do = get_data_object([uri], format="xml")
result_get_do = result_get_do + await ws.send_and_wait(get_do)
# print(result_get_do)
# TODO : ecrire epc
if not output_file_path.endswith(".zip"):
output_file_path = output_file_path + ".zip"
with ZipFile(output_file_path, "w") as zip_file:
for msg in result_get_do:
if isinstance(msg.body, GetDataObjectsResponse):
for _id, do in msg.body.data_objects.items():
obj_uri = parse_uri(do.resource.uri)
obj_path = f"{obj_uri.object_type}_{obj_uri.uuid}.xml"
print(f"Storing file : {obj_path}")
with zip_file.open(obj_path, "w") as xml_file:
xml_file.write(do.data)
else:
print(f"Not a dataobject :{type(msg.body)} : {msg.body}")