#!/usr/bin/env python3

# © Copyright 2000-2026 Elecard: Video Compression Guru. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# The initial release of this source code was created by Amazon.com, Inc. or its affiliates on 2010-2019.
# Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.

# Elecard Boro Solution
# API request signing example

# See: https://boro-vod.elecard.com/docs/en/boro-solution-userguide/chapter.ControlAPI/Signing.Requests.html
# This version makes a POST request and passes request parameters
# in the body (payload) of the request. Auth information is passed in
# the Authorization header.

import base64
import hashlib
import hmac
import json
import os
import sys
import requests  # pip install requests

# To get a date in RFC 1123 Date Representation
from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime

# ************* REQUEST VALUES *************
http_method = 'POST'
content_type = 'application/json'
request_host = '172.16.1.41'
request_path = '/ctrl_api/v1/json'

user_id: int = 1
project_id: int = 74

# "AppList" request body passed in a JSON block.
body = {
    "user_id": user_id,
    "methods": [
        {
            "method": "AppList",
            "params": {
                "project_id": project_id,
                "app_status": "active"
            }
        }
    ]
}

request_parameters = json.dumps(body)


# Best practice is NOT to embed credentials in a code.
# Get API key value from an environment variable
secret_key = os.environ.get('SECRET_ACCESS_KEY')
if secret_key is None:
    print('No API key is available.')
    sys.exit()


# ************* CREATE THE STRING TO SIGN *************
# Create a date in RFC 1123 Date Representation ('Fri, 05 Aug 2022 03:09:30 GMT') format for headers and the credential string
now = datetime.now()
timestamp = format_date_time(mktime(now.timetuple()))

# Calculate payload (body of the request) hash.
# X-Authorization-Content-SHA256 header is the Base64-encoded SHA-256 hash value used to generate the signature base string.
# This header should be provided by the client, to ensure the request body it sent was not tampered with on its way to the server.
payload_hash = hashlib.sha256(request_parameters.encode('utf-8')).digest()
payload_hash_base64 = base64.b64encode(payload_hash)
x_authorization_content_sha256 = payload_hash_base64.decode('utf-8')

# A canonical string is created using your HTTP headers containing the content-type,
# X-Authorization-Content-SHA256, request path and the date/time stamp.
# This string is then used to create the signature.
canonical_string = http_method + ',' + content_type + ',' + x_authorization_content_sha256 + ',' + request_path + ',' + timestamp


# ************* CALCULATE THE SIGNATURE *************
# Calculate the signature which is a Base64 encoded SHA256 HMAC, using the client's Base64 encoded private API key.
signature_hash = hmac.new(base64.b64decode(secret_key), canonical_string.encode('utf-8'), hashlib.sha256).digest()
signature_hash_base64 = base64.b64encode(signature_hash)
signature = signature_hash_base64.decode('utf-8')


# ************* ADD SIGNING INFORMATION TO THE REQUEST *************
# Put the signature to the Authorization HTTP header in the form: Authorization = APIAuth-HMAC-SHA256 "user_id:signature"
authorization_header = 'APIAuth-HMAC-SHA256 ' + str(user_id) + ':' + signature

# Prepare the necessary headers to be passed in the HTTP request. Order here is not significant.
headers = {'Content-Type': content_type,
           'Date': timestamp,
           'X-Authorization-Content-SHA256': x_authorization_content_sha256,
           'Authorization': authorization_header}


# ************* SEND THE REQUEST *************
request_uri = 'http://' + request_host + request_path

print('\nBEGIN REQUEST:')
print('Request URL = ' + request_uri)
print('Request body = ' + request_parameters)

r = requests.post(request_uri, data=request_parameters, headers=headers)

print('\nRESPONSE:')
print('Response code: %d\n' % r.status_code)
print(r.json())
