ConnectService.cs 12 KB

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