MqttController.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. using HiTeachCE.Dtos;
  2. using HiTeachCE.Helpers;
  3. using HiTeachCE.Models;
  4. using HiTeachCE.Services;
  5. using IdentityModel;
  6. using Microsoft.AspNetCore.Authorization;
  7. using Microsoft.AspNetCore.Mvc;
  8. using Microsoft.Extensions.Configuration;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Linq.Expressions;
  13. using System.Threading.Tasks;
  14. using TEAMModelOS;
  15. using TEAMModelOS.SDK.Context.Configuration;
  16. using TEAMModelOS.SDK.Context.Exception;
  17. using TEAMModelOS.SDK.Extension.DataResult.JsonRpcRequest;
  18. using TEAMModelOS.SDK.Extension.DataResult.JsonRpcResponse;
  19. using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
  20. namespace HiTeachCE.Controllers
  21. {
  22. [Route("api/[controller]")]
  23. [ApiController]
  24. public class MqttController:BaseController
  25. {
  26. public static int smsTTL = 4 * 60;
  27. public static int ticketTTL = 1 * 24 * 60 * 60;
  28. //public static int freeTTL = 7 * 24 * 60 * 60;
  29. public static int deviceTTL = 1 * 24 * 60 * 60;
  30. public static string freeOrg = "7f847a9f05224184a5d01ee69a6b00d6";
  31. public static string model_teach = "teach";
  32. public static string model_prepare = "prepare";
  33. private readonly OrganizationService organizationService;
  34. private readonly MemberService memberService;
  35. private readonly ActivationCodeService activationCodeService;
  36. public MqttController( OrganizationService organization, MemberService member, ActivationCodeService activationCode)
  37. {
  38. organizationService = organization;
  39. memberService = member;
  40. activationCodeService = activationCode;
  41. }
  42. /// <summary>
  43. /// 注册装置
  44. /// </summary>
  45. /// <param name="request"></param>
  46. /// <returns></returns>
  47. [HttpPost("regist")]
  48. [Authorize(Policy = Constant.Role_Lecturer)]
  49. public BaseJosnRPCResponse Regist(JosnRPCRequest<Dictionary<string, string>> request)
  50. {
  51. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  52. string unionid = GetLoginUser(JwtClaimTypes.Id);
  53. /**
  54. "params": {
  55. "deviceId": "f67fb5dd-ee1b-d3b7-9b95-61022d7e8acd",
  56. "clientId": "931dee8c-74be-4c9b-a602-c74583b0e985",
  57. }
  58. */
  59. if (request.@params.TryGetValue("deviceId", out string deviceId) && request.@params.TryGetValue("orgCode", out string orgCode) && !string.IsNullOrEmpty(unionid))
  60. {
  61. Dictionary<string, object> dict = ActivationValid(orgCode, unionid);
  62. if (dict != null && dict.TryGetValue("flag", out object flag) && bool.Parse(flag.ToString()))
  63. {
  64. if (RedisHelper.HExists("device:" + deviceId, deviceId))
  65. {
  66. }
  67. else
  68. {
  69. RedisHelper.HSet("device-oud:" + deviceId, deviceId, new OrgUserDevice {orgCode=orgCode,deviceId=deviceId,unionid=unionid });
  70. RedisHelper.HSet("device:" + deviceId, deviceId, null);
  71. RedisHelper.Expire("device-oud:" + deviceId, deviceTTL);
  72. RedisHelper.Expire("device:" + deviceId, deviceTTL);
  73. }
  74. return builder.Data(new Dictionary<string, object> { { "deviceId", deviceId } }).build();
  75. }
  76. else
  77. {
  78. throw new BizException("授权失败!", 2);
  79. }
  80. }
  81. else
  82. {
  83. throw new BizException("参数错误!", 2);
  84. }
  85. }
  86. /// <summary>
  87. /// 创建教室
  88. /// </summary>
  89. /// <param name="request"></param>
  90. /// <returns></returns>
  91. [HttpPost("createGroup")]
  92. [Authorize(Policy = Constant.Role_Lecturer)]
  93. public BaseJosnRPCResponse CreateGroup(JosnRPCRequest<Dictionary<string, string>> request)
  94. {
  95. /**
  96. "params": {
  97. "deviceId": "f67fb5dd-ee1b-d3b7-9b95-61022d7e8acd",
  98. "doBoundGroupNum": false,
  99. "extraInfo": {}
  100. }
  101. */
  102. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  103. //string ClientId =// new List<string>() { "fb564dde14df423cafac2085936e3b96" };
  104. // GetLoginUser(JwtClaimTypes.ClientId);
  105. string groupNum;
  106. if (request.@params.TryGetValue("deviceId", out string deviceId) )
  107. {
  108. if (RedisHelper.HExists("device:" + deviceId, deviceId))
  109. {
  110. groupNum = RedisHelper.HGet<string>("device:" + deviceId, deviceId);
  111. if (string.IsNullOrEmpty(groupNum))
  112. {
  113. do
  114. {
  115. groupNum = RandGroupNum();
  116. } while (RedisHelper.Exists("group:" + groupNum));
  117. RedisHelper.HSet("group:" + groupNum, deviceId, null);
  118. RedisHelper.Expire("group:" + groupNum, deviceTTL);
  119. RedisHelper.HSet("device:" + deviceId, deviceId, groupNum);
  120. }
  121. }
  122. else { throw new BizException("装置未注册", 2); }
  123. }
  124. else
  125. {
  126. throw new BizException("参数错误", 2);
  127. }
  128. return builder.Data(groupNum).build();
  129. }
  130. public string RandGroupNum()
  131. {
  132. Random random = new Random();
  133. String result = "";
  134. for (int i = 0; i < 6; i++)
  135. {
  136. result += random.Next(0, 10);
  137. }
  138. return result;
  139. }
  140. /// <summary>
  141. /// 加入教室
  142. /// </summary>
  143. /// <param name="request"></param>
  144. /// <returns></returns>
  145. [HttpPost("joinGroup")]
  146. [Authorize(Policy = Constant.Role_LecturerLearner)]
  147. public BaseJosnRPCResponse JoinGroup(JosnRPCRequest<Dictionary<string, string>> request)
  148. {
  149. // string ClientId = GetLoginUser(JwtClaimTypes.ClientId);
  150. string Unionid = GetLoginUser(JwtClaimTypes.Id);
  151. string Role = GetLoginUser(JwtClaimTypes.Role);
  152. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  153. Dictionary<string, object> dict;
  154. /**
  155. "params": {
  156. "deviceId": "f67fb5dd-ee1b-d3b7-9b95-61022d7e8acd",
  157. "groupNum": "818288"
  158. }
  159. */
  160. if (request.@params.TryGetValue("deviceId", out string deviceId) &&
  161. request.@params.TryGetValue("groupNum", out string groupNum) &&
  162. !string.IsNullOrEmpty(deviceId) && !string.IsNullOrEmpty(groupNum)
  163. )
  164. {
  165. if (RedisHelper.Exists("group:" + groupNum))
  166. {
  167. Dictionary<string, MQTTMember> member = RedisHelper.HGetAll<MQTTMember>("group:" + groupNum);
  168. if (member != null) {
  169. foreach (string key in member.Keys)
  170. {
  171. if (member[key] != null && member[key].role .Contains("lecturer") && Role.Contains("lecturer") && Unionid != member[key].unionid)
  172. {
  173. throw new BizException("教室只能有一个创建者加入", ResponseCode.DATA_EXIST);
  174. }
  175. }
  176. }
  177. dict = MqttInfo(deviceId, deviceId, groupNum, Unionid, Role);
  178. Dictionary<string, MQTTMember> members = RedisHelper.HGetAll<MQTTMember>("group:" + groupNum);
  179. List<MQTTMember> learners = new List<MQTTMember>();
  180. MQTTMember lecturer = null;
  181. foreach (string key in members.Keys) {
  182. if (members[key].role.Contains("lecturer"))
  183. {
  184. lecturer= members[key];
  185. }
  186. else {
  187. learners.Add(members[key]);
  188. }
  189. }
  190. dict.Add("lecturer", lecturer);
  191. dict.Add("learners", learners);
  192. }
  193. else
  194. {
  195. throw new BizException("教室不存在", 2);
  196. }
  197. }
  198. else
  199. {
  200. throw new BizException("参数错误", 2);
  201. }
  202. return builder.Data(dict).build();
  203. }
  204. private static Dictionary<string, object> MqttInfo(string ClientId, string deviceId, string groupNum, string Unionid, string Role)
  205. {
  206. string brokerHostName = BaseConfigModel.Configuration["brokerHostName"];
  207. Dictionary<string, object> dict = new Dictionary<string, object>();
  208. string password = brokerHostName + "/" + groupNum + "/" + deviceId + "/" + ClientId;
  209. //发给前端使用的
  210. string h1 = BCrypt.Net.BCrypt.HashPassword(password);
  211. //后端存储使用的
  212. string h2 = BCrypt.Net.BCrypt.HashPassword(h1, BCrypt.Net.SaltRevision.Revision2);
  213. bool validPassword = BCrypt.Net.BCrypt.Verify(h1, h2);
  214. string uname = password;
  215. Dictionary<string, string> connectInfo = new Dictionary<string, string>
  216. {
  217. { "brokerHostName", brokerHostName },
  218. { "brokerHostNameWSS", "wss://" +brokerHostName+"/mqtt/"} ,
  219. { "clientID", deviceId },
  220. //使用BCrypt加密
  221. { "password",h1} ,
  222. { "username",uname}
  223. };
  224. Dictionary<string, string> subscribeTopic = BaseConfigModel.Configuration.GetSection("SubscribeTopic").Get<Dictionary<string, string>>();
  225. subscribeTopic["receiveMsg"] = subscribeTopic["receiveMsg"].Replace("{deviceId}", deviceId);
  226. Dictionary<string, string> publishTopic = BaseConfigModel.Configuration.GetSection("PublishTopic").Get<Dictionary<string, string>>();
  227. publishTopic["sendMsg"] = publishTopic["sendMsg"].Replace("{deviceId}", deviceId).Replace("{groupNum}", groupNum);
  228. dict.Add("mqtt", new Dictionary<string, object>() { { "connectInfo", connectInfo }, { "publishTopic", publishTopic }, { "subscribeTopic", subscribeTopic } });
  229. List<string> topic = new List<string>();
  230. topic.AddRange(publishTopic.Values.ToList());
  231. topic.AddRange(subscribeTopic.Values.ToList());
  232. MQTTInfo mqtt = new MQTTInfo
  233. {
  234. brokerHostName = brokerHostName,
  235. brokerHostNameWSS = "wss://" + brokerHostName + "/mqtt/",
  236. clientID = deviceId,
  237. //使用BCrypt加密
  238. password = h2,
  239. username = uname,
  240. topic = topic
  241. };
  242. var groupMember = new MQTTMember
  243. {
  244. clientId = ClientId,
  245. deviceId = deviceId,
  246. unionid = Unionid,
  247. role = Role,
  248. groupNum = groupNum
  249. };
  250. RedisHelper.HSet("group:" + groupNum, deviceId, groupMember);
  251. RedisHelper.HSet("mqtt:" + deviceId, deviceId, mqtt);
  252. RedisHelper.Expire("mqtt:" + deviceId, deviceTTL);
  253. return dict;
  254. }
  255. /// <summary>
  256. /// 教学认证
  257. /// </summary>
  258. /// <param name="request"></param>
  259. /// <returns></returns>
  260. [HttpPost("auth")]
  261. [Authorize(Policy = Constant.Role_Lecturer)]
  262. public BaseJosnRPCResponse Auth(JosnRPCRequest<object> request)
  263. {
  264. JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
  265. string unionid = GetLoginUser(JwtClaimTypes.Id);
  266. string phoneNumber = GetLoginUser(JwtClaimTypes.PhoneNumber);
  267. Expression<Func<Member, bool>> mlinq = null;
  268. mlinq = m => m.unionid == unionid;
  269. List<Dictionary<string, object>> dict = new List<Dictionary<string, object>>();
  270. List<Member> members = memberService.GetList(mlinq);
  271. if (members.IsNotEmpty())
  272. {
  273. foreach (var code in members)
  274. {
  275. var dt = ActivationValid(code.orgCode, unionid);
  276. if (dt != null)
  277. {
  278. dict.Add(dt);
  279. }
  280. }
  281. }
  282. else
  283. {
  284. long time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
  285. ///处理该机构是否激活人数达到上线
  286. Expression<Func<Member, bool>> limitlinq = null;
  287. limitlinq = m => m.orgCode == freeOrg && m.status == 1;
  288. List<Member> countMembers = memberService.GetList(limitlinq);
  289. Expression<Func<ActivationCode, bool>> alinq = null;
  290. alinq = m => m.orgCode == freeOrg && m.status == 1;
  291. List<ActivationCode> activationCodes = activationCodeService.GetList(alinq);
  292. if (activationCodes.IsNotEmpty())
  293. {
  294. //判断组织机构人员是否已经达到最大激活数量
  295. if (countMembers.IsNotEmpty() && countMembers.Count >= activationCodes[0].maximum)
  296. {
  297. //throw new BizException(":HiTeachCE(测试)授权人数超过上限!", 2);
  298. }
  299. else
  300. {
  301. List<string> RootUsers = BaseConfigModel.Configuration.GetSection("RootUser").Get<List<string>>();
  302. string role = "admin,lecturer";
  303. if (RootUsers.Contains(phoneNumber))
  304. {
  305. role = "root," + role;
  306. }
  307. Member member = new Member
  308. {
  309. id = Guid.NewGuid().ToString(),
  310. orgCode = freeOrg,
  311. admin = 0,
  312. status = 1,
  313. // expires = time + freeTTL,
  314. unionid = unionid,
  315. createTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds()
  316. };
  317. bool flag = memberService.Insert(member);
  318. if (flag)
  319. {
  320. var dt = ActivationValid(freeOrg, unionid);
  321. if (dt != null)
  322. {
  323. dict.Add(dt);
  324. }
  325. }
  326. else
  327. {
  328. //throw new BizException("无法加入:HiTeachCE(测试)!", 2);
  329. }
  330. }
  331. }
  332. else
  333. {
  334. }
  335. }
  336. return builder.Data(dict).build();
  337. }
  338. public Dictionary<string, object> ActivationValid(string orgCode, string unionid)
  339. {
  340. //调用ActivationCode
  341. Expression<Func<Organization, bool>> olinq = null;
  342. olinq = m => m.code == orgCode;
  343. Organization org = organizationService.GetList(olinq).FirstOrDefault();
  344. if (org != null)
  345. {
  346. Dictionary<string, object> dict = new Dictionary<string, object>() { { "org", new { orgCode = "", name = org.name } }, { "flag", false } };
  347. if (org.status != 1)
  348. {
  349. dict.Add("msg", "组织机构被禁用!");
  350. }
  351. else
  352. {
  353. //验证组织机构的激活码状态,时间,最大人数
  354. Expression<Func<ActivationCode, bool>> linq = null;
  355. linq = m => m.orgCode == org.code;
  356. List<ActivationCode> activationCodes = activationCodeService.GetList(linq);
  357. if (activationCodes.IsNotEmpty())
  358. {
  359. if (activationCodes[0].status == 1)
  360. {
  361. long time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
  362. if (activationCodes[0].expires > time)
  363. {
  364. int max = activationCodes[0].maximum;
  365. Expression<Func<Member, bool>> mlinq = null;
  366. mlinq = l => l.orgCode == org.code;
  367. List<Member> members = memberService.GetList(mlinq);
  368. if (members.Count > max)
  369. {
  370. dict.Add("msg", "产品授权人数超过上限!");
  371. }
  372. else
  373. {
  374. if (members.Where(x => x.status == 1).Select(x => x.unionid).ToList().Contains(unionid))
  375. {
  376. dict["org"] = new { orgCode = org.code, name = org.name };
  377. dict["flag"] = true;
  378. }
  379. else
  380. {
  381. dict.Add("msg", "组织机构未对该用户授权!");
  382. }
  383. }
  384. }
  385. else
  386. {
  387. dict.Add("msg", "产品授权已经过期!");
  388. }
  389. }
  390. else
  391. {
  392. dict.Add("msg", "组织机构授权状态被禁用!");
  393. }
  394. }
  395. else
  396. {
  397. dict.Add("msg", "组织机构没有授权信息!");
  398. }
  399. }
  400. return dict;
  401. }
  402. return null;
  403. }
  404. }
  405. }