阿里云实时音视频

实时音视频为客户端创建令牌
from aliyunsdkcore.client import AcsClient
from aliyunsdkrtc.request.v20180111 import CreateChannelRequest
from aliyunsdkcore.acs_exception.exceptions import ServerException
import aliyunsdkcore.profile.region_provider as rtc_user_config
import aliyunsdkcore.request as rtc_request
import aliyunsdkcore.http.protocol_type as rtc_protocol_type
import json, uuid


# 频道认证
class ChannelAuth:
    def __init__(self):
        self.app_id = None
        self.channel_id = None
        self.nonce = None
        self.timestamp = None
        self.channel_key = None
        self.recovered = None
        self.request_id = None


# 恢复错误
def recover_for_error(ex, app_id, channel_id):
    fatal = False
    request_id = ""
    if isinstance(ex, ServerException):
        request_id = ex.get_request_id()
        code = ex.get_error_code()
        if code == "IllegalOperationApp":
            fatal = True
        elif code.startswith("InvalidAccessKeyId"):
            fatal = True
        elif code == "SignatureDoesNotMatch":
            fatal = True
    if fatal:
        raise ex
    recovered = "RCV-%s" % str(uuid.uuid4())
    print("Recover from %s, recovered=%s" % (ex, recovered))
    auth = ChannelAuth()
    auth.app_id = app_id
    auth.channel_id = channel_id
    auth.nonce = recovered
    auth.timestamp = 0
    auth.channel_key = recovered
    auth.request_id = request_id
    auth.recovered = True
    return auth


# 创建频道
def create_channel(app_id, channel_id,
                   access_key_id, access_key_secret, region_id, endpoint
                   ):
    try:
        client = AcsClient(access_key_id, access_key_secret, region_id)
        request = CreateChannelRequest.CreateChannelRequest()
        request.set_AppId(app_id)
        request.set_ChannelId(channel_id)

        # Use HTTP, x3 times faster than HTTPS.
        rtc_request.set_default_protocol_type(rtc_protocol_type.HTTP)

        response = client.do_action_with_exception(request)
        obj = json.loads(response)

        auth = ChannelAuth()
        auth.app_id = app_id
        auth.channel_id = channel_id
        auth.nonce = obj['Nonce']
        auth.timestamp = obj['Timestamp']
        auth.channel_key = obj['ChannelKey']
        auth.request_id = obj['RequestId']
        auth.recovered = False
        return auth
    except Exception as ex:
        return recover_for_error(ex, app_id, channel_id)


region_id = "cn-hangzhou"  # 地域
endpoint = "rtc.aliyuncs.com"  # 节点

app_id = 'sj17fi'
channel_id = str(uuid.uuid4())
access_key_id = 'LTAIT0dog7'
access_key_secret = '8LOt6GqvvvvvvvPdvPcBXl'

auth = create_channel(app_id, channel_id,
                      access_key_id, access_key_secret, region_id, endpoint
                      )

# print(r1)
# print(auth.channel_key)
# print(auth.nonce)
# print(auth.timestamp)

# 为客户端创建令牌
import uuid, hashlib


def create_user_id():
    return str(uuid.uuid4())


def create_token(channel_id, channel_key, app_id, user_id, nonce, timestamp):
    channel_id = channel_id.encode('utf-8')
    channel_key = channel_key.encode('utf-8')
    app_id = app_id.encode('utf-8')
    user_id = user_id.encode('utf-8')
    nonce = nonce.encode('utf-8')
    timestamp = str(timestamp).encode('utf-8')

    h = hashlib.sha256()
    h.update(channel_id)
    h.update(channel_key)
    h.update(app_id)
    h.update(user_id)
    h.update(nonce)
    h.update(timestamp)
    token = h.hexdigest()
    return token


userid = create_user_id()
token = create_token(channel_id, auth.channel_key, app_id,
                     userid, auth.nonce, auth.timestamp)

channels = {}

channels['AppID'] = app_id
channels['channel_id'] = channel_id
channels['userid'] = userid
channels['Nonce'] = auth.nonce
channels['Timestamp'] = auth.timestamp
channels['Token'] = channel_id
channels['GSLB'] = 'https://rgslb.rtc.aliyuncs.com'

print(channels)

# { # 'AppID': 'sj1fu7fi', 'channel_id': '02da1070-ec2a-4ebd-829f-4653e385b4a2', # 'userid': '9072b3d7-e954-4fd4-b807-aa60bf1d83c3', 'Nonce': '844bba6b89b5f9956f6a2a6fc33efde8', 'Timestamp': 1555379321, # 'Token': '02da1070-ec2a-4ebd-829f-4653e385b4a2', 'GSLB': 'https://rgslb.rtc.aliyuncs.com' # }

 














 

posted @ 2019-10-16 13:39  虫洞小鳗鱼  阅读(1132)  评论(0编辑  收藏  举报