/* * Copyright (c) 2014 The CCP project authors. All Rights Reserved. * * Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license * that can be found in the LICENSE file in the root of the web site. * * http://www.114390.com * * An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */using System;using System.Collections.Generic;using System.IO;using System.Net;using System.Reflection;using System.Text;using System.Xml;namespace CCPRestSDK{ enum EBodyType:uint { EType_XML = 0, EType_JSON }; public class CCPRestSDK { private string m_restAddress = null; private string m_restPort = null; private string m_mainAccount = null; private string m_mainToken = null; private string m_subAccount = null; private string m_subToken = null; private string m_voipAccount = null; private string m_voipPwd = null; private string m_appId = null; private bool m_isWriteLog = false; private EBodyType m_bodyType = EBodyType.EType_XML; /// /// 服务器api版本 /// const string softVer = "2013-12-26"; /// /// 初始化函数 /// /// 服务器地址 /// 服务器端口 /// public bool init(string restAddress, string restPort) { this.m_restAddress = restAddress; this.m_restPort = restPort; if (m_restAddress == null || m_restAddress.Length < 0 || m_restPort == null || m_restPort.Length < 0 || Convert.ToInt32(m_restPort) < 0) return false; return true; } /// /// 设置主帐号信息 /// /// 主帐号 /// 主帐号令牌 public void setAccount(string accountSid, string accountToken) { this.m_mainAccount = accountSid; this.m_mainToken = accountToken; } /// /// 设置子帐号信息 /// /// 子帐号 /// 子帐号令牌 /// VoIP帐号 /// VoIP密码 public void setSubAccount(string subAccountSid, string subAccountToken, string voipAccount, string voipPassword) { this.m_subAccount = subAccountSid; this.m_subToken = subAccountToken; this.m_voipAccount = voipAccount; this.m_voipPwd = voipPassword; } /// /// 设置应用ID /// /// 应用ID public void setAppId(string appId) { this.m_appId = appId; } /// /// 日志开关 /// /// 日志开关 public void enabeLog(bool enable) { this.m_isWriteLog = enable; } /// /// 获取日志路径 /// /// 日志路径 public string GetLogPath() { string dllpath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase; dllpath = dllpath.Substring(8, dllpath.Length - 8); // 8是 file:// 的长度 return System.IO.Path.GetDirectoryName(dllpath)+"\\log.txt"; } /// /// 主帐号信息查询 /// /// /// 包体内容 public Dictionary QueryAccountInfo() { Dictionary initError = paramCheckRest(); if (initError != null) { return initError; } initError = paramCheckMainAccount(); if (initError != null) { return initError; } try { string date = DateTime.Now.ToString("yyyyMMddhhmmss"); // 构建URL内容 string sigstr = MD5Encrypt(m_mainAccount + m_mainToken + date); string uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/AccountInfo?sig={4}", m_restAddress, m_restPort, softVer, m_mainAccount, sigstr); Uri address = new Uri(uriStr); WriteLog("QueryAccountInfo url = "+uriStr); // 创建网络请求 HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; setCertificateValidationCallBack(); // 构建Head request.Method = "GET"; Encoding myEncoding = Encoding.GetEncoding("utf-8"); byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + date); string authStr = Convert.ToBase64String(myByte); request.Headers.Add("Authorization", authStr); if (m_bodyType == EBodyType.EType_XML) { request.Accept = "application/xml"; request.ContentType = "application/xml;charset=utf-8"; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); string responseStr = reader.ReadToEnd(); WriteLog("QueryAccountInfo responseBody = " + responseStr); if (responseStr != null && responseStr.Length > 0) { //Dictionary responseResult = new Dictionary { { "statusCode", "0" }, { "statusMsg", "成功" }, { "data", null } }; Dictionary responseResult = new Dictionary (); responseResult.Add("statusCode", "0"); responseResult.Add("statusMsg", "成功"); responseResult.Add("data", null); XmlDocument resultXml = new XmlDocument(); resultXml.LoadXml(responseStr); XmlNodeList nodeList = resultXml.SelectSingleNode("Response").ChildNodes; foreach (XmlNode item in nodeList) { if (item.Name == "statusCode") { responseResult["statusCode"] = item.InnerText; } else if (item.Name == "statusMsg") { responseResult["statusMsg"] = item.InnerText; } else if (item.Name == "Account") { Dictionary data = new Dictionary (); foreach (XmlNode subItem in item.ChildNodes) { data.Add(subItem.Name, subItem.InnerText); } //responseResult["data"] = new Dictionary { {item.Name,data}}; Dictionary data1 = new Dictionary (); data1.Add(item.Name, data); responseResult["data"] = data1; } } return responseResult; } //return new Dictionary { { "statusCode", 172002 }, { "statusMsg", "无返回" }, { "data", null } }; Dictionary data2 = new Dictionary (); data2.Add("statusCode", 172002); data2.Add("statusMsg", "无返回"); data2.Add("data", null); return data2; } } else { request.Accept = "application/json"; request.ContentType = "application/json;charset=utf-8"; using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); string responseStr = reader.ReadToEnd(); WriteLog("QueryAccountInfo responseBody = " + responseStr); if (responseStr != null && responseStr.Length > 0) { Dictionary responseResult = new Dictionary (); responseResult["resposeBody"] = responseStr; return responseResult; } //return new Dictionary { { "statusCode", 172002 }, { "statusMsg", "无返回" }, { "data", null } }; Dictionary data2 = new Dictionary (); data2.Add("statusCode", 172002); data2.Add("statusMsg", "无返回"); data2.Add("data", null); return data2; } } // 获取请求 } catch (Exception e) { throw e; } } /// /// 创建子帐号 /// /// 子帐号名称。可由英文字母和阿拉伯数字组成子帐号唯一名称,推荐使用电子邮箱地址 /// 参数不能为空 /// /// 包体内容 public Dictionary CreateSubAccount(string friendlyName) { Dictionary initError = paramCheckRest(); if (initError != null) { return initError; } initError = paramCheckMainAccount(); if (initError != null) { return initError; } initError = paramCheckAppId(); if (initError != null) { return initError; } if(friendlyName == null) throw new ArgumentNullException("friendlyName"); try { string date = DateTime.Now.ToString("yyyyMMddhhmmss"); // 构建URL内容 string sigstr = MD5Encrypt(m_mainAccount + m_mainToken + date); string uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/SubAccounts?sig={4}", m_restAddress, m_restPort, softVer, m_mainAccount, sigstr); Uri address = new Uri(uriStr); WriteLog("CreateSubAccount url = " +uriStr); // 创建网络请求 HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; setCertificateValidationCallBack(); // 构建Head request.Method = "POST"; Encoding myEncoding = Encoding.GetEncoding("utf-8"); byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + date); string authStr = Convert.ToBase64String(myByte); request.Headers.Add("Authorization", authStr); // 构建Body StringBuilder data = new StringBuilder(); if (m_bodyType == EBodyType.EType_XML) { request.Accept = "application/xml"; request.ContentType = "application/xml;charset=utf-8"; data.Append(" "); data.Append(" ").Append(m_appId).Append(" "); data.Append(" ").Append(friendlyName).Append(" "); data.Append(" "); } else { request.Accept = "application/json"; request.ContentType = "application/json;charset=utf-8"; data.Append("{ "); data.Append("\"appId\":\"").Append(m_appId).Append("\""); data.Append(",\"friendlyName\":\"").Append(friendlyName).Append("\""); data.Append("}"); } byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); WriteLog("CreateSubAccount requestBody = " +data.ToString()); // 开始请求 using (Stream postStream = request.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); } // 获取请求 using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); string responseStr = reader.ReadToEnd(); WriteLog("CreateSubAccount responseBody = " + responseStr); if (responseStr != null && responseStr.Length > 0) { //Dictionary responseResult = new Dictionary { { "statusCode", "0" }, { "statusMsg", "成功" }, { "data", null } }; Dictionary responseResult = new Dictionary (); responseResult.Add("statusCode", "0"); responseResult.Add("statusMsg", "成功"); responseResult.Add("data", null); if (m_bodyType == EBodyType.EType_XML) { XmlDocument resultXml = new XmlDocument(); resultXml.LoadXml(responseStr); XmlNodeList nodeList = resultXml.SelectSingleNode("Response").ChildNodes; foreach (XmlNode item in nodeList) { if (item.Name == "statusCode") { responseResult["statusCode"] = item.InnerText; } else if (item.Name == "statusMsg") { responseResult["statusMsg"] = item.InnerText; } else if (item.Name == "SubAccount") { Dictionary retData = new Dictionary (); foreach (XmlNode subItem in item.ChildNodes) { retData.Add(subItem.Name, subItem.InnerText); } //responseResult["data"] = new Dictionary { { item.Name, retData } }; Dictionary data1 = new Dictionary (); data1.Add(item.Name, retData); responseResult["data"] = data1; } } } else { responseResult.Clear(); responseResult["resposeBody"] = responseStr; } return responseResult; } //return new Dictionary { { "statusCode", 172002 }, { "statusMsg", "无返回" }, { "data", null } }; Dictionary data2 = new Dictionary (); data2.Add("statusCode", 172002); data2.Add("statusMsg", "无返回"); data2.Add("data", null); return data2; } } catch (Exception e) { throw e; } } /// /// 获取应用下子帐号 /// /// 开始的序号,默认从0开始 /// 一次查询的最大条数,最小是1条,最大是100条 /// 参数超出范围 /// /// public Dictionary GetSubAccounts(uint startNo, uint offset) { Dictionary initError = paramCheckRest(); if (initError != null) { return initError; } initError = paramCheckMainAccount(); if (initError != null) { return initError; } initError = paramCheckAppId(); if (initError != null) { return initError; } if (offset < 1 || offset > 100) { throw new ArgumentOutOfRangeException("offset超出范围"); } try { string date = DateTime.Now.ToString("yyyyMMddhhmmss"); // 构建URL内容 string sigstr = MD5Encrypt(m_mainAccount + m_mainToken + date); string uriStr = string.Format("https://{0}:{1}/{2}/Accounts/{3}/GetSubAccounts?sig={4}", m_restAddress, m_restPort, softVer, m_mainAccount, sigstr); Uri address = new Uri(uriStr); WriteLog("GetSubAccounts url = "+uriStr); // 创建网络请求 HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; setCertificateValidationCallBack(); // 构建Head request.Method = "POST"; Encoding myEncoding = Encoding.GetEncoding("utf-8"); byte[] myByte = myEncoding.GetBytes(m_mainAccount + ":" + date); string authStr = Convert.ToBase64String(myByte); request.Headers.Add("Authorization", authStr); // 构建Body StringBuilder data = new StringBuilder(); if (m_bodyType == EBodyType.EType_XML) { request.Accept = "application/xml"; request.ContentType = "application/xml;charset=utf-8"; data.Append(" "); data.Append(" ").Append(m_appId).Append(" "); data.Append(" ").Append(startNo).Append(" "); data.Append(" ").Append(offset).Append(" "); data.Append(" "); } else { request.Accept = "application/json"; request.ContentType = "application/json;charset=utf-8"; data.Append("{ "); data.Append("\"appId\":\"").Append(m_appId).Append("\""); data.Append(",\"startNo\":\"").Append(startNo).Append("\""); data.Append(",\"offset\":\"").Append(offset).Append("\""); data.Append("}"); } byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString()); WriteLog("GetSubAccounts requestBody = " + data.ToString()); // 开始请求 using (Stream postStream = request.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); } // 获取请求 using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { // Get the response stream StreamReader reader = new StreamReader(response.GetResponseStream()); string responseStr = reader.ReadToEnd(); WriteLog("GetSubAccounts responseBody = "+responseStr); if (responseStr != null && responseStr.Length > 0) { //Dictionary responseResult = new Dictionary { { "statusCode", "0" }, { "statusMsg", "成功" }, { "data", null } }; Dictionary responseResult = new Dictionary (); responseResult.Add("statusCode", "0"); responseResult.Add("statusMsg", "成功"); responseResult.Add("data", null); Dictionary retData = new Dictionary (); List