milestonexprotectwspython.xpwwebservicebase
Module: xpwwebservicebase.py
Revision History
Date | Version | Description |
---|---|---|
2023/07/11 | 1.0.0.0 | Initial Version. |
The XPWWebServiceBase class provides properties common to all XProtect web-services.
Threadsafety:
This class is fully thread-safe.
Initializes a new instance of the class.
Arguments:
- loginInfo (XPWLoginInfo): Login Information class that contains login token information. This class is returned
on a successful call to any of the LoginX methods from classes that inherit from
XPWWebServiceBase. This allows you to share the same Login Information (token, etc)
between service classes.
Specify null / None to not share Login Information; if doing so, then your first call must be to one of the Login methods (e.g. LoginBasicUser, LoginWindowsUser, etc).
Default is null / None.
Raises:
- XPWException: If supplied, the loginInfo argument was not of type XPWLoginInfo.
The method fails for any reason.
Instance identifier that uniquely identifies the calling application.
Returns:
The InstanceId property value.
The Instance Identifier is a GUID that uniquely identifies the calling application. Typically, each ID should refer to a specific machine running an integration.
Enables / disables the automatic token renewal check logic check that is made prior to making a call to the XProtect web service.
Returns:
The IsAutoTokenRenewalEnabled property value.
If True, the LoginInfo.ExpireTime value is checked to see if the XProtect token is within 1 minute of expiring PRIOR to processing the desired API method (e.g. GetCameras, etc). If the token is about to expire, then it will be automatically renewed via a call to the XProtect web-services Login method (e.g. LoginBasicUser, LoginBasicWindows) that was previously used to login and establish the authentication token. The desired API method (e.g. GetCameras, etc) is then processed as requested.
If False, the desired API method (e.g. GetCameras, etc) is processed normally, though it will probably fail with a XPWLoginTokenExpiredException due to an expired token!
SSL Verify flag used on all request GET / POST method calls. Default Value is True.
Returns:
The IsSslVerifyEnabled property value.
This setting will be added to all request GET / POST calls made to the XProtect web services.
If False, it will ignore SSL Certificate warnings (e.g. certificate expired, self-signed certificate, etc). It also makes a call to "urllib3.disable_warnings(category=InsecureRequestWarning)" to suppress terminal messages.
LoginInfo object that was specified when the class was initialized, or when a Login method (e.g. LoginBasicUser, LoginWindowsUser) was called successfully.
Returns:
The LoginInfo property value.
This property is read-only.
URL prefix of the XProtect Management Server.
Returns:
The ManagementServerUrlPrefix property value.
This url prefix is used to call various web-services that are hosted by the XProtect Management Server. These services include the ServerCommandService.svc, etc.
It should only contain the server name (and port number if required) portion of the server url (e.g. "https://xprotectmanagementserver.example.com", or "https://xprotectmanagementserver.example.com:443").
It should NOT contain any of the server web-service method names or paths (e.g. "https://xprotectmanagementserver.example.com/ManagementServer/ServerCommandService.svc").
URL prefix of the XProtect Server API Server.
Returns:
The ServerApiUrlPrefix property value.
This url prefix is used to call various web-services that are hosted by the XProtect Server API Server. These services include the ServerCommandService.asmx, etc.
It should only contain the server name (and port number if required) portion of the server url (e.g. "https://xprotectmanagementserver.example.com", or "https://xprotectmanagementserver.example.com:443").
It should NOT contain any of the server web-service method names or paths (e.g. "https://xprotectmanagementserver.example.com/ServerAPI/ServerCommandService.asmx").
Checks a dictionary for the specified key name, ensures that it defines a list of strings, and then appends them to the arrayListStrings argument list; otherwise, no values are appended to the arrayListStrings argument.
Arguments:
- oDict (dict): Dictionary to check for the specified key name.
- keyName (str): Key name to check for.
- arrayListStrings (str): An array list of strings to append found values to.
- raiseExceptionIfNotFound (bool): True to raise an Exception if the specified keyName is not found in the dictionary;
otherwise, False.
Default value: False
Check the web-service HTTP response code for error values (4xx, 5xx, etc). An XPWWebServiceException will be thrown if the HTTP status code does not equal 200 or 201.
Arguments:
- serviceMethodName (str): Name of the XProtect web-service method that was called. Example: "GetCameras"
- req (Request): HTTP request object that contains the web server request.
- resp (Response): HTTP response object that contains the web server response.
- serviceResultKeyName (str): Name of the XProtect web-service results node that contains response details. Example: "LoginResult"
- serviceResultNamespaces (dict): XML namespaces to override on the xmltodict parse method. This allows the
xmltodict parser to correctly process XML namespaces in the response. You may
also specify null / None if no namespace references are present in the response.
Example: { 'http://videoos.net/2/XProtectCSServiceRegistration':None, 'http://schemas.microsoft.com/2003/10/Serialization/Arrays':None } - raiseExceptionIfServiceResultKeyNameNotFound (bool): True to raise an Exception if the specified serviceResultKeyName argument value is
not found in the responseXml; otherwise, False.
Default value: False
Returns:
If HTTP status is unsuccessful (e.g. not 200, 201) then an XPWWebServiceException is raised.
If HTTP status is successful (e.g. 200, 201) then the soap XML response is searched for a node that is specified by the serviceResultKeyName argument value.
If found, the XML node is converted to a dictionary via XMLTODICT and returned to the caller.
If not found, then it denotes that no results were found for the request; in this case, an exception will be raised if the raiseExceptionIfServiceResultKeyNameNotFound argument is True; otherwise, a null / None value is returned.
Raises:
- XPWWebServiceException: Raised if the HTTP status returned indicated failue (e.g. 4xx, 5xx, etc).
Parses XProtect web-services failed HTTP response and raises the XPWWebServiceException to indicate the requested call failed.
Arguments:
- serviceMethodName (str): Name of the XProtect web-service method that was called. Example: "GetCameras"
- req (Request): HTTP request object that contains the web server request.
- resp (Response): HTTP response object that contains the web server response.
Raises:
- XPWWebServiceException: Thrown if XProtext web-service error response details were parsed successfully.
- XPWException: Thrown if XProtext web-service error response details could not be parsed successfully.
Checks a dictionary for the specified key name.
Arguments:
- oDict (dict): Dictionary to check for the specified key name.
- keyName (str): Key name to check for.
Returns:
True if the specified key name exists in the dictionary; otherwise, False.
Checks a dictionary for the specified collection key name, and verifies it contains at least one key underneath it with the specified KeyNameItem name.
Arguments:
- oDict (dict): Dictionary to check for the specified collection key and child item key.
- keyNameCollection (str): Key name to check for that contains a collection of nodes.
- keyNameItem (str): Item Key name to check for that contains a child item.
Returns:
A dictionary of item key names, or an empty dictionary if none were found.
This method is useful for parsing collection responses and their underlying item nodes.
For example:
Checks a dictionary for the specified item key name, and verifies it contains at least one occurance.
Arguments:
- oDict (dict): Dictionary to check for the specified collection key and child item key.
- keyNameItem (str): Item Key name to check for that contains a child item.
Returns:
A dictionary of item key names, or an empty dictionary if none were found.
This method is useful for parsing collection responses and their underlying item nodes.
For example:
Checks a dictionary for the specified key name and returns a boolean value if the key exists; otherwise, null is returned.
Arguments:
- oDict (dict): Dictionary to check for the specified key name.
- keyName (str): Key name to check for.
- raiseExceptionIfNotFound (bool): True to raise an Exception if the specified keyName is not found in the dictionary;
otherwise, False.
Default value: False
Returns:
The boolean value of the specified key name if the key exists; otherwise, null.
Checks a dictionary for the specified key name and returns a datetime value if the key exists; otherwise, null is returned.
Arguments:
- oDict (dict): Dictionary to check for the specified key name.
- keyName (str): Key name to check for.
- raiseExceptionIfNotFound (bool): True to raise an Exception if the specified keyName is not found in the dictionary
or the value could not be converted to a datetime object; otherwise, False.
Default value: False - excludeMicroseconds (bool): If True, only the first 19 characters of the date string will be kept - this
assumes that the datetime string is in "YYYY-MM-DDTHH:MM:SS" format.
Default value: False - excludeTimeZoneInfo (bool): If True, then timezone info (tzinfo) is removed from the datetime value.
This can prevent "can't subtract offset-naive and offset-aware datetimes" exceptions when comparing datetimes.
Default value: True
Returns:
The datetime value of the specified key name if the key exists; otherwise, null.
Supported examples for datetime string are:
- "0001-01-01T00:00:00.0000000"
- "2023-07-24T17:12:31.0210000Z"
- "2023-07-24T17:12:31.0210Z"
- "2023-07-24T17:12:31Z"
Checks a dictionary for the specified key name and returns the value if the key exists; otherwise, null is returned.
Arguments:
- oDict (dict): Dictionary to check for the specified key name.
- keyName (str): Key name to check for.
- raiseExceptionIfNotFound (bool): True to raise an Exception if the specified keyName is not found in the dictionary;
otherwise, False.
Default value: False
Returns:
The value of the specified key name if the key exists; otherwise, null.
Checks a dictionary for the specified key name and returns a float value if the key exists; otherwise, null is returned.
Arguments:
- oDict (dict): Dictionary to check for the specified key name.
- keyName (str): Key name to check for.
- raiseExceptionIfNotFound (bool): True to raise an Exception if the specified keyName is not found in the dictionary;
otherwise, False.
Default value: False
Returns:
The float value of the specified key name if the key exists; otherwise, null.
Checks a dictionary for the specified key name and returns a integer value if the key exists; otherwise, null is returned.
Arguments:
- oDict (dict): Dictionary to check for the specified key name.
- keyName (str): Key name to check for.
- raiseExceptionIfNotFound (bool): True to raise an Exception if the specified keyName is not found in the dictionary;
otherwise, False.
Default value: False
Returns:
The integer value of the specified key name if the key exists; otherwise, null.
Checks a dictionary for the specified key name and returns a string value if the key exists; otherwise, null is returned.
Arguments:
- oDict (dict): Dictionary to check for the specified key name.
- keyName (str): Key name to check for.
- raiseExceptionIfNotFound (bool): True to raise an Exception if the specified keyName is not found in the dictionary;
otherwise, False.
Default value: False
Returns:
The string value of the specified key name if the key exists; otherwise, null.
Parses XProtect web-services response for the given block of XML that is specified by the searchNode argument, and uses the xmltodict package to convert the found result to a dictionary.
Arguments:
- responseXml (str): String that contains the XML response of the called web-service method.
- webserviceMethod (str): Name of the XProtect web-service method that was called. Example: "LoginBasicUser"
- searchNode (str): XML node to search for in the response (case-sensitive). Example: "LoginResult"
- searchNamespaces (dict): XML namespaces to override on the xmltodict parse method. This allows the xmltodict parser to correctly process XML namespaces in the response. Example: { 'http://videoos.net/2/XProtectCSServiceRegistration':None, 'http://schemas.microsoft.com/2003/10/Serialization/Arrays':None }
- raiseExceptionIfNotFound (bool): True to raise an Exception if the specified searchNode is not found in the responseXml;
otherwise, False.
Default value: True
Raises:
- Exception: If the start or end nodes could not be found, or if xmltodict could not create a dictionary from the found block of xml.
Returns:
An dictionary that represents the desired XML response node, or null (None) if no items were returned.
Authenticates a user with the specified Basic User login account.
Arguments:
- username (str): Basic account type User Name to authenticate.
- password (str): Basic account type Password for the specified User Name to authenticate.
- currentToken (str): If renewing an existing login token, the value of a previously generated login token; otherwise, an empty string if this is a new Login or you don't wish to renew a token.
Raises:
- XPWWebServiceException: The XProtect Web Server returned a failed response.
- XPWException: userName argument was not supplied.
password argument was not supplied.
The method fails for any reason.
Returns:
An XPWLoginInfo class that contains Login details.
The ManagementServer/ServerCommandService.svc Login method is used to authenticate the user credentials.
This method can also be used to renew a token that was generated by a previous call to this method.
Sample Code
# our package imports.
from milestonexprotectrestpython.xprlogininfo import XPRLoginInfo
from milestonexprotectrestpython.xprrestservice import XPRRestService
# create XPRRestService instance and set server prefixes for our environment.
xrest:XPRRestService = XPRRestService()
xrest.ApiGatewayUrlPrefix = "https://myapigateway.example.com"
xrest.IsSslVerifyEnabled = False
# authenticate using xprotect basic auth credentials.
loginInfo:XPRLoginInfo = xrest.LoginBasicUser("xpsampleadmin", "MyPassword&1")
print("** Login Details:\n{0}\n".format(loginInfo))
Authenticates a user with the specified Windows User login account.
Arguments:
- username (str): Basic account type User Name to authenticate.
- password (str): Basic account type Password for the specified User Name to authenticate.
- currentToken (str): If renewing an existing login token, the value of a previously generated login token; otherwise, an empty string if this is a new Login or you don't wish to renew a token.
Raises:
- XPWWebServiceException: The XProtect Web Server returned a failed response.
- XPWException: userName argument was not supplied.
password argument was not supplied.
The method fails for any reason.
Returns:
An XPWLoginInfo class that contains Login details.
The ServerAPI/ServerCommandService.asmx Login method is used to authenticate the user credentials.
This method can also be used to renew a token that was generated by a previous call to this method.
Sample Code
# our package imports.
from milestonexprotectrestpython.xprlogininfo import XPRLoginInfo
from milestonexprotectrestpython.xprrestservice import XPRRestService
# create XPRRestService instance and set server prefixes for our environment.
xrest:XPRRestService = XPRRestService()
xrest.ApiGatewayUrlPrefix = "https://myapigateway.example.com"
xrest.IsSslVerifyEnabled = False
# authenticate using xprotect windows auth credentials.
loginInfo:XPRLoginInfo = xrest.LoginWindowsUser("MYDOMAIN\XProtectServiceAccount", "XPAService&1")
print("** Login Details:\n{0}\n".format(loginInfo))
Checks a dictionary for the specified outer key name, and returns a string array of values from the inner key name.
Arguments:
- arrayList (list[str]): String array to add the found strings to.
- oDict (dict): Dictionary to check for the specified key name.
- keyNameCollection (str): Key name to check for that contains a collection of nodes.
- keyNameInner (str): Inner Key name to check for that contains the strings to add.
Returns:
An array of string values from the inner key. An array will always be returned, even if it is empty.
This method is useful for parsing repeated occurances of single string values in a parent node. For example: