EncryptionSample.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. using System.Text;
  2. using Agora.Rtc;
  3. using Agora.Util;
  4. using UnityEngine;
  5. using UnityEngine.Serialization;
  6. using UnityEngine.UI;
  7. using Logger = Agora.Util.Logger;
  8. namespace Agora_RTC_Plugin.API_Example.Examples.Advanced.SetEncryption
  9. {
  10. public class EncryptionSample : MonoBehaviour
  11. {
  12. [FormerlySerializedAs("appIdInput")]
  13. [SerializeField]
  14. private AppIdInput _appIdInput;
  15. [Header("_____________Basic Configuration_____________")]
  16. [FormerlySerializedAs("APP_ID")]
  17. [SerializeField]
  18. private string _appID = "";
  19. [FormerlySerializedAs("TOKEN")]
  20. [SerializeField]
  21. private string _token = "";
  22. [FormerlySerializedAs("CHANNEL_NAME")]
  23. [SerializeField]
  24. private string _channelName = "";
  25. [SerializeField]
  26. public ENCRYPTION_MODE EncrytionMode = ENCRYPTION_MODE.AES_128_GCM2;
  27. private string secret = "Hello_Unity";
  28. public Text LogText;
  29. internal Logger Log;
  30. internal IRtcEngine RtcEngine;
  31. // Start is called before the first frame update
  32. private void Start()
  33. {
  34. LoadAssetData();
  35. if (CheckAppId())
  36. {
  37. InitRtcEngine();
  38. SetEncryption();
  39. JoinChannel();
  40. }
  41. }
  42. private void Update()
  43. {
  44. PermissionHelper.RequestMicrophontPermission();
  45. }
  46. private bool CheckAppId()
  47. {
  48. Log = new Logger(LogText);
  49. return Log.DebugAssert(_appID.Length > 10, "Please fill in your appId in API-Example/profile/appIdInput.asset");
  50. }
  51. //Show data in AgoraBasicProfile
  52. [ContextMenu("ShowAgoraBasicProfileData")]
  53. private void LoadAssetData()
  54. {
  55. if (_appIdInput == null) return;
  56. _appID = _appIdInput.appID;
  57. _token = _appIdInput.token;
  58. _channelName = _appIdInput.channelName;
  59. }
  60. private void InitRtcEngine()
  61. {
  62. RtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngine();
  63. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  64. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING,
  65. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_DEFAULT);
  66. RtcEngine.Initialize(context);
  67. RtcEngine.InitEventHandler(new UserEventHandler(this));
  68. }
  69. private byte[] GetEncryptionSaltFromServer()
  70. {
  71. return Encoding.UTF8.GetBytes("EncryptionKdfSaltInBase64Strings");
  72. }
  73. private void SetEncryption()
  74. {
  75. byte[] kdfSal = this.GetEncryptionSaltFromServer();
  76. var config = new EncryptionConfig
  77. {
  78. encryptionMode = EncrytionMode,
  79. encryptionKey = secret,
  80. encryptionKdfSalt = kdfSal
  81. };
  82. Log.UpdateLog(string.Format("encryption mode: {0} secret: {1}", EncrytionMode, secret));
  83. var nRet= RtcEngine.EnableEncryption(true, config);
  84. this.Log.UpdateLog("EnableEncryption: " + nRet);
  85. }
  86. private void JoinChannel()
  87. {
  88. RtcEngine.SetClientRole(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  89. RtcEngine.EnableAudio();
  90. RtcEngine.EnableVideo();
  91. RtcEngine.JoinChannel(_token, _channelName, "", 0);
  92. }
  93. private void OnLeaveBtnClick()
  94. {
  95. RtcEngine.LeaveChannel();
  96. }
  97. private void OnDestroy()
  98. {
  99. Debug.Log("OnDestroy");
  100. if (RtcEngine == null) return;
  101. RtcEngine.InitEventHandler(null);
  102. RtcEngine.LeaveChannel();
  103. RtcEngine.Dispose();
  104. }
  105. #region -- Video Render UI Logic ---
  106. internal static void MakeVideoView(uint uid, string channelId = "")
  107. {
  108. var go = GameObject.Find(uid.ToString());
  109. if (!ReferenceEquals(go, null))
  110. {
  111. return; // reuse
  112. }
  113. // create a GameObject and assign to this new user
  114. var videoSurface = MakeImageSurface(uid.ToString());
  115. if (ReferenceEquals(videoSurface, null)) return;
  116. // configure videoSurface
  117. if (uid == 0)
  118. {
  119. videoSurface.SetForUser(uid, channelId);
  120. }
  121. else
  122. {
  123. videoSurface.SetForUser(uid, channelId, VIDEO_SOURCE_TYPE.VIDEO_SOURCE_REMOTE);
  124. }
  125. videoSurface.OnTextureSizeModify += (int width, int height) =>
  126. {
  127. float scale = (float)height / (float)width;
  128. videoSurface.transform.localScale = new Vector3(-5, 5 * scale, 1);
  129. Debug.Log("OnTextureSizeModify: " + width + " " + height);
  130. };
  131. videoSurface.SetEnable(true);
  132. }
  133. // VIDEO TYPE 1: 3D Object
  134. private static VideoSurface MakePlaneSurface(string goName)
  135. {
  136. var go = GameObject.CreatePrimitive(PrimitiveType.Plane);
  137. if (go == null)
  138. {
  139. return null;
  140. }
  141. go.name = goName;
  142. // set up transform
  143. go.transform.Rotate(-90.0f, 0.0f, 0.0f);
  144. var yPos = Random.Range(3.0f, 5.0f);
  145. var xPos = Random.Range(-2.0f, 2.0f);
  146. go.transform.position = Vector3.zero;
  147. go.transform.localScale = new Vector3(0.25f, 0.5f, 0.5f);
  148. // configure videoSurface
  149. var videoSurface = go.AddComponent<VideoSurface>();
  150. return videoSurface;
  151. }
  152. // Video TYPE 2: RawImage
  153. private static VideoSurface MakeImageSurface(string goName)
  154. {
  155. GameObject go = new GameObject();
  156. if (go == null)
  157. {
  158. return null;
  159. }
  160. go.name = goName;
  161. // to be renderered onto
  162. go.AddComponent<RawImage>();
  163. // make the object draggable
  164. go.AddComponent<UIElementDrag>();
  165. var canvas = GameObject.Find("VideoCanvas");
  166. if (canvas != null)
  167. {
  168. go.transform.parent = canvas.transform;
  169. Debug.Log("add video view");
  170. }
  171. else
  172. {
  173. Debug.Log("Canvas is null video view");
  174. }
  175. // set up transform
  176. go.transform.Rotate(0f, 0.0f, 180.0f);
  177. go.transform.localPosition = Vector3.zero;
  178. go.transform.localScale = new Vector3(2f, 3f, 1f);
  179. // configure videoSurface
  180. var videoSurface = go.AddComponent<VideoSurface>();
  181. return videoSurface;
  182. }
  183. internal static void DestroyVideoView(uint uid)
  184. {
  185. var go = GameObject.Find(uid.ToString());
  186. if (!ReferenceEquals(go, null))
  187. {
  188. Destroy(go);
  189. }
  190. }
  191. #endregion
  192. internal string GetChannelName()
  193. {
  194. return _channelName;
  195. }
  196. }
  197. #region -- Agora Event ---
  198. internal class UserEventHandler : IRtcEngineEventHandler
  199. {
  200. private readonly EncryptionSample _encryptionSample;
  201. internal UserEventHandler(EncryptionSample encryptionSample)
  202. {
  203. _encryptionSample = encryptionSample;
  204. }
  205. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  206. {
  207. int build = 0;
  208. _encryptionSample.Log.UpdateLog(string.Format("sdk version: {0}",
  209. _encryptionSample.RtcEngine.GetVersion(ref build)));
  210. _encryptionSample.Log.UpdateLog(string.Format(
  211. "onJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}", connection.channelId,
  212. connection.localUid, elapsed));
  213. EncryptionSample.MakeVideoView(0);
  214. }
  215. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  216. {
  217. _encryptionSample.Log.UpdateLog("OnLeaveChannelSuccess");
  218. EncryptionSample.MakeVideoView(0);
  219. }
  220. public override void OnUserJoined(RtcConnection connection, uint uid, int elapsed)
  221. {
  222. _encryptionSample.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed));
  223. EncryptionSample.MakeVideoView(uid, _encryptionSample.GetChannelName());
  224. }
  225. public override void OnUserOffline(RtcConnection connection, uint uid, USER_OFFLINE_REASON_TYPE reason)
  226. {
  227. _encryptionSample.Log.UpdateLog(string.Format("OnUserOffLine uid: ${0}, reason: ${1}", uid,
  228. (int)reason));
  229. EncryptionSample.DestroyVideoView(uid);
  230. }
  231. public override void OnError(int error, string msg)
  232. {
  233. _encryptionSample.Log.UpdateLog(string.Format("OnSDKError error: {0}, msg: {1}", error, msg));
  234. }
  235. public override void OnConnectionLost(RtcConnection connection)
  236. {
  237. _encryptionSample.Log.UpdateLog(string.Format("OnConnectionLost "));
  238. }
  239. public override void OnEncryptionError(RtcConnection connection, ENCRYPTION_ERROR_TYPE errorType)
  240. {
  241. _encryptionSample.Log.UpdateLog("OnEncryptionError: " + errorType);
  242. }
  243. }
  244. #endregion
  245. }