123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432 |
- using HiTeachCE.Dtos;
- using HiTeachCE.Helpers;
- using HiTeachCE.Models;
- using HiTeachCE.Services;
- using IdentityModel;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Threading.Tasks;
- using TEAMModelOS;
- using TEAMModelOS.SDK.Context.Configuration;
- using TEAMModelOS.SDK.Context.Exception;
- using TEAMModelOS.SDK.Extension.DataResult.JsonRpcRequest;
- using TEAMModelOS.SDK.Extension.DataResult.JsonRpcResponse;
- using TEAMModelOS.SDK.Helper.Common.CollectionHelper;
- namespace HiTeachCE.Controllers
- {
- [Route("api/[controller]")]
- [ApiController]
- public class MqttController:BaseController
- {
- public static int smsTTL = 4 * 60;
- public static int ticketTTL = 1 * 24 * 60 * 60;
- //public static int freeTTL = 7 * 24 * 60 * 60;
- public static int deviceTTL = 1 * 24 * 60 * 60;
- public static string freeOrg = "7f847a9f05224184a5d01ee69a6b00d6";
- public static string model_teach = "teach";
- public static string model_prepare = "prepare";
- private readonly OrganizationService organizationService;
- private readonly MemberService memberService;
- private readonly ActivationCodeService activationCodeService;
- public MqttController( OrganizationService organization, MemberService member, ActivationCodeService activationCode)
- {
- organizationService = organization;
- memberService = member;
- activationCodeService = activationCode;
- }
- /// <summary>
- /// 注册装置
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("regist")]
- [Authorize(Policy = Constant.Role_Lecturer)]
- public BaseJosnRPCResponse Regist(JosnRPCRequest<Dictionary<string, string>> request)
- {
- JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
- string unionid = GetLoginUser(JwtClaimTypes.Id);
- /**
- "params": {
- "deviceId": "f67fb5dd-ee1b-d3b7-9b95-61022d7e8acd",
- "clientId": "931dee8c-74be-4c9b-a602-c74583b0e985",
- }
- */
- if (request.@params.TryGetValue("deviceId", out string deviceId) && request.@params.TryGetValue("orgCode", out string orgCode) && !string.IsNullOrEmpty(unionid))
- {
- Dictionary<string, object> dict = ActivationValid(orgCode, unionid);
- if (dict != null && dict.TryGetValue("flag", out object flag) && bool.Parse(flag.ToString()))
- {
- if (RedisHelper.HExists("device:" + deviceId, deviceId))
- {
- }
- else
- {
- RedisHelper.HSet("device-oud:" + deviceId, deviceId, new OrgUserDevice {orgCode=orgCode,deviceId=deviceId,unionid=unionid });
- RedisHelper.HSet("device:" + deviceId, deviceId, null);
- RedisHelper.Expire("device-oud:" + deviceId, deviceTTL);
- RedisHelper.Expire("device:" + deviceId, deviceTTL);
- }
- return builder.Data(new Dictionary<string, object> { { "deviceId", deviceId } }).build();
- }
- else
- {
- throw new BizException("授权失败!", 2);
- }
- }
- else
- {
- throw new BizException("参数错误!", 2);
- }
- }
- /// <summary>
- /// 创建教室
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("createGroup")]
- [Authorize(Policy = Constant.Role_Lecturer)]
- public BaseJosnRPCResponse CreateGroup(JosnRPCRequest<Dictionary<string, string>> request)
- {
- /**
- "params": {
- "deviceId": "f67fb5dd-ee1b-d3b7-9b95-61022d7e8acd",
- "doBoundGroupNum": false,
- "extraInfo": {}
- }
- */
- JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
- //string ClientId =// new List<string>() { "fb564dde14df423cafac2085936e3b96" };
- // GetLoginUser(JwtClaimTypes.ClientId);
- string groupNum;
- if (request.@params.TryGetValue("deviceId", out string deviceId) )
- {
- if (RedisHelper.HExists("device:" + deviceId, deviceId))
- {
- groupNum = RedisHelper.HGet<string>("device:" + deviceId, deviceId);
- if (string.IsNullOrEmpty(groupNum))
- {
- do
- {
- groupNum = RandGroupNum();
- } while (RedisHelper.Exists("group:" + groupNum));
- RedisHelper.HSet("group:" + groupNum, deviceId, null);
- RedisHelper.Expire("group:" + groupNum, deviceTTL);
- RedisHelper.HSet("device:" + deviceId, deviceId, groupNum);
- }
- }
- else { throw new BizException("装置未注册", 2); }
- }
- else
- {
- throw new BizException("参数错误", 2);
- }
- return builder.Data(groupNum).build();
- }
- public string RandGroupNum()
- {
- Random random = new Random();
- String result = "";
- for (int i = 0; i < 6; i++)
- {
- result += random.Next(0, 10);
- }
- return result;
- }
- /// <summary>
- /// 加入教室
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("joinGroup")]
- [Authorize(Policy = Constant.Role_LecturerLearner)]
- public BaseJosnRPCResponse JoinGroup(JosnRPCRequest<Dictionary<string, string>> request)
- {
- // string ClientId = GetLoginUser(JwtClaimTypes.ClientId);
- string Unionid = GetLoginUser(JwtClaimTypes.Id);
- string Role = GetLoginUser(JwtClaimTypes.Role);
- JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
- Dictionary<string, object> dict;
- /**
- "params": {
- "deviceId": "f67fb5dd-ee1b-d3b7-9b95-61022d7e8acd",
- "groupNum": "818288"
- }
- */
- if (request.@params.TryGetValue("deviceId", out string deviceId) &&
- request.@params.TryGetValue("groupNum", out string groupNum) &&
- !string.IsNullOrEmpty(deviceId) && !string.IsNullOrEmpty(groupNum)
- )
- {
- if (RedisHelper.Exists("group:" + groupNum))
- {
- Dictionary<string, MQTTMember> member = RedisHelper.HGetAll<MQTTMember>("group:" + groupNum);
- if (member != null) {
- foreach (string key in member.Keys)
- {
- if (member[key] != null && member[key].role .Contains("lecturer") && Role.Contains("lecturer") && Unionid != member[key].unionid)
- {
- throw new BizException("教室只能有一个创建者加入", ResponseCode.DATA_EXIST);
- }
- }
- }
- dict = MqttInfo(deviceId, deviceId, groupNum, Unionid, Role);
- Dictionary<string, MQTTMember> members = RedisHelper.HGetAll<MQTTMember>("group:" + groupNum);
- List<MQTTMember> learners = new List<MQTTMember>();
- MQTTMember lecturer = null;
- foreach (string key in members.Keys) {
- if (members[key].role.Contains("lecturer"))
- {
- lecturer= members[key];
-
- }
- else {
- learners.Add(members[key]);
- }
- }
- dict.Add("lecturer", lecturer);
- dict.Add("learners", learners);
- }
- else
- {
- throw new BizException("教室不存在", 2);
- }
- }
- else
- {
- throw new BizException("参数错误", 2);
- }
- return builder.Data(dict).build();
- }
- private static Dictionary<string, object> MqttInfo(string ClientId, string deviceId, string groupNum, string Unionid, string Role)
- {
- string brokerHostName = BaseConfigModel.Configuration["brokerHostName"];
- Dictionary<string, object> dict = new Dictionary<string, object>();
- string password = brokerHostName + "/" + groupNum + "/" + deviceId + "/" + ClientId;
- //发给前端使用的
- string h1 = BCrypt.Net.BCrypt.HashPassword(password);
- //后端存储使用的
- string h2 = BCrypt.Net.BCrypt.HashPassword(h1, BCrypt.Net.SaltRevision.Revision2);
- bool validPassword = BCrypt.Net.BCrypt.Verify(h1, h2);
- string uname = password;
- Dictionary<string, string> connectInfo = new Dictionary<string, string>
- {
- { "brokerHostName", brokerHostName },
- { "brokerHostNameWSS", "wss://" +brokerHostName+"/mqtt/"} ,
- { "clientID", deviceId },
- //使用BCrypt加密
- { "password",h1} ,
- { "username",uname}
- };
- Dictionary<string, string> subscribeTopic = BaseConfigModel.Configuration.GetSection("SubscribeTopic").Get<Dictionary<string, string>>();
- subscribeTopic["receiveMsg"] = subscribeTopic["receiveMsg"].Replace("{deviceId}", deviceId);
- Dictionary<string, string> publishTopic = BaseConfigModel.Configuration.GetSection("PublishTopic").Get<Dictionary<string, string>>();
- publishTopic["sendMsg"] = publishTopic["sendMsg"].Replace("{deviceId}", deviceId).Replace("{groupNum}", groupNum);
- dict.Add("mqtt", new Dictionary<string, object>() { { "connectInfo", connectInfo }, { "publishTopic", publishTopic }, { "subscribeTopic", subscribeTopic } });
-
- List<string> topic = new List<string>();
- topic.AddRange(publishTopic.Values.ToList());
- topic.AddRange(subscribeTopic.Values.ToList());
- MQTTInfo mqtt = new MQTTInfo
- {
- brokerHostName = brokerHostName,
- brokerHostNameWSS = "wss://" + brokerHostName + "/mqtt/",
- clientID = deviceId,
- //使用BCrypt加密
- password = h2,
- username = uname,
- topic = topic
- };
- var groupMember = new MQTTMember
- {
- clientId = ClientId,
- deviceId = deviceId,
- unionid = Unionid,
- role = Role,
- groupNum = groupNum
- };
- RedisHelper.HSet("group:" + groupNum, deviceId, groupMember);
- RedisHelper.HSet("mqtt:" + deviceId, deviceId, mqtt);
- RedisHelper.Expire("mqtt:" + deviceId, deviceTTL);
- return dict;
- }
- /// <summary>
- /// 教学认证
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("auth")]
- [Authorize(Policy = Constant.Role_Lecturer)]
- public BaseJosnRPCResponse Auth(JosnRPCRequest<object> request)
- {
- JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
- string unionid = GetLoginUser(JwtClaimTypes.Id);
- string phoneNumber = GetLoginUser(JwtClaimTypes.PhoneNumber);
- Expression<Func<Member, bool>> mlinq = null;
- mlinq = m => m.unionid == unionid;
- List<Dictionary<string, object>> dict = new List<Dictionary<string, object>>();
- List<Member> members = memberService.GetList(mlinq);
- if (members.IsNotEmpty())
- {
- foreach (var code in members)
- {
- var dt = ActivationValid(code.orgCode, unionid);
- if (dt != null)
- {
- dict.Add(dt);
- }
- }
- }
- else
- {
- long time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
- ///处理该机构是否激活人数达到上线
- Expression<Func<Member, bool>> limitlinq = null;
- limitlinq = m => m.orgCode == freeOrg && m.status == 1;
- List<Member> countMembers = memberService.GetList(limitlinq);
- Expression<Func<ActivationCode, bool>> alinq = null;
- alinq = m => m.orgCode == freeOrg && m.status == 1;
- List<ActivationCode> activationCodes = activationCodeService.GetList(alinq);
- if (activationCodes.IsNotEmpty())
- {
- //判断组织机构人员是否已经达到最大激活数量
- if (countMembers.IsNotEmpty() && countMembers.Count >= activationCodes[0].maximum)
- {
- //throw new BizException(":HiTeachCE(测试)授权人数超过上限!", 2);
- }
- else
- {
- List<string> RootUsers = BaseConfigModel.Configuration.GetSection("RootUser").Get<List<string>>();
- string role = "admin,lecturer";
- if (RootUsers.Contains(phoneNumber))
- {
- role = "root," + role;
- }
- Member member = new Member
- {
- id = Guid.NewGuid().ToString(),
- orgCode = freeOrg,
- admin = 0,
- status = 1,
- // expires = time + freeTTL,
- unionid = unionid,
- createTime = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds()
- };
- bool flag = memberService.Insert(member);
- if (flag)
- {
- var dt = ActivationValid(freeOrg, unionid);
- if (dt != null)
- {
- dict.Add(dt);
- }
- }
- else
- {
- //throw new BizException("无法加入:HiTeachCE(测试)!", 2);
- }
- }
- }
- else
- {
- }
- }
- return builder.Data(dict).build();
- }
- public Dictionary<string, object> ActivationValid(string orgCode, string unionid)
- {
- //调用ActivationCode
- Expression<Func<Organization, bool>> olinq = null;
- olinq = m => m.code == orgCode;
- Organization org = organizationService.GetList(olinq).FirstOrDefault();
- if (org != null)
- {
- Dictionary<string, object> dict = new Dictionary<string, object>() { { "org", new { orgCode = "", name = org.name } }, { "flag", false } };
- if (org.status != 1)
- {
- dict.Add("msg", "组织机构被禁用!");
- }
- else
- {
- //验证组织机构的激活码状态,时间,最大人数
- Expression<Func<ActivationCode, bool>> linq = null;
- linq = m => m.orgCode == org.code;
- List<ActivationCode> activationCodes = activationCodeService.GetList(linq);
- if (activationCodes.IsNotEmpty())
- {
- if (activationCodes[0].status == 1)
- {
- long time = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
- if (activationCodes[0].expires > time)
- {
- int max = activationCodes[0].maximum;
- Expression<Func<Member, bool>> mlinq = null;
- mlinq = l => l.orgCode == org.code;
- List<Member> members = memberService.GetList(mlinq);
- if (members.Count > max)
- {
- dict.Add("msg", "产品授权人数超过上限!");
- }
- else
- {
- if (members.Where(x => x.status == 1).Select(x => x.unionid).ToList().Contains(unionid))
- {
- dict["org"] = new { orgCode = org.code, name = org.name };
- dict["flag"] = true;
- }
- else
- {
- dict.Add("msg", "组织机构未对该用户授权!");
- }
- }
- }
- else
- {
- dict.Add("msg", "产品授权已经过期!");
- }
- }
- else
- {
- dict.Add("msg", "组织机构授权状态被禁用!");
- }
- }
- else
- {
- dict.Add("msg", "组织机构没有授权信息!");
- }
- }
- return dict;
- }
- return null;
- }
- }
- }
|