Newer
Older
from opencapif_sdk import capif_invoker_connector,capif_provider_connector
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
import os
import logging
import shutil
from requests.auth import HTTPBasicAuth
import urllib3
from OpenSSL.SSL import FILETYPE_PEM
from OpenSSL.crypto import (
dump_certificate_request,
dump_privatekey,
PKey,
TYPE_RSA,
X509Req
)
import requests
import json
import warnings
from requests.exceptions import RequestsDependencyWarning
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
warnings.filterwarnings("ignore", category=RequestsDependencyWarning)
# noqa: E501
# Basic configuration of the logger functionality
log_path = 'logs/sdk_logs.log'
log_dir = os.path.dirname(log_path)
if not os.path.exists(log_dir):
os.makedirs(log_dir)
logging.basicConfig(
level=logging.NOTSET, # Minimum severity level to log
# Log message format
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_path), # Log to a file
logging.StreamHandler() # Also display in the console
]
)
class capif_invoker_event_feature(capif_invoker_connector):
invoker_capif_details = self.invoker_capif_details
subscriberId = invoker_capif_details["api_invoker_id"]
path = self.capif_https_url + f"capif-events/v1/{subscriberId}/subscriptions"
payload = {
"events": self.events_description,
"eventFilters": self.events_filter,
"eventReq": {}, # TO IMPROVE !!!
"notificationDestination": f"{self.capif_callback_url}",
"requestTestNotification": True,
"websockNotifConfig": {
"websocketUri": f"{self.capif_callback_url}",
"requestWebsocketUri": True
},
"supportedFeatures": f"{self.supported_features}"
}
try:
response = requests.post(
url=path,
json=payload,
headers={"Content-Type": "application/json"},
cert=(self.signed_key_crt_path, self.private_key_path),
verify=os.path.join(self.invoker_folder, "ca.crt")
)
response.raise_for_status()
location_header = response.headers.get("Location")
if location_header:
# Extrae el identificador de la URL en el encabezado 'Location'
identifier = location_header.rstrip('/').split('/')[-1]
self.logger.info(f"Subscriptionid obtained: {identifier}")
else:
self.logger.error("The Location header is not available in the response")
path = os.path.join(self.invoker_folder, "capif_subscriptions_id.json")
# Load or initialize the subscription dictionary
# Load or initialize the subscription dictionary
if os.path.exists(path):
subscription = self._load_config_file(path)
if not isinstance(subscription, dict):
raise TypeError(f"Expected 'subscription' to be a dict, but got {type(subscription).__name__}")
if not isinstance(subscriberId, (str, int)):
raise TypeError(f"Expected 'subscriberId' to be a string or integer, but got {type(subscriberId).__name__}")
# Convert events_description to a string if it isn't already
if not isinstance(name, str):
name = str(name)
# Update the subscription structure
subscription[str(subscriberId)] = {
f"{name}": identifier
}
# Save the updated dictionary back to the file
self._create_or_update_file("capif_subscriptions_id", "json", subscription, "w")
except Exception as e:
self.logger.error("Unexpected error: %s", e)
return None, {"error": f"Unexpected error: {e}"}
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
def delete_subscription(self, name):
invoker_capif_details = self.invoker_capif_details
subscriberId = invoker_capif_details["api_invoker_id"]
path = os.path.join(self.invoker_folder, "capif_subscriptions_id.json")
if os.path.exists(path):
subscription = self._load_config_file(path)
if not isinstance(subscription, dict):
raise TypeError(f"Expected 'subscription' to be a dict, but got {type(subscription).__name__}")
if subscriberId in subscription and name in subscription[subscriberId]:
identifier = subscription[subscriberId][name]
# Attempt to delete the subscription from CAPIF
delete_path = self.capif_https_url + f"capif-events/v1/{subscriberId}/subscriptions/{identifier}"
try:
response = requests.delete(
url=delete_path,
headers={"Content-Type": "application/json"},
cert=(self.signed_key_crt_path, self.private_key_path),
verify=os.path.join(self.invoker_folder, "ca.crt")
)
response.raise_for_status()
# Remove the service entry from the subscription dictionary
del subscription[subscriberId][name]
# If no more services exist for the subscriber, remove the subscriber entry
if not subscription[subscriberId]:
del subscription[subscriberId]
# Save the updated dictionary back to the file
self._create_or_update_file("capif_subscriptions_id", "json", subscription, "w")
self.logger.info(f"Successfully deleted subscription for service '{name}'")
except Exception as e:
self.logger.error("Unexpected error: %s", e)
return None, {"error": f"Unexpected error: {e}"}
else:
self.logger.warning(f"Service '{name}' not found for subscriber '{subscriberId}'")
return None, {"error": f"Service '{name}' not found for subscriber '{subscriberId}'"}
else:
self.logger.error("Subscription file not found at path: %s", path)
return None, {"error": "Subscription file not found"}
def update_subcription(self, name):
invoker_capif_details = self.invoker_capif_details
subscriberId = invoker_capif_details["api_invoker_id"]
path = os.path.join(self.invoker_folder, "capif_subscriptions_id.json")
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
payload = {
"events": self.events_description,
"eventFilters": self.events_filter,
"eventReq": {}, # TO IMPROVE !!!
"notificationDestination": f"{self.capif_callback_url}",
"requestTestNotification": True,
"websockNotifConfig": {
"websocketUri": f"{self.capif_callback_url}",
"requestWebsocketUri": True
},
"supportedFeatures": f"{self.supported_features}"
}
if os.path.exists(path):
subscription = self._load_config_file(path)
if not isinstance(subscription, dict):
raise TypeError(f"Expected 'subscription' to be a dict, but got {type(subscription).__name__}")
if subscriberId in subscription and name in subscription[subscriberId]:
identifier = subscription[subscriberId][name]
# Attempt to delete the subscription from CAPIF
put_path = self.capif_https_url + f"capif-events/v1/{subscriberId}/subscriptions/{identifier}"
try:
response = requests.put(
url=put_path,
json=payload,
headers={"Content-Type": "application/json"},
cert=(self.signed_key_crt_path, self.private_key_path),
verify=os.path.join(self.invoker_folder, "ca.crt")
)
response.raise_for_status()
self.logger.info(f"Successfully updated subscription for service '{name}'")
except Exception as e:
self.logger.error("Unexpected error: %s", e)
return None, {"error": f"Unexpected error: {e}"}
else:
self.logger.warning(f"Service '{name}' not found for subscriber '{subscriberId}'")
return None, {"error": f"Service '{name}' not found for subscriber '{subscriberId}'"}
else:
self.logger.error("Subscription file not found at path: %s", path)
return None, {"error": "Subscription file not found"}
def patch_subcription(self, name):
self.update_subcription(self, name)
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
class capif_provider_event_feature(capif_provider_connector):
def create_subscription(self, name, id):
subscriberId = id
path = self.capif_https_url + f"capif-events/v1/{subscriberId}/subscriptions"
list_of_ids = self._load_provider_api_details()
number = self._find_key_by_value(list_of_ids, id)
payload = {
"events": self.events_description,
"eventFilters": self.events_filter,
"eventReq": {}, # TO IMPROVE !!!
"notificationDestination": f"{self.notification_destination}",
"requestTestNotification": True,
"websockNotifConfig": self.websock_notif_config,
"supportedFeatures": f"{self.supported_features}"
}
number_low = number.lower()
cert = (
os.path.join(self.provider_folder, f"{number_low}.crt"),
os.path.join(self.provider_folder, f"{number}_private_key.key"),
)
try:
response = requests.post(
url=path,
json=payload,
headers={"Content-Type": "application/json"},
cert=cert,
verify=os.path.join(self.provider_folder, "ca.crt")
)
response.raise_for_status()
location_header = response.headers.get("Location")
if location_header:
# Extrae el identificador de la URL en el encabezado 'Location'
identifier = location_header.rstrip('/').split('/')[-1]
self.logger.info(f"Subscriptionid obtained: {identifier}")
else:
self.logger.error("The Location header is not available in the response")
path = os.path.join(self.provider_folder, "capif_subscriptions_id.json")
# Load or initialize the subscription dictionary
# Load or initialize the subscription dictionary
if os.path.exists(path):
subscription = self._load_config_file(path)
if not isinstance(subscription, dict):
raise TypeError(f"Expected 'subscription' to be a dict, but got {type(subscription).__name__}")
else:
subscription = {}
if not isinstance(subscriberId, (str, int)):
raise TypeError(f"Expected 'subscriberId' to be a string or integer, but got {type(subscriberId).__name__}")
# Convert events_description to a string if it isn't already
if not isinstance(name, str):
name = str(name)
# Update the subscription structure
subscription[str(subscriberId)] = {
f"{name}": identifier
}
# Save the updated dictionary back to the file
self._create_or_update_file("capif_subscriptions_id", "json", subscription, "w")
except Exception as e:
self.logger.error("Unexpected error: %s", e)
return None, {"error": f"Unexpected error: {e}"}
def delete_subscription(self, name, id):
subscriberId = id
path = os.path.join(self.provider_folder, "capif_subscriptions_id.json")
if os.path.exists(path):
subscription = self._load_config_file(path)
if not isinstance(subscription, dict):
raise TypeError(f"Expected 'subscription' to be a dict, but got {type(subscription).__name__}")
if subscriberId in subscription and name in subscription[subscriberId]:
identifier = subscription[subscriberId][name]
# Attempt to delete the subscription from CAPIF
delete_path = self.capif_https_url + f"capif-events/v1/{subscriberId}/subscriptions/{identifier}"
list_of_ids = self._load_provider_api_details()
number = self._find_key_by_value(list_of_ids, id)
number_low = number.lower()
cert = (
os.path.join(self.provider_folder, f"{number_low}.crt"),
os.path.join(self.provider_folder, f"{number}_private_key.key"),
)
try:
response = requests.delete(
url=delete_path,
headers={"Content-Type": "application/json"},
cert=cert,
verify=os.path.join(self.provider_folder, "ca.crt")
)
response.raise_for_status()
# Remove the service entry from the subscription dictionary
del subscription[subscriberId][name]
# If no more services exist for the subscriber, remove the subscriber entry
if not subscription[subscriberId]:
del subscription[subscriberId]
# Save the updated dictionary back to the file
self._create_or_update_file("capif_subscriptions_id", "json", subscription, "w")
self.logger.info(f"Successfully deleted subscription for service '{name}'")
except Exception as e:
self.logger.error("Unexpected error: %s", e)
return None, {"error": f"Unexpected error: {e}"}
else:
self.logger.warning(f"Service '{name}' not found for subscriber '{subscriberId}'")
return None, {"error": f"Service '{name}' not found for subscriber '{subscriberId}'"}
else:
self.logger.error("Subscription file not found at path: %s", path)
return None, {"error": "Subscription file not found"}
def update_subcription(self, name, id):
subscriberId = id
path = os.path.join(self.provider_folder, "capif_subscriptions_id.json")
list_of_ids = self._load_provider_api_details()
number = self._find_key_by_value(list_of_ids, id)
payload = {
"events": self.events_description,
"eventFilters": self.events_filter,
"eventReq": {}, # TO IMPROVE !!!
"notificationDestination": f"{self.notification_destination}",
"requestTestNotification": True,
"websockNotifConfig": self.websock_notif_config,
"supportedFeatures": f"{self.supported_features}"
}
if os.path.exists(path):
subscription = self._load_config_file(path)
if not isinstance(subscription, dict):
raise TypeError(f"Expected 'subscription' to be a dict, but got {type(subscription).__name__}")
if subscriberId in subscription and name in subscription[subscriberId]:
identifier = subscription[subscriberId][name]
# Attempt to delete the subscription from CAPIF
put_path = self.capif_https_url + f"capif-events/v1/{subscriberId}/subscriptions/{identifier}"
list_of_ids = self._load_provider_api_details()
number = self._find_key_by_value(list_of_ids, id)
number_low = number.lower()
cert = (
os.path.join(self.provider_folder, f"{number_low}.crt"),
os.path.join(self.provider_folder, f"{number}_private_key.key"),
)
try:
response = requests.put(
url=put_path,
json=payload,
headers={"Content-Type": "application/json"},
cert=cert,
verify=os.path.join(self.provider_folder, "ca.crt")
)
response.raise_for_status()
# Remove the service entry from the subscription dictionary
del subscription[subscriberId][name]
# If no more services exist for the subscriber, remove the subscriber entry
if not subscription[subscriberId]:
del subscription[subscriberId]
# Save the updated dictionary back to the file
self._create_or_update_file("capif_subscriptions_id", "json", subscription, "w")
self.logger.info(f"Successfully updated subscription for service '{name}'")
except Exception as e:
self.logger.error("Unexpected error: %s", e)
return None, {"error": f"Unexpected error: {e}"}
else:
self.logger.warning(f"Service '{name}' not found for subscriber '{subscriberId}'")
return None, {"error": f"Service '{name}' not found for subscriber '{subscriberId}'"}
else:
self.logger.error("Subscription file not found at path: %s", path)
return None, {"error": "Subscription file not found"}
def patch_subcription(self, name, id):
self.update_subcription(self, name, id)