#!/usr/bin/env python3  
# -*- coding: utf-8 -*-  
"""
@Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
@AUTHOR: ASJRD018
@NAME: Ansjer
@software: PyCharm
@DATE: 2018/5/31 11:19
@Version: python3.6
@MODIFY DECORD:ansjer dev
@file: CloudfrontSignUrl.py
@Contact: chanjunkai@163.com
"""
from Ansjer.config import *
import datetime
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding
from botocore.signers import CloudFrontSigner


def rsa_signer(message):
    with open(os.path.join(BASE_DIR,'Ansjer/file/pk-APKAINI6BNPKV54NHH7Q.pem'), 'rb') as key_file:
        private_key = serialization.load_pem_private_key(
            key_file.read(),
            password=None,
            backend=default_backend()
        )
    signer = private_key.signer(padding.PKCS1v15(), hashes.SHA1())
    signer.update(message)
    return signer.finalize()


def CloudfrontSignUrl(url):
    key_id = 'APKAINI6BNPKV54NHH7Q'
    # url = 'http://d3om3d8c0l14oc.cloudfront.net/vod/2N1K3LE78TYJ38CE111A_99/1234.ts'
    expire_date = datetime.datetime.now() + datetime.timedelta(days=10)
    print(expire_date)
    cloudfront_signer = CloudFrontSigner(key_id, rsa_signer)
    signed_url = cloudfront_signer.generate_presigned_url(
        url, date_less_than=expire_date)
    return signed_url
