import hashlib
import hmac
import time
import requests
import base64

# see accessmanagerapikey-config.xml
apikey = "9e9a4776f72e2d177492e7853a0b744a5c27e4e184cc436faca4885f38b87c42" # **/client/apikey
secret = "oma4gWkKB0SaI1yWogFs2Fest/pNlpWJE2dUNfGqOpc="                     # **/client/encodedSignatureKey
clientid = 'api-user'                                                       # **/client/clientId (is optional)

# see Cadenza Managment Center for a valid Repo ID
RepoID = "hK6HtUqLDbvz7rgMNxBk"

cadenzabaseurl ="http://localhost:8000"
basePath = "/cadenza"

# unix epochtime in millisecond
epochetime=int(time.time() * 1000)
signatureURL = basePath + "/public/adminapi/repositories/"+RepoID+"?requestTimestamp="+str(epochetime)
URL = cadenzabaseurl + signatureURL

# secret is base64 encoded hmac needs a bayte array
decodedSecret = base64.b64decode(secret)
hmacHash = hmac.new(decodedSecret, signatureURL.encode(), hashlib.sha256).digest()

# hash is a byte array, encode with base64
signature = base64.b64encode(hmacHash).decode()

# defining a params dict for the parameters to be sent to the API
headers = {'X-Api-Key': apikey, 'X-Client-Id': clientid, 'X-Request-Signature': signature,  'Accept': 'application/zip' }

output = "CadenzaRepo_"+RepoID+".zip"

# get request is needed
r = requests.get(URL, headers=headers)
with open(output, 'wb') as f:
    f.write(r.content)

print("RequestURL:          " + str(r.url))
print("SignaturURL:         " + signatureURL)
print("X-Request-Signature: " + signature)
print("Response Code:       " + str(r))

