Newer
Older
from opencapif_sdk import capif_invoker_connector, capif_provider_connector
import os
import logging
import urllib3
import requests
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):
JorgeEcheva26
committed
def create_subscription(self, name, supp_features=0):
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
},
JorgeEcheva26
committed
"supportedFeatures": f"{supp_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)
JorgeEcheva26
committed
if str(subscriberId) not in subscription:
# If the subscriberId is not in the subscription, create an empty dictionary for it
subscription[str(subscriberId)] = {}
JorgeEcheva26
committed
subscription[str(subscriberId)][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}"}
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
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"}
JorgeEcheva26
committed
def update_subcription(self, name, supp_features=0):
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")
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
},
JorgeEcheva26
committed
"supportedFeatures": f"{supp_features}"
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
}
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)
class capif_provider_event_feature(capif_provider_connector):
JorgeEcheva26
committed
def create_subscription(self, name, id, supp_features=0):
subscriberId = id
path = self.capif_https_url + f"capif-events/v1/{subscriberId}/subscriptions"
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,
JorgeEcheva26
committed
"supportedFeatures": f"{supp_features}"
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()
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
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)
JorgeEcheva26
committed
if str(subscriberId) not in subscription:
# If the subscriberId is not in the subscription, create an empty dictionary for it
subscription[str(subscriberId)] = {}
JorgeEcheva26
committed
subscription[str(subscriberId)][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)
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
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"}
JorgeEcheva26
committed
def update_subcription(self, name, id, supp_features=0):
path = os.path.join(self.provider_folder, "capif_subscriptions_id.json")
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,
JorgeEcheva26
committed
"supportedFeatures": f"{supp_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)
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
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"}
JorgeEcheva26
committed
def patch_subcription(self, name, id, supp_features=0):
self.update_subcription(self, name, id, supp_features)