ConnectService.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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. using WingServerCommon.Config.Parameters;
  20. using System.Text.RegularExpressions;
  21. using WingDeviceService.Common;
  22. using WingInterfaceLibrary.Internal.Request;
  23. using System.Net;
  24. using WingServerCommon.Utilities;
  25. namespace WingDeviceService.Service
  26. {
  27. /// <summary>
  28. /// 鉴权服务
  29. /// </summary>
  30. public partial class DeviceService : JsonRpcService, IConnectService
  31. {
  32. private readonly bool _isMergedChannel = ConfigurationManager.GetParammeter<BoolParameter>("Device", "IsMergedChannel").Value;
  33. private readonly int _highMergedVideoOutputWidth = ConfigurationManager.GetParammeter<IntParameter>("Device", "HighMergedVideoOutputWidth").Value;
  34. private readonly int _highMergedVideoOutputHeight = ConfigurationManager.GetParammeter<IntParameter>("Device", "HighMergedVideoOutputHeight").Value;
  35. private readonly int _lowMergedVideoOutputWidth = ConfigurationManager.GetParammeter<IntParameter>("Device", "LowMergedVideoOutputWidth").Value;
  36. private readonly int _lowMergedVideoOutputHeight = ConfigurationManager.GetParammeter<IntParameter>("Device", "LowMergedVideoOutputHeight").Value;
  37. private readonly string _highCpuLevels = ConfigurationManager.GetParammeter<StringParameter>("Device", "HighCpuLevels").Value;
  38. private readonly string _sourceUrl = "cloud.xinglinghui.com";
  39. private readonly object _createShortCodeLocker = new object();
  40. /// <summary>设备连接云服务</summary>
  41. /// <param name="request">请求对象</param>
  42. /// <returns>授权响应</returns>
  43. /// <remarks>POST</remarks>
  44. public async Task<ConnectResult> ConnectAsync(ConnectRequest request)
  45. {
  46. try
  47. {
  48. #region Params Check
  49. if (!request.IsOldPlatform)
  50. {
  51. if (string.IsNullOrWhiteSpace(request.DeviceUniqueCode))
  52. {
  53. ThrowCustomerException(CustomerRpcCode.DeviceUniqueCodeEmpty, "DeviceUniqueCode empty error");
  54. }
  55. if (string.IsNullOrWhiteSpace(request.DeviceModel))
  56. {
  57. ThrowCustomerException(CustomerRpcCode.DeviceModelEmpty, "DeviceModel empty error");
  58. }
  59. if (string.IsNullOrWhiteSpace(request.DeviceType))
  60. {
  61. ThrowCustomerException(CustomerRpcCode.DeviceTypeEmpty, "DeviceType empty error");
  62. }
  63. if (string.IsNullOrWhiteSpace(request.SoftwareVersion))
  64. {
  65. ThrowCustomerException(CustomerRpcCode.SoftwareVersionEmpty, "SoftwareVersion empty error");
  66. }
  67. if (string.IsNullOrWhiteSpace(request.SystemVersion))
  68. {
  69. ThrowCustomerException(CustomerRpcCode.SystemVersionEmpty, "SystemVersion empty error");
  70. }
  71. if (string.IsNullOrWhiteSpace(request.CPUModel))
  72. {
  73. ThrowCustomerException(CustomerRpcCode.CPUModelEmpty, "CPUModel empty error");
  74. }
  75. if (string.IsNullOrWhiteSpace(request.SystemLanguage))
  76. {
  77. ThrowCustomerException(CustomerRpcCode.SystemVersionEmpty, "SystemLanguage empty error");
  78. }
  79. var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
  80. if (!deviceTypeList.Select(x => x.DictionaryCode).Contains(request.DeviceType))
  81. {
  82. // ThrowCustomerException(CustomerRpcCode.DeviceTypeError, "DeviceType error");
  83. Logger.WriteLineWarn(CustomerRpcCode.DeviceTypeError.ToString() + "_" + request.DeviceType);
  84. }
  85. var deviceModelList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceModel });
  86. if (!deviceModelList.Select(x => x.Value).Contains(request.DeviceModel))
  87. {
  88. //ThrowCustomerException(CustomerRpcCode.DeviceModelError, "DeviceModel error");
  89. Logger.WriteLineWarn(CustomerRpcCode.DeviceModelError.ToString() + "_" + request.DeviceModel);
  90. }
  91. }
  92. #endregion
  93. DeviceInfoDTO deviceDto;
  94. if (request.IsOldPlatform)
  95. {
  96. deviceDto = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  97. if (deviceDto == null || string.IsNullOrWhiteSpace(deviceDto.DeviceCode))
  98. {
  99. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "DeviceNotExist");
  100. }
  101. deviceDto.SerialNumber = request.DeviceUniqueCode;
  102. if (!string.IsNullOrWhiteSpace(request.Name))
  103. {
  104. deviceDto.Name = request.Name;
  105. }
  106. deviceDto.DeviceType = request.DeviceType;
  107. deviceDto.DeviceSoftwareVersion = request.SoftwareVersion;
  108. // deviceDto.SystemVersion = request.SystemVersion;
  109. // deviceDto.CPUModel = request.CPUModel;
  110. // deviceDto.SystemLanguage = request.SystemLanguage;
  111. await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDto.DeviceCode, deviceDto, string.Empty, true);
  112. }
  113. else
  114. {
  115. deviceDto = await _deviceInfoDBServiceProxy.FindDeviceInfoBySerialNumberAsync(request.DeviceUniqueCode);
  116. if (deviceDto == null && !string.IsNullOrWhiteSpace(request.Name))
  117. {
  118. deviceDto = await _deviceInfoDBServiceProxy.FindDeviceInfoByNameAsync(request.Name);
  119. if (!string.IsNullOrWhiteSpace(request.Password))
  120. {
  121. var password = OldSecurity.Hash(OldSecurity.Salt(request.Password));
  122. if (deviceDto == null)
  123. {
  124. ThrowCustomerException(CustomerRpcCode.DeviceNameNotExisted, "DeviceNameNotExisted");
  125. }
  126. else if (deviceDto.Password != password)
  127. {
  128. ThrowCustomerException(CustomerRpcCode.DevicePasswordErr, "DevicePasswordErr");
  129. }
  130. }
  131. }
  132. if (deviceDto == null)
  133. {
  134. deviceDto = new DeviceInfoDTO()
  135. {
  136. SerialNumber = request.DeviceUniqueCode,
  137. Name = request.Name,
  138. Password = request.Password,
  139. Description = request.Description,
  140. OrganizationCode = request.OrganizationCode,
  141. DeviceModel = request.DeviceModel,
  142. DeviceType = request.DeviceType,
  143. DeviceSoftwareVersion = request.SoftwareVersion,
  144. SystemVersion = request.SystemVersion,
  145. CPUModel = request.CPUModel,
  146. SystemLanguage = request.SystemLanguage,
  147. IsEncryptedShow = false,
  148. MergedChannel = _isMergedChannel
  149. };
  150. SetDeviceMergedOutput(request.DeviceModel, request.CPUModel, deviceDto);
  151. var shortCode = deviceDto.ShortCode;
  152. for (var i = 0; i < 5; i++)
  153. {
  154. shortCode = GenerateShortCode();
  155. if (!string.IsNullOrWhiteSpace(shortCode))
  156. {
  157. var device = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(shortCode);
  158. if (device == null || string.IsNullOrWhiteSpace(device.DeviceCode))
  159. {
  160. break;
  161. }
  162. }
  163. shortCode = string.Empty;
  164. }
  165. deviceDto.ShortCode = shortCode;
  166. if (string.IsNullOrWhiteSpace(deviceDto.OrganizationCode))
  167. {
  168. deviceDto.OrganizationCode = "VINNO_FIS";
  169. }
  170. deviceDto.DeviceCode = await _deviceInfoDBServiceProxy.InsertDeviceInfoAsync(new WingInterfaceLibrary.DB.Request.CreateDeviceInfoDBRequest
  171. {
  172. Data = deviceDto
  173. });
  174. }
  175. else
  176. {
  177. deviceDto.SerialNumber = request.DeviceUniqueCode;
  178. if (!string.IsNullOrWhiteSpace(request.Name))
  179. {
  180. deviceDto.Name = request.Name;
  181. }
  182. deviceDto.DeviceModel = request.DeviceModel;
  183. deviceDto.DeviceType = request.DeviceType;
  184. deviceDto.DeviceSoftwareVersion = request.SoftwareVersion;
  185. deviceDto.SystemVersion = request.SystemVersion;
  186. deviceDto.CPUModel = request.CPUModel;
  187. SetDeviceMergedOutput(request.DeviceModel, request.CPUModel, deviceDto);
  188. // deviceDto.Description = request.Description;
  189. // deviceDto.Name = request.Name;
  190. // deviceDto.OrganizationCode = request.OrganizationCode;
  191. deviceDto.SystemLanguage = request.SystemLanguage;
  192. await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDto.DeviceCode, deviceDto, string.Empty, true);
  193. }
  194. }
  195. //更新设备型号
  196. if (!string.IsNullOrEmpty(request.DeviceModel) && !string.IsNullOrEmpty(request.DeviceType))
  197. {
  198. var typeModel = await _deviceInfoDBServiceProxy.FindDictionaryByCodeAsync(request.DeviceType);
  199. if (typeModel != null && typeModel.DictionaryType == DictionaryTypeEnum.DeviceType)
  200. {
  201. var dicRequest = new FindDictionaryItemsDBRequest()
  202. {
  203. DictionaryType = (int)DictionaryTypeEnum.DeviceModel,
  204. ParentCode = typeModel.DictionaryCode,
  205. Value = request.DeviceModel
  206. };
  207. var dataList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(dicRequest);
  208. if (dataList?.Count > 0)
  209. {
  210. //存在,不处理
  211. }
  212. else
  213. {
  214. //新增
  215. var createDictionaryItemDBRequest = new CreateDictionaryItemDBRequest()
  216. {
  217. Data = new WingInterfaceLibrary.DTO.Dictionary.DictionaryDTO() {
  218. LanguageConfigs = new List<WingInterfaceLibrary.DTO.Dictionary.DictionaryLanguageConfigDTO> (),
  219. DictionaryCode = Guid.NewGuid().ToString("N"),
  220. DictionaryType = DictionaryTypeEnum.DeviceModel,
  221. Value = request.DeviceModel,
  222. ParentCode = typeModel.DictionaryCode,
  223. },
  224. ExtensionData = string.Empty
  225. };
  226. var res = await _deviceInfoDBServiceProxy.CreateDictionaryItemAsync(createDictionaryItemDBRequest);
  227. }
  228. }
  229. }
  230. var deviceName = !string.IsNullOrWhiteSpace(deviceDto.Description) ? deviceDto.Description : deviceDto.Name;
  231. if (string.IsNullOrWhiteSpace(deviceName))
  232. {
  233. deviceName = deviceDto.ShortCode;
  234. }
  235. var applyRequest = new ApplyTokenRequest(AccountType.US, deviceName, request.Platform, request.LoginSource, deviceDto.DeviceCode, ConfigurationManager.Host, IpToLong(request.Ip), request.InstallVersion, request.IsOldPlatform,request.ProxyType);
  236. var tokenInfo = await _authenticationService.ApplyTokenAsync(applyRequest);
  237. if (!string.IsNullOrWhiteSpace(tokenInfo.Code))
  238. {
  239. _deviceHeartRateManager.AddOrUpdate(tokenInfo.Code);
  240. }
  241. _rtcService.GetOrCloseDeviceAsync(new GetOrCloseDeviceRequest
  242. {
  243. DeviceShortCode = deviceDto.ShortCode,
  244. CloseDevicePush = true,
  245. });
  246. return new ConnectResult
  247. {
  248. Token = tokenInfo.Code,
  249. UniqueCode = deviceDto.ShortCode,
  250. DeviceCode = deviceDto.DeviceCode
  251. };
  252. }
  253. catch (Exception ex)
  254. {
  255. Logger.WriteLineWarn($"device connect server failed, err:{ex}");
  256. throw;
  257. }
  258. }
  259. /// <summary>
  260. /// Ip转Long
  261. /// </summary>
  262. /// <param name="ip"></param>
  263. /// <returns></returns>
  264. private long IpToLong(string ip)
  265. {
  266. try
  267. {
  268. if (System.Net.IPAddress.TryParse(ip, out IPAddress ipAddress))
  269. {
  270. char[] separator = new char[] { '.' };
  271. string[] items = ip.Split(separator);
  272. var ipLong = long.Parse(items[0]) << 24 | long.Parse(items[1]) << 16 | long.Parse(items[2]) << 8 | long.Parse(items[3]);
  273. return ipLong;
  274. }
  275. // else
  276. // {
  277. // Logger.WriteLineWarn($"IpToLong failed, err ip formatter, ip: {ip}");
  278. // }
  279. }
  280. catch (Exception ex)
  281. {
  282. Logger.WriteLineWarn($"IpToLong failed, ip: {ip}, ex:{ex}");
  283. }
  284. return 0;
  285. }
  286. private void SetDeviceMergedOutput(string deviceModel, string cpuModel, DeviceInfoDTO deviceDto)
  287. {
  288. var highCpu = _highCpuLevels?.Split(',');
  289. if (deviceModel.ToUpper().StartsWith("SP002"))
  290. {
  291. deviceDto.MergedVideoOutputWidth = _highMergedVideoOutputWidth;
  292. deviceDto.MergedVideoOutputHeight = _highMergedVideoOutputHeight;
  293. }
  294. else if (highCpu != null && highCpu.Contains(cpuModel))
  295. {
  296. deviceDto.MergedVideoOutputWidth = _highMergedVideoOutputWidth;
  297. deviceDto.MergedVideoOutputHeight = _highMergedVideoOutputHeight;
  298. }
  299. else if (Regex.IsMatch(cpuModel, "[iI][0-9]*-"))
  300. {
  301. var matches = Regex.Match(cpuModel, "[iI]([0-9]*)-");
  302. if (matches.Success)
  303. {
  304. int.TryParse(matches.Groups[1].Value, out int cpuLevel);
  305. if (cpuLevel >= 5)
  306. {
  307. deviceDto.MergedVideoOutputWidth = _highMergedVideoOutputWidth;
  308. deviceDto.MergedVideoOutputHeight = _highMergedVideoOutputHeight;
  309. }
  310. else
  311. {
  312. deviceDto.MergedVideoOutputWidth = _lowMergedVideoOutputWidth;
  313. deviceDto.MergedVideoOutputHeight = _lowMergedVideoOutputHeight;
  314. }
  315. }
  316. else
  317. {
  318. deviceDto.MergedVideoOutputWidth = _lowMergedVideoOutputWidth;
  319. deviceDto.MergedVideoOutputHeight = _lowMergedVideoOutputHeight;
  320. }
  321. }
  322. else
  323. {
  324. deviceDto.MergedVideoOutputWidth = _lowMergedVideoOutputWidth;
  325. deviceDto.MergedVideoOutputHeight = _lowMergedVideoOutputHeight;
  326. }
  327. }
  328. /// <summary>查询当前设备信息</summary>
  329. /// <param name="request">请求对象</param>
  330. /// <returns>设备信息</returns>
  331. /// <remarks>POST</remarks>
  332. public async Task<CacheDeviceDTO> GetDeviceByTokenAsync(TokenRequest request)
  333. {
  334. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  335. var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  336. var cacheDeviceInfo = deviceDTO.MappingTo<CacheDeviceDTO>();
  337. cacheDeviceInfo.IsOnline = await GetDeviceOnlineState(deviceCode);
  338. return cacheDeviceInfo;
  339. }
  340. /// <summary>设备与云服务断开连接</summary>
  341. /// <param name="request">请求对象</param>
  342. /// <returns>是否成功</returns>
  343. /// <value>true</value>
  344. public async Task<bool> DisConnectAsync(TokenRequest request)
  345. {
  346. try
  347. {
  348. await _authenticationService.LogOffAsync(request);
  349. return true;
  350. }
  351. catch (Exception ex)
  352. {
  353. Logger.WriteLineWarn($"device disconnect failed, ex:{ex}");
  354. throw;
  355. }
  356. }
  357. /// <summary>获取设备在线状态</summary>
  358. /// <param name="deviceCode"></param>
  359. /// <returns></returns>
  360. private async Task<bool> GetDeviceOnlineState(string deviceCode)
  361. {
  362. var tokenList = await _authenticationService.GetTokensWithClientIdAsync(new GetTokensWithClientIdRequest { ClientId = deviceCode });
  363. return tokenList.FirstOrDefault()?.IsOnline ?? false;
  364. }
  365. /// <summary>生成唯一 shortCode</summary>
  366. /// <returns></returns>
  367. private string GenerateShortCode()
  368. {
  369. try
  370. {
  371. lock (_createShortCodeLocker)
  372. {
  373. var uniqueId = new byte[6];
  374. var rand = new Random((int)(DateTime.Now.Ticks % 1000000));
  375. for (int i = 0; i < 6; i++)
  376. {
  377. int randCode;
  378. do
  379. {
  380. randCode = rand.Next(50, 90);
  381. uniqueId[i] = Convert.ToByte(randCode);
  382. } while (randCode >= 58 && randCode <= 64 || randCode == 79 || randCode == 73);
  383. }
  384. return System.Text.Encoding.ASCII.GetString(uniqueId);
  385. }
  386. }
  387. catch (Exception ex)
  388. {
  389. Logger.WriteLineError($"GenerateShortCode error {ex}");
  390. }
  391. return string.Empty;
  392. }
  393. /// <summary>
  394. /// 设置敏感信息是否加密请求
  395. /// </summary>
  396. /// <param name="request">设置敏感信息是否加密请求实体</param>
  397. /// <returns>是否成功</returns>
  398. public async Task<bool> SetDeviceIsEncryptedShowAsync(SetDeviceIsEncryptedShowRequest request)
  399. {
  400. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  401. var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  402. if (deviceDTO == null)
  403. {
  404. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
  405. }
  406. deviceDTO.IsEncryptedShow = request.IsEncryptedShow;
  407. return await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDTO.DeviceCode, deviceDTO, string.Empty);
  408. }
  409. }
  410. }