DeviceService.cs 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using WingInterfaceLibrary.DTO.Device;
  6. using WingInterfaceLibrary.Interface;
  7. using WingInterfaceLibrary.Request.Device;
  8. using WingInterfaceLibrary.DTO.Dictionary;
  9. using WingServerCommon.Log;
  10. using WingServerCommon.Service;
  11. using WingInterfaceLibrary.Interface.DBInterface;
  12. using WingInterfaceLibrary.DB.Request;
  13. using WingServerCommon.Mapper;
  14. using WingInterfaceLibrary.Request;
  15. using WingInterfaceLibrary.Request.Authentication;
  16. using WingInterfaceLibrary.DTO.User;
  17. using WingInterfaceLibrary.DTO.Management;
  18. using WingServerCommon.Config;
  19. using WingDeviceService.Common;
  20. using WingInterfaceLibrary.Request.User;
  21. using WingInterfaceLibrary.Enum;
  22. using WingInterfaceLibrary.DTO.Organization;
  23. using WingInterfaceLibrary.DTO.DiagnosisModule;
  24. using WingServerCommon.Config.Parameters;
  25. using WingServerCommon.Interfaces.Cache;
  26. using WingInterfaceLibrary.LiveConsultation;
  27. using WingInterfaceLibrary.Result.Languge;
  28. using WingInterfaceLibrary.Internal.Interface;
  29. using WingInterfaceLibrary.Notifications;
  30. using WingInterfaceLibrary.Internal.Request;
  31. using WingInterfaceLibrary.Rtc;
  32. using WingInterfaceLibrary.Enum.CommentEnum;
  33. using WingInterfaceLibrary.DTO.RTC;
  34. using Newtonsoft.Json;
  35. using WingInterfaceLibrary.Notifications.Live;
  36. using WingInterfaceLibrary.Enum.NotificationEnum;
  37. using WingInterfaceLibrary.DTO.LiveRoom;
  38. using WingInterfaceLibrary.Request.DBRequest;
  39. using WingInterfaceLibrary.DTO.Record;
  40. using WingInterfaceLibrary.DTO.Consultation;
  41. using WingServerCommon.Interfaces.Cache;
  42. using System.Collections.Concurrent;
  43. namespace WingDeviceService.Service
  44. {
  45. /// <summary>
  46. /// 设备管理服务
  47. /// </summary>
  48. public partial class DeviceService : JsonRpcService, IDeviceService
  49. {
  50. private ConcurrentDictionary<string, CacheControllingParameter> _controllingParameterDevices = new ConcurrentDictionary<string, CacheControllingParameter>();
  51. private IUserDBService _userServiceProxy;
  52. private IDeviceInfoDBService _deviceInfoDBServiceProxy;
  53. private IAuthenticationService _authenticationService;
  54. private IOrganizationDBService _organizationDBService;
  55. private INotificationService _notificationService;
  56. private IRecordsInfoDBService _recordsInfoDBService;
  57. private IPatientInfoDBService _patientInfoDBService;
  58. private IDiagnosisModuleDBService _diagnosisModuleService;
  59. private IRemedicalService _remedicalService;
  60. private IWingRtcService _rtcService;
  61. private int _heartRateSeconds;
  62. private DeviceHeartRateManager _deviceHeartRateManager;
  63. private string _webSocketUrl = string.Empty;
  64. private int _liveConsultationRateSeconds = 0;
  65. private bool _isRTCSelf = false;
  66. private int _sdkAppId = 0;
  67. private int _remoteControlAskTimeoutSec = 0;
  68. private int _reportStateIntervalSeconds = 0;
  69. private int _reportStateTimeout = 0;
  70. private ILiveConsultationService _liveConsultationService;
  71. private IConsultationRecordDBService _consultationRecordDBService;
  72. private IRemedicalDBService _remedicalDBService;
  73. /// <summary>
  74. /// Init service
  75. /// </summary>
  76. public override void Load(JsonRpcClientPool jsonRpcClientPool)
  77. {
  78. base.Load(jsonRpcClientPool);
  79. _userServiceProxy = GetProxy<IUserDBService>();
  80. _authenticationService = GetProxy<IAuthenticationService>();
  81. _deviceInfoDBServiceProxy = GetProxy<IDeviceInfoDBService>();
  82. _organizationDBService = GetProxy<IOrganizationDBService>();
  83. _notificationService = GetProxy<INotificationService>();
  84. _recordsInfoDBService = GetProxy<IRecordsInfoDBService>();
  85. _patientInfoDBService = GetProxy<IPatientInfoDBService>();
  86. _diagnosisModuleService = GetProxy<IDiagnosisModuleDBService>();
  87. _remedicalService = GetProxy<IRemedicalService>();
  88. _rtcService = GetProxy<IWingRtcService>();
  89. _liveConsultationService = GetProxy<ILiveConsultationService>();
  90. _consultationRecordDBService = GetProxy<IConsultationRecordDBService>();
  91. _remedicalDBService = GetProxy<IRemedicalDBService>();
  92. _heartRateSeconds = ConfigurationManager.GetParammeter<IntParameter>("Device", "HeartRateSeconds").Value;
  93. _deviceHeartRateManager = new DeviceHeartRateManager(SetOnlineState);
  94. _webSocketUrl = ConfigurationManager.GetParammeter<StringParameter>("Notification", "WebSocketUrl").Value;
  95. _liveConsultationRateSeconds = ConfigurationManager.GetParammeter<IntParameter>("Live", "HeartRateSeconds").Value;
  96. _isRTCSelf = ConfigurationManager.GetParammeter<BoolParameter>("Rtc", "IsSelf").Value;
  97. var sdkAppIdString = ConfigurationManager.GetParammeter<StringParameter>("Rtc", "RTCAppId").Value;
  98. if (int.TryParse(sdkAppIdString, out int sdkAppId))
  99. {
  100. _sdkAppId = sdkAppId;
  101. }
  102. _remoteControlAskTimeoutSec = ConfigurationManager.GetParammeter<IntParameter>("Device", "RemoteControlAskTimeoutSec").Value;
  103. var _reportStateIntervalSeconds = ConfigurationManager.GetParammeter<IntParameter>("Live", "ReportStateIntervalSeconds").Value;
  104. var _reportStateTimeout = ConfigurationManager.GetParammeter<IntParameter>("Live", "ReportStateTimeout").Value;
  105. }
  106. /// <summary>
  107. /// 设备心跳
  108. /// </summary>
  109. /// <param name="request"></param>
  110. /// <returns></returns>
  111. public async Task<bool> HeartRateAsync(TokenRequest request)
  112. {
  113. _deviceHeartRateManager.AddOrUpdate(request.Token);
  114. var result = SetOnlineState(request.Token, true);
  115. return result;
  116. }
  117. private bool SetOnlineState(string token, bool isOnline)
  118. {
  119. return _authenticationService.SetOnlineStateAsync(new SetOnlineStateRequest { Token = token, IsOnline = isOnline }).Result;
  120. }
  121. /// <summary>
  122. /// 添加分享设备关联用户请求
  123. /// </summary>
  124. /// <param name="request"></param>
  125. /// <returns></returns>
  126. public async Task<bool> CreateShareDeviceToUserAsync(CreateShareDeviceToUserRequest request)
  127. {
  128. var userCodes = request.UserCodes;
  129. var deviceCode = request.DeviceCode;
  130. //检查设备编码不为空
  131. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  132. {
  133. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  134. }
  135. if (userCodes == null || userCodes.Count <= 0)
  136. {
  137. ThrowCustomerException(CustomerRpcCode.UserCodeEmptyError, "Required parameter:UserCodes cannot be empty");
  138. }
  139. //查询设备对象
  140. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  141. if (deviceDb == null)
  142. {
  143. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  144. }
  145. foreach (var userCode in userCodes)
  146. {
  147. var existUser = await _userServiceProxy.FindUserByCodeAsync(userCode);
  148. if (existUser == null)
  149. {
  150. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  151. }
  152. }
  153. await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  154. {
  155. DeviceCodes = new List<string> { deviceCode },
  156. UserCodes = userCodes.ToList()
  157. });
  158. return true;
  159. }
  160. /// <summary>
  161. /// 根据设备code获取设备信息
  162. /// </summary>
  163. /// <param name="request">设备code请求实体</param>
  164. /// <returns>返回查询到的设备对象信息</returns>
  165. public async Task<DeviceExtendInfoDTO> GetDeviceInfoAsync(GetDeviceRequest request)
  166. {
  167. //验证
  168. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  169. {
  170. ThrowCustomerException(CustomerRpcCode.DeviceCodeEmpty, "DeviceCode empty error");
  171. }
  172. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  173. if (deviceDb == null || deviceDb.DeviceCode != request.DeviceCode)
  174. {
  175. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  176. }
  177. //根据机构编号查询机构名称
  178. var organizationName = "";
  179. if (!string.IsNullOrEmpty(deviceDb.OrganizationCode))
  180. {
  181. var organization = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceDb.OrganizationCode });
  182. organizationName = organization?.OrganizationName ?? string.Empty;
  183. }
  184. //根据机构编号查询科室名称
  185. var departmentName = "";
  186. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  187. {
  188. var department = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceDb.DepartmentCode });
  189. departmentName = department?.OrganizationName ?? string.Empty;
  190. }
  191. //是否在线 todo
  192. var deviceTypeModel = await _deviceInfoDBServiceProxy.FindDictionaryByCodeAsync(deviceDb.DeviceType);
  193. var result = new DeviceExtendInfoDTO()
  194. {
  195. DepartmentName = departmentName,
  196. OrganizationName = organizationName,
  197. IsOnline = await GetDeviceOnlineState(deviceDb.DeviceCode),
  198. DeviceCode = deviceDb.DeviceCode,
  199. SerialNumber = deviceDb.SerialNumber,
  200. Name = deviceDb.Name,
  201. Description = deviceDb.Description,
  202. DeviceModel = deviceDb.DeviceModel,
  203. DeviceType = deviceDb.DeviceType,
  204. HeadPicUrl = deviceDb.HeadPicUrl,
  205. DeviceSoftwareVersion = deviceDb.DeviceSoftwareVersion,
  206. SDKSoftwareVersion = deviceDb.SDKSoftwareVersion,
  207. OrganizationCode = deviceDb.OrganizationCode,
  208. DepartmentCode = deviceDb.DepartmentCode,
  209. ShortCode = deviceDb.ShortCode,
  210. LanguageConfigs = deviceTypeModel.LanguageConfigs
  211. };
  212. return result;
  213. }
  214. /// <summary>
  215. /// 根据设备动态唯一码获取设备信息
  216. /// </summary>
  217. /// <param name="request"></param>
  218. /// <returns></returns>
  219. public async Task<DeviceExtendInfoDTO> GetDeviceByShortCodeAsync(GetDeviceByShortCodeRequest request)
  220. {
  221. //验证
  222. if (string.IsNullOrWhiteSpace(request.ShortCode))
  223. {
  224. ThrowCustomerException(CustomerRpcCode.ShortCodeEmpty, "ShortCode empty error");
  225. }
  226. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(request.ShortCode);
  227. if (deviceDb == null || deviceDb.ShortCode != request.ShortCode)
  228. {
  229. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  230. }
  231. return await MapToExtendDTO(deviceDb);
  232. }
  233. public async Task<PageCollection<DeviceInfoDTO>> GetDeviceInfoPageAsync(PageFilterRequest request)
  234. {
  235. throw new System.NotImplementedException();
  236. }
  237. public async Task<bool> DeleteShareDeviceToUserAsync(DeleteShareDeviceToUserRequest request)
  238. {
  239. var userCodes = request.UserCodes;
  240. var deviceCode = request.DeviceCode;
  241. //检查设备编码不为空
  242. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  243. {
  244. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  245. }
  246. //用户编码集合检查
  247. if (userCodes == null || userCodes.Count <= 0)
  248. {
  249. ThrowCustomerException(CustomerRpcCode.UserCodeEmptyError, "Required parameter:UserCodes cannot be empty");
  250. }
  251. //查询设备对象
  252. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  253. if (deviceDb == null)
  254. {
  255. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  256. }
  257. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  258. foreach (var userCode in userCodes)
  259. {
  260. var user = await _userServiceProxy.FindUserByCodeAsync(userCode);
  261. if (user != null)
  262. {
  263. if (user.BindDevices.Contains(deviceCode))
  264. {
  265. user.BindDevices.Remove(deviceCode);
  266. updateUsers.Add(new TableDataItem<UserPasswordDTO>()
  267. {
  268. Data = user.MappingTo<UserPasswordDTO>(),
  269. });
  270. }
  271. }
  272. }
  273. if (updateUsers.Count > 0)
  274. {
  275. var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
  276. await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
  277. }
  278. return true;
  279. }
  280. /// <summary>
  281. /// 机构设备移除-根据机构code和设备code解除其绑定关系
  282. /// </summary>
  283. /// <param name="request">移除设备请求实体</param>
  284. /// <returns>移除是否成功:true-成功;false-失败</returns>
  285. public async Task<bool> RemoveDeviceRelevancyAsync(RemoveDeviceRelevancyRequest request)
  286. {
  287. //验证
  288. if (string.IsNullOrWhiteSpace(request.DeviceCode) || string.IsNullOrWhiteSpace(request.OrganizationCode))
  289. {
  290. ThrowCustomerException(CustomerRpcCode.DeviceCodeOrOrganizationCodeEmpty, "DeviceCode Or OrganizationCode empty error");
  291. }
  292. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  293. if (deviceDb == null || deviceDb.OrganizationCode != request.OrganizationCode || deviceDb.DepartmentCode != request.DepartmentCode)
  294. {
  295. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "DeviceInfo not exist error");
  296. }
  297. //根据设备code和机构code查询相关数据,查到则删除关联
  298. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  299. {
  300. deviceDb.DepartmentCode = "";
  301. deviceDb.OrganizationCode = "";
  302. }
  303. else
  304. {
  305. deviceDb.OrganizationCode = "";
  306. }
  307. bool removeDeviceResult = await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
  308. return removeDeviceResult;
  309. }
  310. private async Task<string> GetClientIdByTokenAsync(string token)
  311. {
  312. var request = new TokenRequest() { Token = token };
  313. var result = await _authenticationService.GetTokenAsync(request);
  314. return result.ClientId; //return User code
  315. }
  316. /// <summary>
  317. /// 查询个人名下所有设备列表接口
  318. /// </summary>
  319. /// <param name="request">查询个人名下所有设备列表请求实体</param>
  320. /// <returns>返回设备信息列表</returns>
  321. public async Task<PageCollection<DeviceExtendInfoDTO>> GetPersonDeviceListAsync(GetPersonDeviceRequest request)
  322. {
  323. //验证
  324. var userCode = await GetClientIdByTokenAsync(request.Token);
  325. //查询用户是否存在
  326. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  327. if (userInfoDO == null)
  328. {
  329. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  330. }
  331. //查询用户的医院是否存在
  332. if (string.IsNullOrWhiteSpace(userInfoDO.OrganizationCode))
  333. {
  334. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  335. }
  336. var deviceInfoDOList = new List<DeviceInfoDTO>();
  337. if (!userInfoDO.IsDirector)
  338. {
  339. //普通用户,查询用户绑定的设备
  340. if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Any())
  341. {
  342. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
  343. }
  344. }
  345. else
  346. {
  347. //机构负责人
  348. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
  349. }
  350. if (!deviceInfoDOList.Any())
  351. {
  352. return new PageCollection<DeviceExtendInfoDTO>() { CurrentPage = request.PageIndex, PageSize = request.PageSize, DataCount = 0, PageData = new List<DeviceExtendInfoDTO>() };
  353. }
  354. var deviceList = await MapToExtendDTO(deviceInfoDOList);
  355. //条件筛选
  356. if (!string.IsNullOrWhiteSpace(request.DeviceType))
  357. {
  358. deviceList = deviceList.Where(d => d.DeviceType == request.DeviceType)?.ToList() ?? new List<DeviceExtendInfoDTO>();
  359. }
  360. if (!string.IsNullOrWhiteSpace(request.DeviceModel))
  361. {
  362. deviceList = deviceList.Where(d => d.DeviceModel == request.DeviceModel)?.ToList() ?? new List<DeviceExtendInfoDTO>();
  363. }
  364. if (!string.IsNullOrWhiteSpace(request.KeyWord))
  365. {
  366. var keyword = request.KeyWord.Trim().ToLower();
  367. deviceList = deviceList.Where(d => d.Name.ToLower().Contains(keyword) || d.ShortCode.ToLower().Contains(keyword))?.ToList() ?? new List<DeviceExtendInfoDTO>();
  368. }
  369. if (request.IsOnline != null)
  370. {
  371. deviceList = deviceList.Where(d => d.IsOnline == request.IsOnline)?.ToList() ?? new List<DeviceExtendInfoDTO>();
  372. }
  373. var pagedResult = new PageCollection<DeviceExtendInfoDTO>
  374. {
  375. CurrentPage = request.PageIndex,
  376. PageSize = request.PageSize,
  377. DataCount = deviceList.Count,
  378. PageData = deviceList.Skip(request.PageSize * (request.PageIndex - 1)).Take(request.PageSize)?.ToList() ?? new List<DeviceExtendInfoDTO>()
  379. };
  380. return pagedResult;
  381. }
  382. /// <summary>
  383. /// 绑定设备
  384. /// </summary>
  385. /// <param name="request"></param>
  386. /// <returns></returns>
  387. public async Task<bool> BindDeviceAsync(BindDeviceRequest request)
  388. {
  389. //验证
  390. var userCode = await GetClientIdByTokenAsync(request.Token);
  391. //查询用户是否存在
  392. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  393. if (userInfoDO == null)
  394. {
  395. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  396. }
  397. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(request.ShortCode);
  398. if (deviceDb == null)
  399. {
  400. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
  401. }
  402. if (userInfoDO.BindDevices != null && userInfoDO.BindDevices.Contains(deviceDb.DeviceCode))
  403. {
  404. ThrowCustomerException(CustomerRpcCode.HasAddedDevice, "The device has been Added");
  405. }
  406. try
  407. {
  408. var isInvented = (string.IsNullOrWhiteSpace(deviceDb.OrganizationCode) || deviceDb.OrganizationCode == $"invented_{deviceDb.ShortCode}") ? true : false;
  409. deviceDb.Name = request.Name;
  410. deviceDb.SerialNumber = request.SerialNumber;
  411. deviceDb.Description = request.Description;
  412. if (!string.IsNullOrEmpty(request.HeadPicUrl))
  413. {
  414. deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
  415. }
  416. deviceDb.DepartmentCode = request.DepartmentCode;
  417. deviceDb.IsAutoShared = request.IsAutoShared;
  418. deviceDb.OrganizationCode = request.OrganizationCode;
  419. await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty);
  420. if (isInvented && !string.IsNullOrWhiteSpace(request.OrganizationCode)) //虚拟机构改为正常机构
  421. {
  422. var newOrgCode = string.IsNullOrWhiteSpace(request.DepartmentCode) ? request.OrganizationCode : request.DepartmentCode;
  423. //迁移数据超声机上传检查记录
  424. await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
  425. //迁移数据超声机上传病人
  426. await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { deviceDb.DeviceCode }, newOrgCode);
  427. }
  428. if (deviceDb.IsAutoShared)
  429. {
  430. var users = new List<UserDTO>();
  431. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  432. {
  433. users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List<string> { deviceDb.DepartmentCode });
  434. }
  435. else
  436. {
  437. users = await _userServiceProxy.GetUserListAsync(new GetUserListDBRequest { OrganizationQueryType = OrganizationQueryTypeEnum.All, OrganizationCode = deviceDb.OrganizationCode });
  438. }
  439. var userCodes = users.Select(f => f.UserCode).ToList();
  440. await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  441. {
  442. DeviceCodes = new List<string> { deviceDb.DeviceCode.ToString() },
  443. UserCodes = userCodes.Select(f => f.ToString()).ToList()
  444. });
  445. }
  446. return true;
  447. }
  448. catch (Exception ex)
  449. {
  450. Logger.WriteLineError($"BindDeviceAsync error {ex}");
  451. }
  452. return false;
  453. }
  454. /// <summary>
  455. /// 修改设备
  456. /// </summary>
  457. /// <param name="request"></param>
  458. /// <returns></returns>
  459. public async Task<bool> ModifyDeviceAsync(ModifyDeviceRequest request)
  460. {
  461. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  462. if (deviceDb == null)
  463. {
  464. ThrowCustomerException(CustomerRpcCode.DeviceNotExist, "Not find device");
  465. }
  466. if (string.IsNullOrWhiteSpace(request.Name))
  467. {
  468. ThrowCustomerException(CustomerRpcCode.DeviceNameEmpty, "Device name cannot be empty");
  469. }
  470. deviceDb.Name = request.Name;
  471. if (!string.IsNullOrWhiteSpace(request.HeadPicUrl))
  472. {
  473. deviceDb.HeadPicUrl = request.HeadPicUrl.ToUrlToken();
  474. }
  475. else
  476. {
  477. deviceDb.HeadPicUrl = string.Empty;
  478. }
  479. deviceDb.DepartmentCode = request.DepartmentCode;
  480. //修改自动分享
  481. deviceDb.IsAutoShared = request.IsAutoShared;
  482. if (deviceDb.IsAutoShared)
  483. {
  484. var users = new List<UserDTO>();
  485. if (!string.IsNullOrEmpty(deviceDb.DepartmentCode))
  486. {
  487. users = await _userServiceProxy.FindUserListByOrganizationCodesAsync(new List<string> { deviceDb.DepartmentCode });
  488. }
  489. else
  490. {
  491. users = await _userServiceProxy.GetUserListAsync(new GetUserListDBRequest { OrganizationQueryType = OrganizationQueryTypeEnum.All, OrganizationCode = deviceDb.OrganizationCode });
  492. }
  493. var userCodes = users.Select(f => f.UserCode).ToList();
  494. //先解绑,再绑定,避免绑定重复设备code
  495. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  496. foreach (var user in users)
  497. {
  498. var userPasswordDTO = user.MappingTo<UserPasswordDTO>();
  499. user.BindDevices?.Remove(deviceDb.DeviceCode);
  500. await _userServiceProxy.UpdateUserAsync(userPasswordDTO.UserCode, userPasswordDTO, string.Empty);
  501. }
  502. await _userServiceProxy.BingDevicesToUsersAsync(new BingDevicesToUsersRequest
  503. {
  504. DeviceCodes = new List<string> { deviceDb.DeviceCode.ToString() },
  505. UserCodes = userCodes.Select(f => f.ToString()).ToList()
  506. });
  507. }
  508. return await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDb.DeviceCode, deviceDb, string.Empty, true);
  509. }
  510. /// <summary>
  511. /// 创建字典
  512. /// </summary>
  513. /// <param name="request"></param>
  514. /// <returns></returns>
  515. public async Task<string> CreateDictionaryItemAsync(CreateDictionaryItemRequest request)
  516. {
  517. return await _deviceInfoDBServiceProxy.CreateDictionaryItemAsync(new CreateDictionaryItemDBRequest
  518. {
  519. Data = new DictionaryDTO { DictionaryType = request.DictionaryType, Value = request.DictionaryItemValue, ParentCode = request.ParentCode },
  520. ExtensionData = string.Empty
  521. });
  522. }
  523. /// <summary>
  524. /// 查找设备型号所有字典项
  525. /// </summary>
  526. /// <param name="request"></param>
  527. /// <returns></returns>
  528. public async Task<List<DictionaryDTO>> FindDeviceModelItemsAsync(FindDeviceModelItemsRequest request)
  529. {
  530. var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
  531. {
  532. DictionaryType = (int)request.DictionaryType,
  533. ParentCode = request.DeviceTypeCode
  534. });
  535. return dictionaryDOList;
  536. }
  537. /// <summary>
  538. /// 查找设备类型所有字典项
  539. /// </summary>
  540. /// <param name="request"></param>
  541. /// <returns></returns>
  542. public async Task<List<DictionaryDTO>> FindDeviceTypeItemsAsync(FindDeviceTypeItemsRequest request)
  543. {
  544. var dictionaryDOList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest
  545. {
  546. DictionaryType = (int)request.DictionaryType
  547. });
  548. return dictionaryDOList;
  549. }
  550. /// <summary>
  551. /// 根据组织编码查询所属全部设备信息
  552. /// </summary>
  553. /// <param name="request"></param>
  554. /// <returns></returns>
  555. public async Task<List<DeviceExtendInfoDTO>> FindDevicesByOrganizationCodeAsync(FindDevicesByOrganizationCodeRequest request)
  556. {
  557. var result = new List<DeviceExtendInfoDTO>();
  558. var deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(request.OrganizationCode);
  559. if (deviceInfoDOList?.Count > 0)
  560. {
  561. //根据机构编号查询机构名称
  562. var organizationCode = deviceInfoDOList.FindAll(c => !string.IsNullOrEmpty(c.OrganizationCode)).Select(c => c.OrganizationCode).FirstOrDefault() ?? string.Empty;
  563. var organization = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = organizationCode });
  564. var organizationName = organization?.OrganizationName ?? string.Empty;
  565. //根据机构编号查询科室名称
  566. var organizationFilter = new Dictionary<string, string>();
  567. organizationFilter.Add("RootCode", organizationCode);
  568. var organizations = await _organizationDBService.GetOrganizationPageAsync((new PageFilterRequest { CurrentPage = 1, PageSize = 999999, Filter = organizationFilter, IsFuzzy = false }));
  569. var deviceCodes = deviceInfoDOList.Select(x => x.DeviceCode).ToList();
  570. var deviceTokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest { ClientIds = deviceCodes });
  571. var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
  572. foreach (var c in deviceInfoDOList)
  573. {
  574. var deviceTypeModel = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == c.DeviceType);
  575. result.Add(new DeviceExtendInfoDTO
  576. {
  577. DepartmentName = organizations.PageData.FirstOrDefault(o => o.OrganizationCode == c.DepartmentCode)?.OrganizationName,
  578. OrganizationName = organizationName,
  579. IsOnline = deviceTokens.FirstOrDefault(x => x.ClientId == c.DeviceCode)?.IsOnline ?? false,
  580. DeviceCode = c.DeviceCode,
  581. SerialNumber = c.SerialNumber,
  582. Name = c.Name,
  583. Description = c.Description,
  584. DeviceModel = c.DeviceModel,
  585. DeviceType = c.DeviceType,
  586. HeadPicUrl = c.HeadPicUrl,
  587. DeviceSoftwareVersion = c.DeviceSoftwareVersion,
  588. SDKSoftwareVersion = c.SDKSoftwareVersion,
  589. OrganizationCode = c.OrganizationCode,
  590. DepartmentCode = c.DepartmentCode,
  591. ShortCode = c.ShortCode,
  592. LanguageConfigs = deviceTypeModel?.LanguageConfigs
  593. });
  594. }
  595. }
  596. return result;
  597. }
  598. public Task<DeviceInfoDTO> CreateDeviceInfoAsync(CreateDeviceRequest request)
  599. {
  600. throw new NotImplementedException();
  601. }
  602. public async Task<List<SelectItemDTO>> GetPersonDeviceDropdownListAsync(TokenRequest request)
  603. {
  604. //验证
  605. var userCode = await GetClientIdByTokenAsync(request.Token);
  606. //查询用户是否存在
  607. var userInfoDO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  608. if (userInfoDO == null)
  609. {
  610. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  611. }
  612. var result = new List<SelectItemDTO>();
  613. //查询用户的医院是否存在
  614. if (string.IsNullOrEmpty(userInfoDO.OrganizationCode))
  615. {
  616. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  617. }
  618. var deviceInfoDOList = new List<DeviceInfoDTO>();
  619. if (userInfoDO.IsDirector)
  620. {
  621. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
  622. }
  623. else if (!userInfoDO.RoleCodes.Contains("Role_ExpertAssistant"))
  624. {
  625. //查询用户绑定的设备
  626. if (userInfoDO.BindDevices == null || userInfoDO.BindDevices.Count <= 0)
  627. {
  628. return result;
  629. }
  630. //根据用户名下的设备id查询所有的设备信息
  631. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(userInfoDO.BindDevices);
  632. }
  633. else
  634. {
  635. var experts = await _userServiceProxy.GetBindExpertsAsync(userCode);
  636. if (experts.Any())
  637. {
  638. var bindDeviceCodes = experts.SelectMany(x => x.BindDevices ?? new List<string>()).Distinct().ToList();
  639. if (bindDeviceCodes.Any())
  640. {
  641. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByCodeListAsync(bindDeviceCodes);
  642. }
  643. }
  644. else
  645. {
  646. deviceInfoDOList = await _deviceInfoDBServiceProxy.FindDeviceInfoListByOrganizationCodeAsync(userInfoDO.RootOrganizationCode);
  647. }
  648. }
  649. if (deviceInfoDOList?.Count > 0)
  650. {
  651. result = deviceInfoDOList.Select(c => new SelectItemDTO()
  652. {
  653. Key = c.DeviceCode,
  654. Value = c.Name
  655. }).ToList();
  656. }
  657. return result;
  658. }
  659. /// <summary>
  660. /// 设备端调用,查询获取服务器配置信息接口
  661. /// </summary>
  662. /// <param name="request">Token验证</param>
  663. /// <returns>服务器配置信息结果:key:字段,value:数据值,复杂类型可为json</returns>
  664. public async Task<DeviceServerSettingResult> QueryServerConfigAsync(TokenRequest request)
  665. {
  666. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  667. var deviceInfo = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  668. if (deviceInfo == null || string.IsNullOrWhiteSpace(deviceInfo.DeviceCode))
  669. {
  670. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  671. }
  672. var org = new OrganizationDTO();
  673. if (!string.IsNullOrWhiteSpace(deviceInfo.OrganizationCode))
  674. {
  675. org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = deviceInfo.OrganizationCode });
  676. if (org == null)
  677. {
  678. org = new OrganizationDTO();
  679. }
  680. }
  681. var dictionary = new Dictionary<string, string>();
  682. //定义配置字段 并扩充字段,返回数据可持续更新接口文档,如果数据是复杂类型可以转成json
  683. //TODO 配置信息: 直播配置、存储配置、
  684. //存储上传图像或者视频是 是否本地上传缩略图
  685. var isUploadThumbnail = ConfigurationManager.RemedicalSettings.IsUploadThumbnail;
  686. dictionary.Add("IsUploadThumbnail", isUploadThumbnail.ToString());
  687. dictionary.Add("PatientType", org.PatientType.ToString());
  688. dictionary.Add("HeartRateSeconds", _heartRateSeconds.ToString());
  689. dictionary.Add("NotificationUrl", _webSocketUrl);
  690. dictionary.Add("MergedChannel", deviceInfo.MergedChannel.ToString());
  691. dictionary.Add("LiveConsultationRateSeconds", _liveConsultationRateSeconds.ToString());
  692. var result = new DeviceServerSettingResult()
  693. {
  694. ServerConfigList = dictionary,
  695. IsUploadThumbnail = isUploadThumbnail,
  696. PatientType = org.PatientType,
  697. HeartRateSeconds = _heartRateSeconds,
  698. NotificationUrl = _webSocketUrl,
  699. LiveConsultationRateSeconds = _liveConsultationRateSeconds,
  700. MergedChannel = deviceInfo.MergedChannel,
  701. MergedVideoOutputWidth = deviceInfo.MergedVideoOutputWidth,
  702. MergedVideoOutputHeight = deviceInfo.MergedVideoOutputHeight,
  703. IsSelfRtcService = _isRTCSelf,
  704. RemoteControlAskTimeoutSec = _remoteControlAskTimeoutSec
  705. };
  706. return result;
  707. }
  708. /// <summary>
  709. /// 添加或迁移设备到医院请求
  710. /// </summary>
  711. /// <param name="request"></param>
  712. /// <returns></returns>
  713. public async Task<bool> AddDeviceToOrgAsync(AddDeviceToOrgRequest request)
  714. {
  715. var shortCode = request.UniqueCode;
  716. #region Params Check
  717. var userCode = await GetClientIdByTokenAsync(request.Token);
  718. if (string.IsNullOrEmpty(shortCode))
  719. {
  720. ThrowCustomerException(CustomerRpcCode.UniqueCodeIsEmpty, "UniqueCode is empty");
  721. }
  722. var device = await _deviceInfoDBServiceProxy.FindDeviceInfoByShortCodeAsync(shortCode);
  723. if (device == null)
  724. {
  725. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  726. }
  727. var oldOrg = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = device.OrganizationCode });
  728. if (oldOrg == null || string.IsNullOrWhiteSpace(oldOrg.OrganizationCode))
  729. {
  730. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  731. }
  732. //用户
  733. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  734. if (userDTO == null)
  735. {
  736. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  737. }
  738. if (!userDTO.IsDirector)
  739. {
  740. ThrowCustomerException(CustomerRpcCode.NotOrgAdmin, "not org admin");
  741. }
  742. var org = await _organizationDBService.GetOrganizationDetailAsync(new GetOrganizationDBRequest { OrganizationCode = userDTO.OrganizationCode });
  743. if (org == null || string.IsNullOrWhiteSpace(org.OrganizationCode))
  744. {
  745. ThrowCustomerException(CustomerRpcCode.OrganizationNotExist, "Org does not exist");
  746. }
  747. #endregion
  748. try
  749. {
  750. var newOrgode = org.OrganizationCode;
  751. //设备更新医院
  752. if (!string.IsNullOrEmpty(device.DepartmentCode))
  753. {
  754. device.DepartmentCode = "";
  755. }
  756. if (!string.IsNullOrEmpty(device.Name))
  757. {
  758. device.Name = "";
  759. }
  760. device.HeadPicUrl = "";
  761. device.Description = "";
  762. device.IsAutoShared = false;
  763. device.OrganizationCode = newOrgode;
  764. bool success = await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(device.DeviceCode, device, string.Empty, true);
  765. if (success)
  766. {
  767. // 删除已知绑定的用户
  768. var users = await _userServiceProxy.GetUsersByDeviceAsync(device.DeviceCode);
  769. var updateUsers = new List<TableDataItem<UserPasswordDTO>>();
  770. foreach (var user in users)
  771. {
  772. user.BindDevices.Remove(device.DeviceCode);
  773. updateUsers.Add(new TableDataItem<UserPasswordDTO>()
  774. {
  775. Data = user.MappingTo<UserPasswordDTO>(),
  776. });
  777. }
  778. if (updateUsers.Count > 0)
  779. {
  780. var updateUsersDBRequest = new UpdateUsersDBRequest() { Users = updateUsers };
  781. await _userServiceProxy.UpdateUsersAsync(updateUsersDBRequest);
  782. }
  783. if (oldOrg.Isinvented) // 虚拟医院
  784. {
  785. //迁移数据超声机上传检查记录
  786. await _recordsInfoDBService.UpdateRecordsWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
  787. //迁移数据超声机上传病人
  788. await _patientInfoDBService.UpdatePatientWithOrgCodeAsync(new List<string>() { device.DeviceCode }, newOrgode);
  789. }
  790. }
  791. return success;
  792. }
  793. catch (System.Exception ex)
  794. {
  795. Logger.WriteLineError($"AddDeviceToOrgAsync error {ex}");
  796. }
  797. return false;
  798. }
  799. /// <summary>
  800. /// 补齐设备扩展信息
  801. /// </summary>
  802. /// <param name="deviceInfoDOList"></param>
  803. /// <returns></returns>
  804. private async Task<List<DeviceExtendInfoDTO>> MapToExtendDTO(List<DeviceInfoDTO> deviceInfoDOList)
  805. {
  806. var deviceList = new List<DeviceExtendInfoDTO>();
  807. if (deviceInfoDOList != null && deviceInfoDOList.Any())
  808. {
  809. //查询机构
  810. var orgCodes = deviceInfoDOList.Select(x => x.OrganizationCode).ToList();
  811. orgCodes.AddRange(deviceInfoDOList.Select(x => x.DepartmentCode));
  812. var organizations = await _organizationDBService.FindOrganizationListByCodesAsync(orgCodes.Distinct().ToList());
  813. //查询机构负责人
  814. var organizationDirectorCodes = new List<string>();
  815. foreach (var org in organizations)
  816. {
  817. if (org.Directors != null && org.Directors.Any())
  818. {
  819. organizationDirectorCodes.AddRange(org.Directors);
  820. }
  821. }
  822. var organizationDirectors = await _userServiceProxy.FindUserListByUserCodesAsync(organizationDirectorCodes);
  823. var deviceCodes = deviceInfoDOList.Select(x => x.DeviceCode).ToList();
  824. var deviceTokens = await _authenticationService.GetTokenWithClientIdsAsync(new GetTokenWithClientIdsRequest { ClientIds = deviceCodes });
  825. var deviceTypeList = await _deviceInfoDBServiceProxy.FindDictionaryItemsAsync(new FindDictionaryItemsDBRequest { DictionaryType = (int)DictionaryTypeEnum.DeviceType });
  826. foreach (var dto in deviceInfoDOList)
  827. {
  828. var device = dto.MappingTo<DeviceExtendInfoDTO>();
  829. device.IsOnline = deviceTokens.FirstOrDefault(x => x.ClientId == dto.DeviceCode)?.IsOnline ?? false;
  830. device.DepartmentName = organizations.FirstOrDefault(x => x.OrganizationCode == dto.DepartmentCode)?.OrganizationName;
  831. device.LanguageConfigs = deviceTypeList.FirstOrDefault(t => t.DictionaryCode == device.DeviceType)?.LanguageConfigs;
  832. var organization = organizations.FirstOrDefault(x => x.OrganizationCode == dto.OrganizationCode);
  833. if (organization != null)
  834. {
  835. device.OrganizationName = organization.OrganizationName;
  836. if (organization.Directors != null && organization.Directors.Any())
  837. {
  838. var director = organizationDirectors.FirstOrDefault(x => x.UserCode == organization.Directors.FirstOrDefault());
  839. device.OrganizationDirectorCode = director?.UserCode;
  840. device.OrganizationDirectorUserName = director?.UserName;
  841. device.OrganizationDirectorFullName = director?.FullName;
  842. }
  843. }
  844. deviceList.Add(device);
  845. }
  846. }
  847. return deviceList;
  848. }
  849. /// <summary>
  850. /// 补齐设备扩展信息
  851. /// </summary>
  852. /// <param name="deviceInfoDOList"></param>
  853. /// <returns></returns>
  854. private async Task<DeviceExtendInfoDTO> MapToExtendDTO(DeviceInfoDTO deviceInfoDO)
  855. {
  856. var deviceList = await MapToExtendDTO(new List<DeviceInfoDTO> { deviceInfoDO });
  857. return deviceList.FirstOrDefault();
  858. }
  859. /// <summary>
  860. /// 获取设备绑定用户codes
  861. /// </summary>
  862. /// <param name="request">获取设备绑定用户codes请求实体</param>
  863. /// <returns>test01,test02</returns>
  864. public async Task<List<string>> GetDeviceBindUsersCodesAsync(GetDeviceRequest request)
  865. {
  866. //检查设备编码不为空
  867. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  868. {
  869. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  870. }
  871. //查询设备对象
  872. var deviceDb = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(request.DeviceCode);
  873. if (deviceDb == null)
  874. {
  875. ThrowCustomerException(CustomerRpcCode.NoExistDevice, "Device does not exist");
  876. }
  877. var userListResult = await _userServiceProxy.GetUsersByDeviceAsync(request.DeviceCode);
  878. if (userListResult != null && userListResult.Count > 0)
  879. {
  880. return userListResult.Select(u => u.UserCode).ToList();
  881. }
  882. return new List<string>();
  883. }
  884. /// <summary>
  885. /// 查询设备AI应用的状态
  886. /// </summary>
  887. /// <param name="request">请求参数</param>
  888. /// <returns>AI应用集合</returns>
  889. public async Task<List<DiagnosisModuleDTO>> FindDeviceDiagnosisModulesAsync(FindDeviceDiagnosisModulesRequest request)
  890. {
  891. //检查设备编码不为空
  892. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  893. {
  894. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  895. }
  896. return await _diagnosisModuleService.GetDeviceDiagnosisModulesAsync(new GetDeviceDiagnosisModulesDBRequest { DeviceCode = request.DeviceCode });
  897. }
  898. /// <summary>
  899. /// 修改设备AI应用启用状态
  900. /// </summary>
  901. /// <param name="request">修改设备AI应用启用状态请求实体</param>
  902. /// <returns>是否成功</returns>
  903. /// <para>DeviceErrorCodeEnum</para>
  904. public async Task<bool> ModifyDeviceDiagnosisModuleStateAsync(ModifyDeviceDiagnosisModuleStateRequest request)
  905. {
  906. //检查设备编码不为空
  907. if (string.IsNullOrWhiteSpace(request.DeviceCode))
  908. {
  909. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  910. }
  911. if (string.IsNullOrWhiteSpace(request.DiagnosisModule))
  912. {
  913. ThrowCustomerException(CustomerRpcCode.DeviceAIDiagnosisModule, "Required parameter:DeviceCode cannot be empty");
  914. }
  915. var result = await _diagnosisModuleService.UpdateDeviceDiagnosisModuleStateAsync(new UpdateDeviceDiagnosisModuleStateDBRequest
  916. {
  917. DeviceCode = request.DeviceCode,
  918. DiagnosisModule = request.DiagnosisModule,
  919. Enabled = request.Enabled
  920. });
  921. CacheMaintenance.Instance.Get<IDeviceInfosManager>().Remove(request.DeviceCode);
  922. return result;
  923. }
  924. /// <summary>
  925. /// 设备离开会诊房间
  926. /// </summary>
  927. /// <param name="request">设备离开会诊房间请求实体</param>
  928. /// <returns></returns>
  929. public async Task<DeviceLeaveLiveConsultationResult> DeviceLeaveLiveConsultationAsync(DeviceLeaveLiveConsultationRequest request)
  930. {
  931. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  932. var result = new DeviceLeaveLiveConsultationResult
  933. {
  934. Success = false,
  935. };
  936. return result;
  937. }
  938. /// <summary>
  939. /// 通用异常处理方法
  940. /// </summary>
  941. /// <param name="customerRpcCodeEnum">异常标识码</param>
  942. /// <param name="msg">异常信息</param>
  943. /// <param name="internalMessage">内部异常信息,非必填</param>
  944. private void ThrowCustomerException(CustomerRpcCode customerRpcCodeEnum, string msg, string internalMessage = null)
  945. {
  946. ThrowRpcException((int)customerRpcCodeEnum, msg, internalMessage);
  947. }
  948. /// <summary>
  949. /// 上报设备画面尺寸相关信息
  950. /// </summary>
  951. /// <param name="request"></param>
  952. /// <docFirstDirectory>设备端API</docFirstDirectory>
  953. /// <docSecondDirectory>实时会诊服务接口</docSecondDirectory>
  954. /// <docThirdDirectory>会诊</docThirdDirectory>
  955. /// <returns></returns>
  956. public async Task<ReportVideoDeviceInfoResult> ReportVideoDeviceInfoAsync(ReportVideoDeviceInfoRequest request)
  957. {
  958. var result = new ReportVideoDeviceInfoResult();
  959. if (request.VideoDeviceInfos == null || request.VideoDeviceInfos.Count == 0)
  960. {
  961. //视屏设备画面信息为空
  962. ThrowCustomerException(CustomerRpcCode.VideoDeviceInfosEmpty, "VideoDeviceInfosEmpty");
  963. }
  964. if (request.VideoDeviceInfos.Any(x => string.IsNullOrWhiteSpace(x.VideoDeviceId)))
  965. {
  966. //视屏设备ID为空
  967. ThrowCustomerException(CustomerRpcCode.VideoDeviceIdEmpty, "VideoDeviceIdEmpty");
  968. }
  969. var videoDeviceIdCount = request.VideoDeviceInfos.Select(x => x.VideoDeviceId).Distinct().Count();
  970. if (videoDeviceIdCount < request.VideoDeviceInfos.Count)
  971. {
  972. //视屏设备ID重复
  973. ThrowCustomerException(CustomerRpcCode.VideoDeviceIdRepeatError, "VideoDeviceIdRepeatError");
  974. }
  975. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  976. var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  977. var videoDeviceInfos = new List<VideoDeviceDTO>();
  978. foreach (var video in request.VideoDeviceInfos)
  979. {
  980. var videoDeviceInfo = new VideoDeviceDTO
  981. {
  982. VideoDeviceId = video.VideoDeviceId,
  983. VideoDeviceSourceType = video.VideoDeviceSourceType,
  984. Width = video.Width,
  985. Height = video.Height,
  986. OutputWidth = video.Width,
  987. OutputHeight = video.Height
  988. };
  989. if (deviceDTO.VideoDeviceInfos != null && deviceDTO.VideoDeviceInfos.Any(x => x.VideoDeviceId == video.VideoDeviceId))
  990. {
  991. var oldVideo = deviceDTO.VideoDeviceInfos.FirstOrDefault(x => x.VideoDeviceId == video.VideoDeviceId);
  992. videoDeviceInfo.OutputWidth = oldVideo.OutputWidth;
  993. videoDeviceInfo.OutputHeight = oldVideo.OutputHeight;
  994. videoDeviceInfo.VideoFps = oldVideo.VideoFps;
  995. videoDeviceInfo.VideoBitrate = oldVideo.VideoBitrate;
  996. videoDeviceInfo.MinVideoBitrate = oldVideo.MinVideoBitrate;
  997. }
  998. videoDeviceInfos.Add(videoDeviceInfo);
  999. }
  1000. deviceDTO.VideoDeviceInfos = videoDeviceInfos;
  1001. var updateVideoDeviceInfosDBRequest = new UpdateVideoDeviceInfosDBRequest
  1002. {
  1003. DeviceCode = deviceDTO.DeviceCode,
  1004. LiveOpened = request.LiveOpened,
  1005. VideoDeviceInfos = videoDeviceInfos
  1006. };
  1007. await _deviceInfoDBServiceProxy.UpdateVideoDeviceInfosAsync(updateVideoDeviceInfosDBRequest);
  1008. CacheMaintenance.Instance.Get<IDeviceInfosManager>().Remove(deviceDTO.DeviceCode);
  1009. result.Success = true;
  1010. return result;
  1011. }
  1012. /// <summary>
  1013. /// 查找有效设备总数量
  1014. /// </summary>
  1015. /// <returns></returns>
  1016. public async Task<long> GetActiveDeviceCount()
  1017. {
  1018. return await _deviceInfoDBServiceProxy.GetActiveDeviceCount();
  1019. }
  1020. /// <summary>
  1021. /// 设备发送调参初始化数据
  1022. /// </summary>
  1023. /// <param name="request">调参数据请求</param>
  1024. /// <returns></returns>
  1025. public async Task<bool> SendControlParameterByDeviceAsync(SendControlParameterByDeviceRequest request)
  1026. {
  1027. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  1028. var userCode = request.ControlUserCode;
  1029. //发送控制人通知
  1030. if (string.IsNullOrWhiteSpace(userCode))
  1031. {
  1032. ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
  1033. }
  1034. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  1035. if (userDTO == null)
  1036. {
  1037. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  1038. }
  1039. var notify = new DeviceParametersNotification()
  1040. {
  1041. DeviceCode = deviceCode,
  1042. IsResponse = true
  1043. };
  1044. var cacheControllingParameter = new CacheControllingParameter()
  1045. {
  1046. Code = deviceCode,
  1047. ProbeApplication = Newtonsoft.Json.JsonConvert.SerializeObject(request.ProbeApplication),
  1048. Parameter = Newtonsoft.Json.JsonConvert.SerializeObject(request.Parameter),
  1049. };
  1050. _controllingParameterDevices.AddOrUpdate(deviceCode,(k)=>cacheControllingParameter,(k,exist)=>{
  1051. return cacheControllingParameter;
  1052. });
  1053. var notificationRequest = new SendNotificationRequest()
  1054. {
  1055. ClientId = userCode,
  1056. Message = notify,
  1057. JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
  1058. NotificationType = notify.NotificationType,
  1059. TransactionType = TransactionTypeEnum.ControlParameter,
  1060. RelevanceCode = userCode,
  1061. ReceiverType = ApplicantTypeEnum.Client
  1062. };
  1063. await _notificationService.PostMessageAsync(notificationRequest);
  1064. return true;
  1065. }
  1066. /// <summary>
  1067. /// 获取设备参数调节数据请求
  1068. /// </summary>
  1069. /// <param name="request"></param>
  1070. /// <returns></returns>
  1071. public async Task<DeviceControlParameterDataDTO> GetControlParametersAsync(GetControlParametersRequest request)
  1072. {
  1073. var deviceCode = request.DeviceCode;
  1074. //检查设备编码不为空
  1075. if (string.IsNullOrWhiteSpace(deviceCode))
  1076. {
  1077. ThrowCustomerException(CustomerRpcCode.DeviceCodeIsEmpty, "Required parameter:DeviceCode cannot be empty");
  1078. }
  1079. _controllingParameterDevices.TryGetValue(deviceCode,out var controlParameterData);
  1080. if (controlParameterData != null)
  1081. {
  1082. return new DeviceControlParameterDataDTO()
  1083. {
  1084. DeviceCode = controlParameterData.Code,
  1085. ProbeApplication = controlParameterData.ProbeApplication,
  1086. Parameter = controlParameterData.Parameter
  1087. };
  1088. }
  1089. return null;
  1090. }
  1091. /// <summary>
  1092. /// 用户进入设备直播房间
  1093. /// </summary>
  1094. /// <param name="request">用户进入设备直播房间请求实体</param>
  1095. /// <returns></returns>
  1096. public async Task<JoinDeviceLiveRoomResult> JoinDeviceLiveRoomAsync(JoinDeviceLiveRoomRequest request)
  1097. {
  1098. var userInfo = await _authenticationService.GetTokenAsync(request);
  1099. var deviceCode = request.DeviceCode;
  1100. var liveRooms = await _rtcService.GetLiveRoomsByDeviceCodeAsync(new GetLiveRoomsByDeviceCodeRequest
  1101. {
  1102. DeviceCode = deviceCode
  1103. });
  1104. var liveRoom = liveRooms?.FirstOrDefault(x => x.Status == LiveRoomStatus.Initiating);
  1105. LiveMemberDTO deviceMemberInfo;
  1106. if (liveRoom != null)
  1107. {
  1108. //设备正在推流
  1109. deviceMemberInfo = liveRoom.Members.FirstOrDefault(x => x.Code == deviceCode);
  1110. if (deviceMemberInfo?.Status == LiveMemberStatus.Joined)
  1111. {
  1112. return new JoinDeviceLiveRoomResult
  1113. {
  1114. RoomNo = liveRoom.RoomNo,
  1115. RtmpUrl = deviceMemberInfo.LiveData.RtmpPullUrl,
  1116. };
  1117. }
  1118. }
  1119. //新增或更新设备直播间 TODO
  1120. var rtcRoomResult = await _rtcService.GetRoomIdAsync(new GetRoomIdRequest
  1121. {
  1122. UniqueId = deviceCode,
  1123. });
  1124. var rtcRoomId = (int)rtcRoomResult.RoomId;
  1125. var initiateResult = await _rtcService.InitiateLiveAsync(new InitiateLiveRequest
  1126. {
  1127. RoomId = deviceCode,
  1128. InitiatorCode = deviceCode,
  1129. IntegerRoomId = rtcRoomId
  1130. });
  1131. //添加观众
  1132. var addOrUpdateViewerResult = await _rtcService.SaveViewerAsync(new SaveViewerRequest
  1133. {
  1134. LiveRoomCode = initiateResult.RoomId,
  1135. UserCode = userInfo.ClientId,
  1136. UserName = userInfo.AccountName,
  1137. });
  1138. //通知设备推流
  1139. deviceMemberInfo = initiateResult.Members.FirstOrDefault(x => x.Code == deviceCode);
  1140. var message = new StartLiveToDeviceNotification
  1141. {
  1142. LiveRoomCode = initiateResult.RoomId,
  1143. RoomNo = initiateResult.RoomNo,
  1144. AppId = _sdkAppId,
  1145. // MergedChannel = deviceMemberInfo.MergedChannel,
  1146. // MergedVideoOutputWidth = deviceMemberInfo.MergedVideoOutputWidth,
  1147. // MergedVideoOutputHeight = deviceMemberInfo.MergedVideoOutputHeight,
  1148. // VideoDeviceOutputList = deviceMemberInfo.VideoDeviceInfos.ToList(),
  1149. };
  1150. await BroadcastNotificationAsync(liveRoom.RoomId, new List<string> { deviceCode }, message);
  1151. return new JoinDeviceLiveRoomResult
  1152. {
  1153. RoomNo = initiateResult.RoomNo,
  1154. RtmpUrl = deviceMemberInfo.LiveData.RtmpPullUrl,
  1155. ReportStateIntervalSeconds = _reportStateIntervalSeconds,
  1156. };
  1157. }
  1158. /// <summary>
  1159. /// 用户离开设备直播房间
  1160. /// </summary>
  1161. /// <param name="request">用户离开设备直播房间请求实体</param>
  1162. /// <returns></returns>
  1163. public async Task<bool> LeaveDeviceLiveRoomAsync(LeaveDeviceLiveRoomRequest request)
  1164. {
  1165. var userInfo = await _authenticationService.GetTokenAsync(request);
  1166. var userCode = userInfo.ClientId;
  1167. var rtcRoomId = request.RoomNo;
  1168. var liveRooms = await _rtcService.GetLiveRoomsByRtcRoomIdAsync(new GetLiveRoomsByRtcRoomIdRequest
  1169. {
  1170. RtcRoomId = rtcRoomId
  1171. });
  1172. var liveRoom = liveRooms?.FirstOrDefault(x => x.Status == LiveRoomStatus.Initiating);
  1173. if (liveRoom != null)
  1174. {
  1175. var deviceCode = liveRoom.DeviceInfos?.FirstOrDefault()?.Code;
  1176. //移除观众
  1177. var removeViewerResult = await _rtcService.RemoveViewerAsync(new RemoveViewerRequest
  1178. {
  1179. LiveRoomCode = liveRoom.RoomId,
  1180. UserCode = userInfo.ClientId,
  1181. });
  1182. var expireTime = DateTime.UtcNow.AddSeconds(_reportStateTimeout * -1);
  1183. if (!liveRoom.ViewerInfos.Any(x => x.UserCode != userCode && x.LastReportTime >= expireTime) && !string.IsNullOrWhiteSpace(deviceCode))
  1184. {
  1185. //关闭直播 to device
  1186. var message = new CloseLiveToDeviceNotification
  1187. {
  1188. LiveRoomCode = liveRoom.RoomId,
  1189. };
  1190. await BroadcastNotificationAsync(liveRoom.RoomId, new List<string> { deviceCode }, message);
  1191. }
  1192. }
  1193. return true;
  1194. }
  1195. /// <summary>
  1196. /// 上报观看直播状态
  1197. /// </summary>
  1198. /// <param name="request">上报观看直播状态请求实体</param>
  1199. /// <returns></returns>
  1200. public async Task<bool> ReportLiveViewStateAsync(ReportLiveViewStateRequest request)
  1201. {
  1202. var userInfo = await _authenticationService.GetTokenAsync(request);
  1203. var rtcRoomId = request.RoomNo;
  1204. var liveRooms = await _rtcService.GetLiveRoomsByRtcRoomIdAsync(new GetLiveRoomsByRtcRoomIdRequest
  1205. {
  1206. RtcRoomId = rtcRoomId
  1207. });
  1208. var liveRoom = liveRooms?.FirstOrDefault(x => x.Status == LiveRoomStatus.Initiating);
  1209. if (liveRoom != null)
  1210. {
  1211. //添加观众
  1212. var addOrUpdateViewerResult = await _rtcService.SaveViewerAsync(new SaveViewerRequest
  1213. {
  1214. LiveRoomCode = liveRoom.RoomId,
  1215. UserCode = userInfo.ClientId,
  1216. UserName = userInfo.AccountName,
  1217. });
  1218. }
  1219. return true;
  1220. }
  1221. /// <summary>
  1222. /// 上报直播状态
  1223. /// </summary>
  1224. /// <param name="request">上报直播状态请求实体</param>
  1225. /// <returns></returns>
  1226. public async Task<bool> ReportLiveStateAsync(ReportLiveStateRequest request)
  1227. {
  1228. var tokenInfo = await _authenticationService.GetTokenAsync(request);
  1229. var deviceCode = tokenInfo.ClientId;
  1230. switch (request.LiveState)
  1231. {
  1232. case DeviceLiveStateEnum.Error:
  1233. case DeviceLiveStateEnum.Warning:
  1234. Logger.WriteLineWarn($"DeviceService ReportLiveStateAsync, [{tokenInfo.AccountType.ToString()}]{tokenInfo.AccountName}, state:{request.LiveState.ToString()}, message:{request.Message}");
  1235. break;
  1236. default:
  1237. Logger.WriteLineInfo($"DeviceService ReportLiveStateAsync, [{tokenInfo.AccountType.ToString()}]{tokenInfo.AccountName}, state:{request.LiveState.ToString()}, message:{request.Message}");
  1238. break;
  1239. }
  1240. if (request.LiveState == DeviceLiveStateEnum.Pushing || request.LiveState == DeviceLiveStateEnum.Closed)
  1241. {
  1242. var rtcRoomId = request.RoomNo;
  1243. var liveRooms = await _rtcService.GetLiveRoomsByRtcRoomIdAsync(new GetLiveRoomsByRtcRoomIdRequest
  1244. {
  1245. RtcRoomId = rtcRoomId
  1246. });
  1247. var liveRoom = liveRooms?.FirstOrDefault(x => x.Status == LiveRoomStatus.Initiating);
  1248. if (liveRoom != null)
  1249. {
  1250. var expireTime = DateTime.UtcNow.AddSeconds(_reportStateTimeout * -1);
  1251. var validViewers = liveRoom.ViewerInfos.Where(x => x.LastReportTime >= expireTime)?.ToList() ?? new List<LiveViewerDTO>();
  1252. if (request.LiveState == DeviceLiveStateEnum.Closed && validViewers.Any())
  1253. {
  1254. //关闭直播 to users
  1255. var message = new DeviceLiveFinishedNotification
  1256. {
  1257. LiveRoomCode = liveRoom.RoomId,
  1258. };
  1259. await BroadcastNotificationAsync(liveRoom.RoomId, validViewers.Select(x => x.UserCode).ToList(), message);
  1260. }
  1261. if (request.LiveState == DeviceLiveStateEnum.Pushing && !validViewers.Any())
  1262. {
  1263. //关闭直播 to device
  1264. var message = new CloseLiveToDeviceNotification
  1265. {
  1266. LiveRoomCode = liveRoom.RoomId,
  1267. };
  1268. await BroadcastNotificationAsync(liveRoom.RoomId, new List<string> { deviceCode }, message);
  1269. }
  1270. }
  1271. }
  1272. return await Task.FromResult(true);
  1273. }
  1274. /// <summary>
  1275. /// 获取实时音视频参数
  1276. /// </summary>
  1277. /// <param name="request">获取实时音视频参数请求实体</param>
  1278. /// <returns></returns>
  1279. public async Task<CreateLiveRoomInfoResult> CreateLiveRoomInfoAsync(CreateLiveRoomInfoRequest request)
  1280. {
  1281. Logger.WriteLineInfo($"DeviceService CreateLiveRoomInfoAsync, DeviceUniqueCode:{request.DeviceUniqueCode}, DeviceType:{request.DeviceType}, DeviceModel:{request.DeviceModel}, SoftwareVersion:{request.SoftwareVersion}");
  1282. var userCode = Guid.NewGuid().ToString("N");
  1283. var getUserSignRequest = new GetUserSignRequest
  1284. {
  1285. UserId = userCode,
  1286. };
  1287. var getUserSignResult = await _rtcService.GetUserSignAsync(getUserSignRequest);
  1288. var userSign = getUserSignResult.UserSign;
  1289. var getRoomIdRequest = new GetRoomIdRequest
  1290. {
  1291. UniqueId = userCode,
  1292. };
  1293. var getRoomIdResult = await _rtcService.GetRoomIdAsync(getRoomIdRequest);
  1294. var intRoomNo = (int)getRoomIdResult.RoomId;
  1295. Logger.WriteLineInfo($"DeviceService CreateLiveRoomInfoAsync, DeviceUniqueCode:{request.DeviceUniqueCode}, UserCode:{userCode}, roomNo:{intRoomNo}");
  1296. return new CreateLiveRoomInfoResult
  1297. {
  1298. IsTrtc = !_isRTCSelf,
  1299. UserCode = userCode,
  1300. UserSign = userSign,
  1301. AppId = _sdkAppId,
  1302. RoomNo = intRoomNo,
  1303. };
  1304. }
  1305. private async Task<bool> BroadcastNotificationAsync(string roomId, IList<string> clientIds, NotificationDTO message)
  1306. {
  1307. var broadcastNotificationRequest = new BroadcastRoomNotificationRequest
  1308. {
  1309. RoomId = roomId,
  1310. ClientIds = clientIds,
  1311. Message = message,
  1312. TransactionType = TransactionTypeEnum.Live,
  1313. RelevanceCode = roomId,
  1314. ReceiverType = ApplicantTypeEnum.Client,
  1315. WSConnectType = WSConnectTypeEnum.Default
  1316. };
  1317. return await _rtcService.BroadcastRoomNotificationAsync(broadcastNotificationRequest);
  1318. }
  1319. /// <summary>
  1320. /// 拒绝远程控制
  1321. /// </summary>
  1322. /// <param name="request"></param>
  1323. /// <returns></returns>
  1324. public async Task<bool> RejectRemoteControl(RemoteControlRequest request)
  1325. {
  1326. string deviceCode = await GetClientIdByTokenAsync(request.Token);
  1327. string userCode = request.ControlUserCode;
  1328. //发送控制人通知
  1329. if (string.IsNullOrWhiteSpace(userCode))
  1330. {
  1331. ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
  1332. }
  1333. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  1334. if (userDTO == null)
  1335. {
  1336. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  1337. }
  1338. var notify = new DeviceRejectRemoteControlNotification()
  1339. {
  1340. DeviceCode = deviceCode,
  1341. };
  1342. var notificationRequest = new SendNotificationRequest()
  1343. {
  1344. ClientId = userCode,
  1345. Message = notify,
  1346. JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
  1347. NotificationType = notify.NotificationType,
  1348. TransactionType = TransactionTypeEnum.RemoteControl,
  1349. RelevanceCode = userCode,
  1350. ReceiverType = ApplicantTypeEnum.Client
  1351. };
  1352. await _notificationService.PostMessageAsync(notificationRequest);
  1353. //更改房间调参状态
  1354. // var getRoomRequest = new FindRoomByCodeRequest { DeviceCode = deviceCode, UserCode = userCode };
  1355. // var room = await _rtcService.GetLiveRoomByCodeAsync(getRoomRequest);
  1356. // if (room != null && !string.IsNullOrWhiteSpace(room.RoomId))
  1357. // {
  1358. // var changeControllingParameterStateRequest = new SetLiveParamsRequest { UserCode = userCode, RoomId = room.RoomId, IsControllingParameter = false };
  1359. // await _rtcService.ChangeControllingParameterStateAsync(changeControllingParameterStateRequest);
  1360. // }
  1361. var roomRequest = new ChangeConsultationControllingStateRequest { DeviceCode = deviceCode, UserCode = userCode, IsControllingParameter = false };
  1362. await _liveConsultationService.ChangeConsultationControllingStateAsync(roomRequest);
  1363. return true;
  1364. }
  1365. /// <summary>
  1366. /// 断开远程控制
  1367. /// </summary>
  1368. /// <param name="request"></param>
  1369. /// <returns></returns>
  1370. public async Task<bool> DisconnectRemoteControl(RemoteControlRequest request)
  1371. {
  1372. string deviceCode = await GetClientIdByTokenAsync(request.Token);
  1373. string userCode = request.ControlUserCode;
  1374. //发送控制人通知
  1375. if (string.IsNullOrWhiteSpace(userCode))
  1376. {
  1377. ThrowCustomerException(CustomerRpcCode.UsercodeIsEmpty, "User code is empty");
  1378. }
  1379. var userDTO = await _userServiceProxy.FindUserByCodeAsync(userCode);
  1380. if (userDTO == null)
  1381. {
  1382. ThrowCustomerException(CustomerRpcCode.UserNotExistError, "User does not exist");
  1383. }
  1384. var notify = new DeviceDisconnectRemoteControlNotification()
  1385. {
  1386. DeviceCode = deviceCode,
  1387. };
  1388. var notificationRequest = new SendNotificationRequest()
  1389. {
  1390. ClientId = userCode,
  1391. Message = notify,
  1392. JsonMessage = Newtonsoft.Json.JsonConvert.SerializeObject(notify),
  1393. NotificationType = notify.NotificationType,
  1394. TransactionType = TransactionTypeEnum.RemoteControl,
  1395. RelevanceCode = userCode,
  1396. ReceiverType = ApplicantTypeEnum.Client
  1397. };
  1398. await _notificationService.PostMessageAsync(notificationRequest);
  1399. //更改房间调参状态
  1400. // var getRoomRequest = new FindRoomByCodeRequest { DeviceCode = deviceCode, UserCode = userCode };
  1401. // var room = await _rtcService.GetLiveRoomByCodeAsync(getRoomRequest);
  1402. // if (room != null && !string.IsNullOrWhiteSpace(room.RoomId))
  1403. // {
  1404. // var changeControllingParameterStateRequest = new SetLiveParamsRequest { UserCode = userCode, RoomId = room.RoomId, IsControllingParameter = false };
  1405. // await _rtcService.ChangeControllingParameterStateAsync(changeControllingParameterStateRequest);
  1406. // }
  1407. var roomRequest = new ChangeConsultationControllingStateRequest { DeviceCode = deviceCode, UserCode = userCode, IsControllingParameter = false };
  1408. await _liveConsultationService.ChangeConsultationControllingStateAsync(roomRequest);
  1409. return true;
  1410. }
  1411. public async Task<bool> UploadConsultationDataAsync(UploadConsultationDataRequest request)
  1412. {
  1413. var deviceInfo = await GetDeviceByTokenAsync(request);
  1414. var consultationCode = request.ConsultationCode;
  1415. if (string.IsNullOrWhiteSpace(consultationCode))
  1416. {
  1417. ThrowCustomerException(CustomerRpcCode.ConsultationCodeIsEmpty, "ConsultationCode is empty");
  1418. }
  1419. if (string.IsNullOrWhiteSpace(request.FileToken))
  1420. {
  1421. ThrowCustomerException(CustomerRpcCode.FileTokenIsEmpty, "FileToken is empty");
  1422. }
  1423. var findConsultationRequest = new ConsultationRecordCodeDBRequest { Code = consultationCode };
  1424. var consultationRecord = await _consultationRecordDBService.FindConsultationRecordByCodeAsync(findConsultationRequest);
  1425. if (consultationRecord == null || string.IsNullOrWhiteSpace(consultationRecord.ConsultationCode))
  1426. {
  1427. ThrowCustomerException(CustomerRpcCode.ConsultationNotExisted, "Consultation not exist");
  1428. }
  1429. var dataDTO = new RemedicalInfoDTO();
  1430. dataDTO.DeviceCode = deviceInfo.DeviceCode;
  1431. dataDTO.RecordCode = consultationRecord.ConsultationCode;
  1432. dataDTO.ApplicationCategory = request.ApplicationCategory;
  1433. dataDTO.Application = request.Application;
  1434. dataDTO.TerminalImages = new TerminalImageDTO();
  1435. var originImageUrl = request.FileToken;
  1436. dataDTO.TerminalImages.OriginImageUrl = originImageUrl;//源站地址
  1437. dataDTO.TerminalImages.ImageUrl = request.FileToken.ToUrlToken();//CDN 地址
  1438. dataDTO.TerminalImages.PreviewUrl = request.PreviewFileToken.ToUrlToken();
  1439. dataDTO.TerminalImages.CoverImageUrl = request.CoverImageToken.ToUrlToken();
  1440. dataDTO.TerminalImages.ImageSize = request.FileSize;
  1441. dataDTO.FileDataType = request.FileDataType;
  1442. dataDTO.MeasuredResult = request.MeasuredResult;
  1443. dataDTO.CommentResult = request.CommentResult;
  1444. dataDTO.BusinessType = BusinessTypeEnum.LiveConsultation;
  1445. dataDTO.RemedicalCode = await _remedicalDBService.InsertRemedicalInfoAsync(new CreateRemedicalInfoDBRequest { Data = dataDTO });
  1446. //更新会诊记录
  1447. if (consultationRecord.ConsultationFileList == null)
  1448. {
  1449. consultationRecord.ConsultationFileList = new List<ConsultationFileDTO>();
  1450. }
  1451. var consultationFileDTO = new ConsultationFileDTO
  1452. {
  1453. SourceUrl = originImageUrl,
  1454. CoverImageUrl = dataDTO.TerminalImages.CoverImageUrl,
  1455. PreviewImageUrl = dataDTO.TerminalImages.PreviewUrl,
  1456. FileDataType = request.FileDataType,
  1457. CreateTime = DateTime.UtcNow,
  1458. ConsultationFileType = ConsultationFileTypeEnum.UltrasoundImage,
  1459. RemedicalCode = dataDTO.RemedicalCode
  1460. };
  1461. consultationRecord.ConsultationFileList.Add(consultationFileDTO);
  1462. var result = await _consultationRecordDBService.UpdateConsultationRecordAsync(consultationRecord);
  1463. return !string.IsNullOrWhiteSpace(dataDTO.RemedicalCode);
  1464. }
  1465. }
  1466. }