ClientManager.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Threading.Tasks;
  6. using Vinno.IUS.Common.Log;
  7. using Vinno.IUS.Common.Network;
  8. using Vinno.IUS.Common.Network.Leaf;
  9. using Vinno.IUS.Common.Network.Tcp;
  10. using Vinno.IUS.Common.Network.Transfer;
  11. using Vinno.vCloud.Client.Proxy.Interfaces;
  12. using Vinno.vCloud.Common.Client.Managers.Interfaces;
  13. using Vinno.vCloud.Common.Client.Managers.vCloudClient;
  14. using Vinno.vCloud.Common.Storage;
  15. using Vinno.vCloud.Common.Storage.ObjectStorageInfo;
  16. using Vinno.vCloud.Protocol.Infrastructures;
  17. using Vinno.vCloud.Protocol.Initializers;
  18. using Vinno.vCloud.Protocol.Messages;
  19. using Vinno.vCloud.Protocol.Messages.Client.Account;
  20. using Vinno.vCloud.Protocol.Messages.Client.LiveTalking;
  21. using Vinno.vCloud.Protocol.Messages.Client.Login;
  22. using Vinno.vCloud.Protocol.Messages.Client.Storage;
  23. using Vinno.vCloud.Protocol.Messages.Live;
  24. using Vinno.vCloud.Protocol.Messages.Login;
  25. namespace Vinno.vCloud.Client.Proxy
  26. {
  27. public partial class ClientManager
  28. {
  29. private const int HeartRateTime = 1; //minute
  30. private ConnectionKeeper _connectionKeeper;
  31. private HeartRateKeeper _heartRateKeeper;
  32. private ITcpCreator _tcpCreator;
  33. private LoginSource _loginSource;
  34. private string _sessionId;
  35. private object _clientLoker = new object();
  36. private ClientLeaf _leaf;
  37. private string _password;
  38. private string _accountName;
  39. private string _accountId;
  40. private string _liveServiceUrl;
  41. private ClientAccountMessage _accountDataMessage;
  42. private string _currentUniqueCode = string.Empty;
  43. private string _serverAddress;
  44. private int _port;
  45. private string _clinetId;
  46. private string _openId;
  47. /// <summary>
  48. /// login account Id
  49. /// </summary>
  50. public string AccountId => _accountId;
  51. public string AccountName=> _accountName;
  52. /// <summary>
  53. /// Gets or set the leaf of this client manager.
  54. /// </summary>
  55. public ClientLeaf Leaf
  56. {
  57. get { return _leaf; }
  58. set
  59. {
  60. if (_leaf != value)
  61. {
  62. if (_leaf != null)
  63. {
  64. _heartRateKeeper?.Stop();
  65. if (_connectionKeeper != null)
  66. {
  67. _connectionKeeper.Offlined -= OnOfflined;
  68. _connectionKeeper.Stop();
  69. }
  70. _leaf.MessageArrived -= OnMessageArrived;
  71. _leaf.Close();
  72. }
  73. _leaf = value;
  74. if (_leaf != null)
  75. {
  76. _leaf.MessageArrived += OnMessageArrived;
  77. _connectionKeeper = new ConnectionKeeper(Leaf);
  78. _connectionKeeper.Offlined += OnOfflined;
  79. _connectionKeeper.Start();
  80. }
  81. }
  82. }
  83. }
  84. /// <summary>
  85. /// Network connection is offlined then relogining, trigger by connection keeper
  86. /// </summary>
  87. public event EventHandler AccountRelogining;
  88. /// <summary>
  89. /// The event that account relogin
  90. /// </summary>
  91. public event EventHandler AccountRelogin;
  92. /// <summary>
  93. /// The event befor connection replaced
  94. /// </summary>
  95. public event EventHandler ConnectionReplacing;
  96. /// <summary>
  97. /// The event connection replaced, it may account login in another client
  98. /// </summary>
  99. public event EventHandler ConnectionReplaced;
  100. /// <summary>
  101. /// The event account password changed in another client
  102. /// </summary>
  103. public event EventHandler<string> AccountPasswordChanged;
  104. /// <summary>
  105. /// execute when visitor relogin fail
  106. /// </summary>
  107. public event EventHandler<LoginStatus> VisitorReloginFail;
  108. /// <summary>
  109. /// execute when scan login success
  110. /// </summary>
  111. public event EventHandler<bool> ScanLoginState;
  112. /// <summary>
  113. /// Flag indicates client is connected to vCloud server
  114. /// </summary>
  115. public bool IsConnected => Leaf != null && Leaf.Online;
  116. public event EventHandler<bool> ConnectedChanged;
  117. /// <summary>
  118. /// Get the upgrader which providers the upgrade functions.
  119. /// </summary>
  120. public IUpgrader Upgrader { get; set; }
  121. public IRemedical Remedical { get; }
  122. public IRemoteDiagnosis RemoteDiagnosis { get; }
  123. /// <summary>
  124. /// This property provide all community api communicate to server.
  125. /// </summary>
  126. public ICommunity Community { get; }
  127. /// <summary>
  128. /// Provide all chat message api communicate to server.
  129. /// </summary>
  130. public IMessageCenter MessageCenter { get; }
  131. /// <summary>
  132. /// Provide all account api communicate to server.
  133. /// </summary>
  134. public IAccount Account { get; }
  135. /// <summary>
  136. /// provide all report api
  137. /// </summary>
  138. public IReport Report { get; }
  139. /// <summary>
  140. /// provide all Share api
  141. /// </summary>
  142. public IShare Share { get; }
  143. /// <summary>
  144. /// provide all live api
  145. /// </summary>
  146. public ILive Live { get; }
  147. /// <summary>
  148. /// WorkOrder System
  149. /// </summary>
  150. public IWorkOrderSystem WorkOrderSystem { get; }
  151. /// <summary>
  152. /// provide all training api
  153. /// </summary>
  154. public ITraining Training { get; }
  155. public IDataStatistics DataStatistics { get; }
  156. /// <summary>
  157. /// Assign terminal
  158. /// </summary>
  159. public IAssignTerminal AssignTerminal { get; }
  160. public ILiveTalking LiveTalking { get; }
  161. public IAfterSales AfterSales { get; }
  162. public ICarotid Carotid { get; }
  163. /// <summary>
  164. /// provide all teaching api
  165. /// </summary>
  166. public ITeaching Teaching { get; }
  167. /// <summary>
  168. /// Provide all AI diagnosis requests.
  169. /// </summary>
  170. public IAIDiagnosis AIDiagnosis { get; }
  171. public IFrontPage FrontPage { get; }
  172. public ILiveWatcher LiveWatcher { get; private set; }
  173. public event EventHandler<Message> MessageArrived;
  174. public ClientManager(string hostUrl)
  175. {
  176. var address = hostUrl.Split(':');
  177. _serverAddress = address[0];
  178. _port = int.Parse(address[1]);
  179. _tcpCreator = new TcpCreator(_serverAddress, _port);
  180. Leaf = new ClientLeaf(new LeafIdContext(), LeafMode.Dual, _tcpCreator);
  181. Leaf.RegisterSetAccountDataMessageFunc(SetAccountDataToMessage);
  182. UploadHelper.GetAuthorization = GetAuthentication;
  183. }
  184. private void OnOfflined(object sender, EventArgs eventArgs)
  185. {
  186. lock (_clientLoker)
  187. {
  188. try
  189. {
  190. if (Leaf == null) //Account had log off, do not need to reconnect
  191. {
  192. return;
  193. }
  194. Logger.WriteLineInfo("OnOfflined Enter");
  195. _heartRateKeeper?.Stop();
  196. _heartRateKeeper = null;
  197. OnAccountRelogining();
  198. TryResetClientLeaf();
  199. if (Leaf.Online)
  200. {
  201. if (LoginByOpenId(_openId, _accountName,_password) == LoginStatus.Success)
  202. {
  203. OnAccountRelogin();
  204. }
  205. }
  206. }
  207. catch (Exception e)
  208. {
  209. Logger.WriteLineError($"OnOfflined{e}");
  210. }
  211. }
  212. }
  213. public event EventHandler LoginChanged;
  214. private void OnMessageArrived(object sender, Message e)
  215. {
  216. MessageArrived?.Invoke(this, e);
  217. }
  218. public void ResetClientLeafWithLock()
  219. {
  220. lock (_clientLoker)
  221. {
  222. TryResetClientLeaf();
  223. }
  224. }
  225. /// <summary>
  226. /// Try set ClientLeaf if is online
  227. /// </summary>
  228. private void TryResetClientLeaf()
  229. {
  230. _tcpCreator = new TcpCreator(_serverAddress, _port);
  231. if (!_tcpCreator.HasValidIpAddress)
  232. {
  233. return;
  234. }
  235. var clientLeaf = new ClientLeaf(new LeafIdContext(), LeafMode.Dual, _tcpCreator);
  236. if (clientLeaf.Online)
  237. {
  238. Leaf = clientLeaf;
  239. Leaf.RegisterSetAccountDataMessageFunc(SetAccountDataToMessage);
  240. }
  241. else
  242. {
  243. clientLeaf.Close();
  244. }
  245. Logger.WriteLineInfo($"TryResetClientLeaf- new ClientLeaf end");
  246. }
  247. /// <summary>
  248. /// Login to vCloud server
  249. /// </summary>
  250. /// <param name="accountName">Account name (Unique)</param>
  251. /// <param name="password">Password(encrypted) </param>
  252. /// <param name="loginSource">Login Source</param>
  253. /// <returns></returns>
  254. public LoginStatus Login(string accountName, string password, LoginSource loginSource, string clientId, bool isOffine = false)
  255. {
  256. lock (_clientLoker)
  257. {
  258. _loginSource = loginSource;
  259. _accountName = accountName;
  260. _password = password;
  261. _clinetId = clientId;
  262. if (IsConnected)
  263. {
  264. var loginRequest = new ClientLoginRequest2
  265. {
  266. Name = accountName,
  267. Password = password,
  268. Source = loginSource,
  269. ClientId = clientId,
  270. ClientVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(),
  271. Force = true
  272. };
  273. try
  274. {
  275. var result = Leaf.Send(loginRequest);
  276. var loginResult = LoginResult2.Convert(result);
  277. if (loginResult != null)
  278. {
  279. _sessionId = loginResult.AccountSessionId;
  280. _accountId = loginResult.AccountId;
  281. var status = loginResult.Status;
  282. if (status == LoginStatus.Success)
  283. {
  284. Logger.WriteLineInfo($"LoginRequest Success - account:{accountName}");
  285. if (Leaf.Mode == LeafMode.Dual)
  286. {
  287. _heartRateKeeper = new HeartRateKeeper(_sessionId, Leaf, HeartRateTime);
  288. _heartRateKeeper.Start();
  289. }
  290. }
  291. return loginResult.Status;
  292. }
  293. }
  294. catch (ConnectionTimeoutException)
  295. {
  296. return LoginStatus.ConnectionTmeout;
  297. }
  298. catch (NotConnectedException)
  299. {
  300. return LoginStatus.ConnectServerFailed;
  301. }
  302. catch (Exception e)
  303. {
  304. Logger.WriteLineError($"Login ex:{e}");
  305. }
  306. }
  307. ConnectedChanged?.Invoke(this, false);
  308. return LoginStatus.Unknown;
  309. }
  310. }
  311. public LoginStatus LoginByOpenId(string openId, string username="", string password = "" )
  312. {
  313. lock (_clientLoker)
  314. {
  315. try
  316. {
  317. _openId = openId;
  318. _loginSource = LoginSource.ClientProxy;
  319. if (!string.IsNullOrEmpty(username))
  320. {
  321. _accountName = username;
  322. }
  323. if (!string.IsNullOrEmpty(password))
  324. {
  325. _password = password;
  326. }
  327. if (string.IsNullOrEmpty(_clinetId))
  328. {
  329. _clinetId = Guid.NewGuid().ToString();
  330. }
  331. if (IsConnected)
  332. {
  333. using (var request = MessagePool.GetMessage<LoginByOpenIdRequest>())
  334. {
  335. request.OpenId = openId;
  336. request.Source = _loginSource;
  337. request.ClientId = _clinetId;
  338. request.ClientVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
  339. request.Name = username;
  340. request.Password = password;
  341. request.Type = LoginType.User;
  342. var result = Leaf.Send(request);
  343. var loginResult = LoginResult2.Convert(result);
  344. if (loginResult != null)
  345. {
  346. _sessionId = loginResult.AccountSessionId;
  347. _accountId = loginResult.AccountId;
  348. var status = loginResult.Status;
  349. if (status == LoginStatus.Success)
  350. {
  351. Logger.WriteLineInfo($"LoginRequest Success -openId:{openId} , account:{_accountId}");
  352. if (Leaf.Mode == LeafMode.Dual)
  353. {
  354. _heartRateKeeper = new HeartRateKeeper(_sessionId, Leaf, HeartRateTime);
  355. _heartRateKeeper.Start();
  356. }
  357. }
  358. return loginResult.Status;
  359. }
  360. }
  361. }
  362. }
  363. catch (ConnectionTimeoutException)
  364. {
  365. return LoginStatus.ConnectionTmeout;
  366. }
  367. catch (NotConnectedException)
  368. {
  369. return LoginStatus.ConnectServerFailed;
  370. }
  371. catch (Exception e)
  372. {
  373. Logger.WriteLineError($"Login ex:{e}");
  374. }
  375. ConnectedChanged?.Invoke(this, false);
  376. return LoginStatus.Unknown;
  377. }
  378. }
  379. internal Task<Message> SendAsync(Message request)
  380. {
  381. return Leaf.SendAsync(request);
  382. }
  383. /// <summary>
  384. /// Logout from vCloud server async method
  385. /// </summary>
  386. /// <returns>Logoff status</returns>
  387. public async Task<LogoffStatus> LogoutAsync()
  388. {
  389. LogoffStatus logoffStatus = await Task.Run(() =>
  390. {
  391. lock (_clientLoker)
  392. {
  393. try
  394. {
  395. var logoffRequest = new ClientLogoffRequest
  396. {
  397. Name = _accountName,
  398. Password = _password,
  399. Source = _loginSource
  400. };
  401. var result = Leaf.Send(logoffRequest);
  402. LogoffResult logoffResult = LogoffResult.Convert(result);
  403. if (logoffResult != null)
  404. {
  405. return logoffResult.Status;
  406. }
  407. }
  408. catch (Exception exception)
  409. {
  410. Logger.WriteLineError($"LogoutAsync ex {exception}");
  411. }
  412. finally
  413. {
  414. try
  415. {
  416. Leaf = null;
  417. }
  418. catch (Exception ex)
  419. {
  420. Logger.WriteLineError($"KeepConnection failed, ex: {ex}");
  421. }
  422. }
  423. return LogoffStatus.Unknown;
  424. }
  425. });
  426. return logoffStatus;
  427. }
  428. public void Dispose()
  429. {
  430. lock (_clientLoker)
  431. {
  432. Leaf = null;
  433. }
  434. }
  435. protected virtual void OnAccountRelogining()
  436. {
  437. AccountRelogining?.Invoke(this, EventArgs.Empty);
  438. }
  439. protected virtual void OnAccountRelogin()
  440. {
  441. AccountRelogin?.Invoke(this, EventArgs.Empty);
  442. }
  443. public void StartBackgroundKeeper()
  444. {
  445. _connectionKeeper?.Stop();
  446. _heartRateKeeper?.Stop();
  447. _connectionKeeper?.Start();
  448. _heartRateKeeper?.Start();
  449. }
  450. private Message SetAccountDataToMessage(Message message)
  451. {
  452. if (message is ClientRequestMessage clientRequestMessage)
  453. {
  454. if (clientRequestMessage != null)
  455. {
  456. clientRequestMessage.AccountData = GetAccountDataMessage() as ClientAccountMessage;
  457. }
  458. }
  459. else if (message is DictionaryMessage dictionaryMessage)
  460. {
  461. var accountMessage = GetAccountDataMessage() as ClientAccountMessage;
  462. if (accountMessage != null && dictionaryMessage != null && string.IsNullOrWhiteSpace(dictionaryMessage.GetAccountId()))
  463. {
  464. dictionaryMessage.SetAccountBaseId(accountMessage.AccountId);
  465. var accountIdValue = dictionaryMessage.GetAccountId();
  466. }
  467. }
  468. return message;
  469. }
  470. private Message GetAccountDataMessage()
  471. {
  472. var accountData = new ClientAccountMessage
  473. {
  474. AccountId = _accountId ?? string.Empty,
  475. AccountName = _accountName ?? string.Empty,
  476. SessionId = _sessionId ?? string.Empty,
  477. Source = _loginSource
  478. };
  479. return accountData;
  480. }
  481. private string GetAuthentication(string fileName)
  482. {
  483. try
  484. {
  485. var authorization = string.Empty;
  486. var getAuthorizationRequest = new GetAuthorizationRequest();
  487. getAuthorizationRequest.FileName = fileName;
  488. var storageResult = Leaf.Send(getAuthorizationRequest);
  489. var getAuthorizationResult = GetAuthorizationResult.Convert(storageResult);
  490. if (getAuthorizationResult != null)
  491. {
  492. authorization = getAuthorizationResult.Authorization;
  493. }
  494. return authorization;
  495. }
  496. catch (Exception e)
  497. {
  498. throw new Exception("get authentication form server error");
  499. }
  500. }
  501. public string GetLiveServiceUrl()
  502. {
  503. if (string.IsNullOrEmpty(_liveServiceUrl))
  504. {
  505. using (var request = MessagePool.GetMessage<GetLiveServiceUrlRequest>())
  506. {
  507. var result = Leaf.Send(request);
  508. if (result != null)
  509. {
  510. var resultMessage = GetLiveServiceUrlResult.Convert(result);
  511. if (resultMessage != null)
  512. {
  513. _liveServiceUrl = resultMessage.Url;
  514. }
  515. }
  516. }
  517. }
  518. return _liveServiceUrl;
  519. }
  520. }
  521. }