ConnectService.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
  66. if (!deviceTypeList.Select(x => x.DictionaryCode).Contains(request.DeviceType))
  67. {
  68. ThrowCustomerException(CustomerRpcCode.DeviceTypeError, "DeviceType error");
  69. }
  70. #endregion
  71. var deviceDto = await _deviceInfoDBServiceProxy.FindDeviceInfoBySerialNumberAsync(request.DeviceUniqueCode);
  72. if (deviceDto == null)
  73. {
  74. deviceDto = new DeviceInfoDTO()
  75. {
  76. SerialNumber = request.DeviceUniqueCode,
  77. Name = request.Name,
  78. Password = request.Password,
  79. Description = request.Description,
  80. OrganizationCode = request.OrganizationCode,
  81. DeviceModel = request.DeviceModel,
  82. DeviceType = request.DeviceType,
  83. DeviceSoftwareVersion = request.SoftwareVersion,
  84. SystemVersion = request.SystemVersion,
  85. CPUModel = request.CPUModel,
  86. SystemLanguage = request.SystemLanguage,
  87. IsEncryptedShow = true
  88. };
  89. var shortCode = deviceDto.ShortCode;
  90. for (var i = 0; i < 5; i++)
  91. {
  92. shortCode = GenerateShortCode();
  93. if (!string.IsNullOrWhiteSpace(shortCode))
  94. {
  95. var device = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(shortCode);
  96. if (device == null || string.IsNullOrWhiteSpace(device.DeviceCode))
  97. {
  98. break;
  99. }
  100. }
  101. shortCode = string.Empty;
  102. }
  103. deviceDto.ShortCode = shortCode;
  104. deviceDto.DeviceCode = await _deviceInfoDBServiceProxy.InsertDeviceInfoAsync(new WingInterfaceLibrary.DB.Request.CreateDeviceInfoDBRequest
  105. {
  106. Data = deviceDto
  107. });
  108. //创建虚拟机构
  109. var inventedOrgCode = "invented_" + shortCode;
  110. var orgData = new TableDataItem<OrganizationDTO>
  111. {
  112. Data = new OrganizationDTO
  113. {
  114. OrganizationCode = inventedOrgCode,
  115. RootCode = inventedOrgCode,
  116. OrganizationName = shortCode,
  117. OrganizationType = OrganizationTypeEnum.Corporation,
  118. State = OrganizationStateEnum.Audited,
  119. RegionCode = "1000000",
  120. Isinvented = true
  121. },
  122. PlatformDatas = new Dictionary<string, string>(),
  123. ExtensionData = string.Empty,
  124. };
  125. await _organizationDBService.CreateOrganizationsAsync(new CreateOrganizationsDBRequest { Infos = new List<TableDataItem<OrganizationDTO>> { orgData } });
  126. }
  127. else
  128. {
  129. deviceDto.DeviceModel = request.DeviceModel;
  130. deviceDto.DeviceType = request.DeviceType;
  131. deviceDto.DeviceSoftwareVersion = request.SoftwareVersion;
  132. deviceDto.SystemVersion = request.SystemVersion;
  133. deviceDto.CPUModel = request.CPUModel;
  134. // deviceDto.Description = request.Description;
  135. // deviceDto.Name = request.Name;
  136. // deviceDto.OrganizationCode = request.OrganizationCode;
  137. deviceDto.SystemLanguage = request.SystemLanguage;
  138. await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDto.DeviceCode, deviceDto, string.Empty, true);
  139. }
  140. var deviceName = deviceDto.Name;
  141. if (string.IsNullOrWhiteSpace(deviceName))
  142. {
  143. deviceName = deviceDto.ShortCode;
  144. }
  145. var applyRequest = new ApplyTokenRequest(AccountType.US, deviceName, request.Platform, request.LoginSource, deviceDto.DeviceCode, ConfigurationManager.Host, 0);
  146. var tokenInfo = await _authenticationService.ApplyTokenAsync(applyRequest);
  147. if (!string.IsNullOrWhiteSpace(tokenInfo.Code))
  148. {
  149. _deviceHeartRateManager.AddOrUpdate(tokenInfo.Code);
  150. }
  151. return new ConnectResult
  152. {
  153. Token = tokenInfo.Code,
  154. UniqueCode = deviceDto.ShortCode
  155. };
  156. }
  157. catch (Exception ex)
  158. {
  159. Logger.WriteLineWarn($"device connect server failed, err:{ex}");
  160. throw;
  161. }
  162. }
  163. /// <summary>查询当前设备信息</summary>
  164. /// <param name="request">请求对象</param>
  165. /// <returns>设备信息</returns>
  166. /// <remarks>POST</remarks>
  167. public async Task<CacheDeviceDTO> GetDeviceByTokenAsync(TokenRequest request)
  168. {
  169. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  170. var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  171. var cacheDeviceInfo = deviceDTO.MappingTo<CacheDeviceDTO>();
  172. cacheDeviceInfo.IsOnline = await GetDeviceOnlineState(deviceCode);
  173. return cacheDeviceInfo;
  174. }
  175. /// <summary>设备与云服务断开连接</summary>
  176. /// <param name="request">请求对象</param>
  177. /// <returns>是否成功</returns>
  178. /// <value>true</value>
  179. public async Task<bool> DisConnectAsync(TokenRequest request)
  180. {
  181. try
  182. {
  183. await _authenticationService.LogOffAsync(request);
  184. return true;
  185. }
  186. catch (Exception ex)
  187. {
  188. Logger.WriteLineWarn($"device disconnect failed, ex:{ex}");
  189. throw;
  190. }
  191. }
  192. /// <summary>获取设备在线状态</summary>
  193. /// <param name="deviceCode"></param>
  194. /// <returns></returns>
  195. private async Task<bool> GetDeviceOnlineState(string deviceCode)
  196. {
  197. var tokenList = await _authenticationService.GetTokensWithClientIdAsync(new GetTokensWithClientIdRequest { ClientId = deviceCode });
  198. return tokenList.FirstOrDefault()?.IsOnline ?? false;
  199. }
  200. /// <summary>生成唯一 shortCode</summary>
  201. /// <returns></returns>
  202. private string GenerateShortCode()
  203. {
  204. try
  205. {
  206. lock (_createShortCodeLocker)
  207. {
  208. var uniqueId = new byte[6];
  209. var rand = new Random((int)(DateTime.Now.Ticks % 1000000));
  210. for (int i = 0; i < 6; i++)
  211. {
  212. int randCode;
  213. do
  214. {
  215. randCode = rand.Next(50, 90);
  216. uniqueId[i] = Convert.ToByte(randCode);
  217. } while (randCode >= 58 && randCode <= 64 || randCode == 79 || randCode == 73);
  218. }
  219. return System.Text.Encoding.ASCII.GetString(uniqueId);
  220. }
  221. }
  222. catch (Exception ex)
  223. {
  224. Logger.WriteLineError($"GenerateShortCode error {ex}");
  225. }
  226. return string.Empty;
  227. }
  228. /// <summary>
  229. /// 设置敏感信息是否加密请求
  230. /// </summary>
  231. /// <param name="request">设置敏感信息是否加密请求实体</param>
  232. /// <returns>是否成功</returns>
  233. public async Task<bool> SetDeviceIsEncryptedShowAsync(SetDeviceIsEncryptedShowRequest request)
  234. {
  235. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  236. var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  237. if (deviceDTO == null)
  238. {
  239. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
  240. }
  241. deviceDTO.IsEncryptedShow = request.IsEncryptedShow;
  242. return await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDTO.DeviceCode, deviceDTO, string.Empty);
  243. }
  244. }
  245. }