ConnectService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using JsonRpcLite.Services;
  6. using WingInterfaceLibrary.DB.Request;
  7. using WingInterfaceLibrary.DTO.Device;
  8. using WingInterfaceLibrary.DTO.Organization;
  9. using WingInterfaceLibrary.Enum;
  10. using WingInterfaceLibrary.Interface;
  11. using WingInterfaceLibrary.Request;
  12. using WingInterfaceLibrary.Request.Authentication;
  13. using WingInterfaceLibrary.Request.Device;
  14. using WingInterfaceLibrary.Result.Device;
  15. using WingServerCommon.Log;
  16. using WingServerCommon.Mapper;
  17. using WingServerCommon.Service;
  18. using WingServerCommon.Config;
  19. namespace WingDeviceService.Service
  20. {
  21. /// <summary>
  22. /// 鉴权服务
  23. /// </summary>
  24. public partial class DeviceService : JsonRpcService, IConnectService
  25. {
  26. private readonly string _sourceUrl = "cloud.xinglinghui.com";
  27. private readonly object _createShortCodeLocker = new object();
  28. /// <summary>设备连接云服务</summary>
  29. /// <param name="request">请求对象</param>
  30. /// <returns>授权响应</returns>
  31. /// <remarks>POST</remarks>
  32. public async Task<ConnectResult> ConnectAsync(ConnectRequest request)
  33. {
  34. try
  35. {
  36. #region Params Check
  37. if (string.IsNullOrWhiteSpace(request.DeviceUniqueCode))
  38. {
  39. ThrowCustomerException(CustomerRpcCode.DeviceUniqueCodeEmpty, "DeviceUniqueCode empty error");
  40. }
  41. if (string.IsNullOrWhiteSpace(request.DeviceModel))
  42. {
  43. ThrowCustomerException(CustomerRpcCode.DeviceModelEmpty, "DeviceModel empty error");
  44. }
  45. if (string.IsNullOrWhiteSpace(request.DeviceType))
  46. {
  47. ThrowCustomerException(CustomerRpcCode.DeviceTypeEmpty, "DeviceType empty error");
  48. }
  49. if (string.IsNullOrWhiteSpace(request.SoftwareVersion))
  50. {
  51. ThrowCustomerException(CustomerRpcCode.SoftwareVersionEmpty, "SoftwareVersion empty error");
  52. }
  53. if (string.IsNullOrWhiteSpace(request.SystemVersion))
  54. {
  55. ThrowCustomerException(CustomerRpcCode.SystemVersionEmpty, "SystemVersion empty error");
  56. }
  57. if (string.IsNullOrWhiteSpace(request.CPUModel))
  58. {
  59. ThrowCustomerException(CustomerRpcCode.CPUModelEmpty, "CPUModel empty error");
  60. }
  61. if (string.IsNullOrWhiteSpace(request.SystemLanguage))
  62. {
  63. ThrowCustomerException(CustomerRpcCode.SystemVersionEmpty, "SystemLanguage empty error");
  64. }
  65. #endregion
  66. var deviceDto = await _deviceInfoDBServiceProxy.FindDeviceInfoBySerialNumberAsync(request.DeviceUniqueCode);
  67. if (deviceDto == null)
  68. {
  69. deviceDto = new DeviceInfoDTO()
  70. {
  71. SerialNumber = request.DeviceUniqueCode,
  72. Name = request.Name,
  73. Password = request.Password,
  74. Description = request.Description,
  75. OrganizationCode = request.OrganizationCode,
  76. DeviceModel = request.DeviceModel,
  77. DeviceType = request.DeviceType,
  78. DeviceSoftwareVersion = request.SoftwareVersion,
  79. SystemVersion = request.SystemVersion,
  80. CPUModel = request.CPUModel,
  81. SystemLanguage = request.SystemLanguage,
  82. IsEncryptedShow = true
  83. };
  84. var shortCode = deviceDto.ShortCode;
  85. for (var i = 0; i < 5; i++)
  86. {
  87. shortCode = GenerateShortCode();
  88. if (!string.IsNullOrWhiteSpace(shortCode))
  89. {
  90. var device = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(shortCode);
  91. if (device == null || string.IsNullOrWhiteSpace(device.DeviceCode))
  92. {
  93. break;
  94. }
  95. }
  96. shortCode = string.Empty;
  97. }
  98. deviceDto.ShortCode = shortCode;
  99. deviceDto.DeviceCode = await _deviceInfoDBServiceProxy.InsertDeviceInfoAsync(new WingInterfaceLibrary.DB.Request.CreateDeviceInfoDBRequest
  100. {
  101. Data = deviceDto
  102. });
  103. //创建虚拟机构
  104. var inventedOrgCode = "invented_" + shortCode;
  105. var orgData = new TableDataItem<OrganizationDTO>
  106. {
  107. Data = new OrganizationDTO
  108. {
  109. OrganizationCode = inventedOrgCode,
  110. RootCode = inventedOrgCode,
  111. OrganizationName = shortCode,
  112. OrganizationType = OrganizationTypeEnum.Corporation,
  113. State = OrganizationStateEnum.Audited,
  114. RegionCode = "1000000",
  115. Isinvented = true
  116. },
  117. PlatformDatas = new Dictionary<string, string>(),
  118. ExtensionData = string.Empty,
  119. };
  120. await _organizationDBService.CreateOrganizationsAsync(new CreateOrganizationsDBRequest { Infos = new List<TableDataItem<OrganizationDTO>> { orgData } });
  121. }
  122. else
  123. {
  124. deviceDto.DeviceModel = request.DeviceModel;
  125. deviceDto.DeviceType = request.DeviceType;
  126. deviceDto.DeviceSoftwareVersion = request.SoftwareVersion;
  127. deviceDto.SystemVersion = request.SystemVersion;
  128. deviceDto.CPUModel = request.CPUModel;
  129. // deviceDto.Description = request.Description;
  130. // deviceDto.Name = request.Name;
  131. // deviceDto.OrganizationCode = request.OrganizationCode;
  132. deviceDto.SystemLanguage = request.SystemLanguage;
  133. await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDto.DeviceCode, deviceDto, string.Empty, true);
  134. }
  135. var deviceName = deviceDto.Name;
  136. if (!string.IsNullOrWhiteSpace(deviceName))
  137. {
  138. deviceName = deviceDto.ShortCode;
  139. }
  140. var applyRequest = new ApplyTokenRequest(AccountType.US, deviceName, request.Platform, request.LoginSource, deviceDto.DeviceCode, ConfigurationManager.Host, 0);
  141. var tokenInfo = await _authenticationService.ApplyTokenAsync(applyRequest);
  142. if (!string.IsNullOrWhiteSpace(tokenInfo.Code))
  143. {
  144. _deviceHeartRateManager.AddOrUpdate(tokenInfo.Code);
  145. }
  146. return new ConnectResult
  147. {
  148. Token = tokenInfo.Code,
  149. UniqueCode = deviceDto.ShortCode
  150. };
  151. }
  152. catch (Exception ex)
  153. {
  154. Logger.WriteLineWarn($"device connect server failed, err:{ex}");
  155. throw;
  156. }
  157. }
  158. /// <summary>查询当前设备信息</summary>
  159. /// <param name="request">请求对象</param>
  160. /// <returns>设备信息</returns>
  161. /// <remarks>POST</remarks>
  162. public async Task<CacheDeviceDTO> GetDeviceByTokenAsync(TokenRequest request)
  163. {
  164. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  165. var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  166. var cacheDeviceInfo = deviceDTO.MappingTo<CacheDeviceDTO>();
  167. cacheDeviceInfo.IsOnline = await GetDeviceOnlineState(deviceCode);
  168. return cacheDeviceInfo;
  169. }
  170. /// <summary>设备与云服务断开连接</summary>
  171. /// <param name="request">请求对象</param>
  172. /// <returns>是否成功</returns>
  173. /// <value>true</value>
  174. public async Task<bool> DisConnectAsync(TokenRequest request)
  175. {
  176. try
  177. {
  178. await _authenticationService.LogOffAsync(request);
  179. return true;
  180. }
  181. catch (Exception ex)
  182. {
  183. Logger.WriteLineWarn($"device disconnect failed, ex:{ex}");
  184. throw;
  185. }
  186. }
  187. /// <summary>获取设备在线状态</summary>
  188. /// <param name="deviceCode"></param>
  189. /// <returns></returns>
  190. private async Task<bool> GetDeviceOnlineState(string deviceCode)
  191. {
  192. var tokenList = await _authenticationService.GetTokensWithClientIdAsync(new GetTokensWithClientIdRequest { ClientId = deviceCode });
  193. return tokenList.FirstOrDefault()?.IsOnline ?? false;
  194. }
  195. /// <summary>生成唯一 shortCode</summary>
  196. /// <returns></returns>
  197. private string GenerateShortCode()
  198. {
  199. try
  200. {
  201. lock (_createShortCodeLocker)
  202. {
  203. var uniqueId = new byte[6];
  204. var rand = new Random((int)(DateTime.Now.Ticks % 1000000));
  205. for (int i = 0; i < 6; i++)
  206. {
  207. int randCode;
  208. do
  209. {
  210. randCode = rand.Next(50, 90);
  211. uniqueId[i] = Convert.ToByte(randCode);
  212. } while (randCode >= 58 && randCode <= 64 || randCode == 79 || randCode == 73);
  213. }
  214. return System.Text.Encoding.ASCII.GetString(uniqueId);
  215. }
  216. }
  217. catch (Exception ex)
  218. {
  219. Logger.WriteLineError($"GenerateShortCode error {ex}");
  220. }
  221. return string.Empty;
  222. }
  223. /// <summary>
  224. /// 设置敏感信息是否加密请求
  225. /// </summary>
  226. /// <param name="request">设置敏感信息是否加密请求实体</param>
  227. /// <returns>是否成功</returns>
  228. public async Task<bool> SetDeviceIsEncryptedShowAsync(SetDeviceIsEncryptedShowRequest request)
  229. {
  230. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  231. var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  232. if (deviceDTO == null)
  233. {
  234. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
  235. }
  236. deviceDTO.IsEncryptedShow = request.IsEncryptedShow;
  237. return await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDTO.DeviceCode, deviceDTO, string.Empty);
  238. }
  239. }
  240. }