示例#1
0
        public static string GetAppToken()
        {
            if (mRedis.KeyExists(KEY_APP_TOKEN))
            {
                return(mRedis.StringGet(KEY_APP_TOKEN));
            }
            IMoredianApiClient      client  = new DefaultMoredianApiClient(Config.MoreDian.APIURL);
            MoredianAppTokenRequest request = new MoredianAppTokenRequest
            {
                AppId  = Config.MoreDian.APPID,
                Secret = Config.MoreDian.SECRET
            };
            MoredianAppTokenResponse response = client.Execute(request);

            if (null == response || !response.IsSucc())
            {
                return("");
            }
            mRedis.StringSet(KEY_APP_TOKEN, response.appToken, TimeSpan.FromSeconds(response.expires));
            return(response.appToken);
        }
示例#2
0
        public static string GetAccessToken(string OrgId, string OrgAuthKey)
        {
            if (mRedis.KeyExists(string.Format(KEY_ACCESS_TOKEN, OrgId)))
            {
                return(mRedis.StringGet(string.Format(KEY_ACCESS_TOKEN, OrgId)));
            }
            IMoredianApiClient         client  = new DefaultMoredianApiClient(Config.MoreDian.APIURL);
            MoredianAccessTokenRequest request = new MoredianAccessTokenRequest
            {
                OrgId      = OrgId,
                OrgAuthKey = OrgAuthKey
            };
            MoredianAccessTokenResponse response = client.Execute(request, AppTokenRedis.GetAppToken(), null);

            if (null == response || !response.IsSucc())
            {
                return("");
            }
            mRedis.StringSet(string.Format(KEY_ACCESS_TOKEN, OrgId), response.accessToken, TimeSpan.FromSeconds(response.expires));
            return(response.accessToken);
        }
示例#3
0
        /// <summary>
        /// 发起远程开门
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        private string RemoteOpenDoor(DataRow row)
        {
            try
            {
                #region 获取参数并简单校验
                string Mobile = string.Empty;
                if (row.Table.Columns.Contains("Mobile"))
                {
                    Mobile = row["Mobile"].ToString();
                }
                if (string.IsNullOrEmpty(Mobile))
                {
                    return(new WxResponse(0, "用户不存在", null).toJson());
                }
                if (Mobile.Length != 11)
                {
                    return(new WxResponse(0, "用户不存在", null).toJson());
                }
                if (!row.Table.Columns.Contains("UserID") || !int.TryParse(row["UserID"].ToString(), out int UserID))
                {
                    return(new WxResponse(0, "用户不存在", null).toJson());
                }
                string DeviceId = string.Empty;
                if (row.Table.Columns.Contains("DeviceId"))
                {
                    DeviceId = row["DeviceId"].ToString();
                }
                if (string.IsNullOrEmpty(DeviceId))
                {
                    return(new WxResponse(0, "请选择要开的门", null).toJson());
                }
                DateTime DateNow = DateTime.Now;
                #endregion
                using (IDbConnection conn = new SqlConnection(PubConstant.WChat2020ConnectionString),
                       erpConn = new SqlConnection(erpConnStr))
                {
                    #region 查询用户信息
                    Tb_User tb_User = conn.QueryFirstOrDefault <Tb_User>("SELECT * FROM Tb_User WITH(NOLOCK) WHERE Id = @Id AND Mobile = @Mobile", new { Id = UserID, Mobile });
                    if (null == tb_User)
                    {
                        return(new WxResponse(0, "用户不存在", null).toJson());
                    }
                    #endregion

                    #region 获取AppToken
                    TianChengEntranceSyncService.Config.EntranceConnectionStr  = erpConnStr;
                    TianChengEntranceSyncService.Config.WChat2020ConnectionStr = PubConstant.WChat2020ConnectionString;
                    string app_token = AppTokenRedis.GetAppToken();
                    if (string.IsNullOrEmpty(app_token))
                    {
                        return(new WxResponse(0, "获取AppToken失败,请联系管理员", null).toJson());
                    }
                    #endregion

                    // 成员信息不存在,进行创建
                    #region 先查询/创建组织机构
                    MoredianOrg moredianOrg = OrgRedis.GetMoredianOrg();
                    if (null == moredianOrg)
                    {
                        return(new WxResponse(0, "组织机构配置错误,请联系管理员", null).toJson());
                    }
                    #endregion
                    #region 获取AccessToken
                    string access_token = AccessTokenRedis.GetAccessToken(Convert.ToString(moredianOrg.orgId), moredianOrg.orgAuthKey);
                    if (string.IsNullOrEmpty(access_token))
                    {
                        return(new WxResponse(0, "获取AccessToken失败,请联系管理员", null).toJson());
                    }
                    #endregion
                    #region 查询人员信息
                    MoredianMember moredianMember = MemberRedis.GetMoredianMember(Mobile);
                    if (null == moredianMember)
                    {
                        return(new WxResponse(0, "请先使用“人脸采集”功能录入人脸信息后再使用远程开门", null).toJson());
                    }
                    long   memberId   = moredianMember.memberId;
                    string memberName = moredianMember.memberName;
                    if (string.IsNullOrEmpty(memberName))
                    {
                        memberName = moredianMember.mobile;
                    }
                    #endregion
                    #region 查询设备是否存在
                    DeviceId = erpConn.QueryFirstOrDefault <string>("SELECT DeviceId FROM Tb_HSPR_Entrance_Device WITH(NOLOCK) WHERE DeviceId = @DeviceId", new { DeviceId });
                    if (string.IsNullOrEmpty(DeviceId))
                    {
                        return(new WxResponse(0, "该设备不存在", null).toJson());
                    }
                    #endregion
                    #region 发起远程开门
                    {
                        IMoredianApiClient            client  = new DefaultMoredianApiClient(TianChengEntranceSyncService.Config.MoreDian.APIURL);
                        MoredianRemoteOpenDoorRequest request = new MoredianRemoteOpenDoorRequest
                        {
                            deviceId   = Convert.ToInt64(DeviceId),
                            memberId   = memberId,
                            memberName = memberName
                        };
                        MoredianRemoteOpenDoorResponse response = client.Execute(request, app_token, access_token);
                        if (!response.IsSucc())
                        {
                            return(new WxResponse(0, response.Message, response).toJson());
                        }
                        return(new WxResponse(200, "操作成功", response).toJson());
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                GetLog().Error(ex.Message + Environment.CommandLine + ex.StackTrace);
                return(new WxResponse(0, "响应异常", null).toJson());
            }
        }
示例#4
0
        /// <summary>
        /// 提交魔蓝成员信息(创建或者修改成员信息)
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        private string SubmitMoredianMember(DataRow row)
        {
            try
            {
                #region 获取参数并简单校验
                string Mobile = string.Empty;
                if (row.Table.Columns.Contains("Mobile"))
                {
                    Mobile = row["Mobile"].ToString();
                }
                if (string.IsNullOrEmpty(Mobile))
                {
                    return(new WxResponse(0, "用户不存在", null).toJson());
                }
                if (Mobile.Length != 11)
                {
                    return(new WxResponse(0, "用户不存在", null).toJson());
                }
                string Face = string.Empty;
                if (row.Table.Columns.Contains("Face"))
                {
                    Face = row["Face"].ToString();
                }
                DateTime DateNow = DateTime.Now;
                #endregion

                using (IDbConnection conn = new SqlConnection(PubConstant.WChat2020ConnectionString),
                       erpConn = new SqlConnection(erpConnStr))
                {
                    #region 获取AppToken
                    TianChengEntranceSyncService.Config.EntranceConnectionStr  = erpConnStr;
                    TianChengEntranceSyncService.Config.WChat2020ConnectionStr = PubConstant.WChat2020ConnectionString;
                    string app_token = AppTokenRedis.GetAppToken();
                    if (string.IsNullOrEmpty(app_token))
                    {
                        return(new WxResponse(0, "获取AppToken失败,请联系管理员", null).toJson());
                    }
                    #endregion
                    #region 先查询/创建组织机构
                    MoredianOrg moredianOrg = OrgRedis.GetMoredianOrg();
                    if (null == moredianOrg)
                    {
                        return(new WxResponse(0, "组织机构配置错误,请联系管理员", null).toJson());
                    }
                    #endregion
                    #region 获取组织机构的AccessToken
                    string access_token = AccessTokenRedis.GetAccessToken(Convert.ToString(moredianOrg.orgId), moredianOrg.orgAuthKey);
                    if (string.IsNullOrEmpty(access_token))
                    {
                        return(new WxResponse(0, "获取AccessToken失败,请联系管理员", null).toJson());
                    }
                    #endregion
                    MoredianMember moredianMember = MemberRedis.GetMoredianMember(Mobile);

                    #region 读取人脸图片
                    byte[] showFace = null;
                    string IncidentAcceptImageUrl = Global_Fun.AppWebSettings("IncidentAcceptImageUrl");
                    if (Face.Contains(IncidentAcceptImageUrl))
                    {
                        string IncidentAcceptImageSavePath = Global_Fun.AppWebSettings("IncidentAcceptImageSavePath");
                        #region 从本地服务器读取图片
                        // 替换文件路径为本地路径
                        string localFacePath = Face.Replace(IncidentAcceptImageUrl, IncidentAcceptImageSavePath);
                        if (!File.Exists(localFacePath))
                        {
                            return(new WxResponse(0, "人脸图片不存在,请重试", null).toJson());
                        }
                        FileStream fileStream = File.OpenRead(localFacePath);
                        int        filelength = (int)fileStream.Length;
                        showFace = new byte[filelength];
                        fileStream.Read(showFace, 0, filelength);
                        #endregion
                    }
                    else
                    {
                        #region 从网络获取图片内容
                        {
                            try
                            {
                                HttpHelper http = new HttpHelper();
                                HttpItem   item = new HttpItem()
                                {
                                    URL              = Face,                  //URL     必需项
                                    Method           = "GET",                 //URL     可选项 默认为Get
                                    Timeout          = 5000,                  //连接超时时间     可选项默认为100000
                                    ReadWriteTimeout = 5000,                  //写入Post数据超时时间     可选项默认为30000
                                    ResultType       = ResultType.Byte,       //返回数据类型,是Byte还是String
                                    ProtocolVersion  = HttpVersion.Version11, //获取或设置用于请求的 HTTP 版本。默认为 System.Net.HttpVersion.Version11
                                };
                                HttpResult result = http.GetHtml(item);
                                showFace = result.ResultByte;
                            }
                            catch (Exception ex)
                            {
                                return(new WxResponse(0, "读取人脸图片失败,请重试", ex.Message).toJson());
                            }
                        }
                        #endregion
                    }
                    #endregion

                    #region 成员不存在,创建成员
                    if (null == moredianMember)
                    {
                        // 进行创建人员信息
                        IMoredianApiClient          client  = new DefaultMoredianApiClient(TianChengEntranceSyncService.Config.MoreDian.APIURL);
                        MoredianCreateMemberRequest request = new MoredianCreateMemberRequest
                        {
                            moredianMember = new MoredianMember
                            {
                                mobile     = Mobile,
                                memberName = Mobile,
                            },

                            showFace   = showFace,
                            verifyFace = showFace,
                        };
                        MoredianCreateMemberResponse response = client.Execute(request, app_token, access_token);
                        if (!response.IsSucc())
                        {
                            return(new WxResponse(0, "上传人脸信息失败,请重试", response.Message).toJson());
                        }
                        moredianMember = new MoredianMember
                        {
                            memberId = response.memberId,
                            mobile   = Mobile,
                            showFace = Face
                        };
                        erpConn.Execute("INSERT INTO [dbo].[Tb_HSPR_Entrance_Member](Mobile, MemberId, Face) VALUES (@Mobile, @MemberId, @Face)", new { Mobile, Face, MemberId = moredianMember.memberId });
                        moredianMember = MemberRedis.UpdateMoredianMember(Mobile);
                        return(new WxResponse(200, "上传人脸信息成功", moredianMember).toJson());
                    }
                    #endregion

                    if (string.IsNullOrEmpty(moredianMember.showFace) && string.IsNullOrEmpty(Face))
                    {
                        return(new WxResponse(200, "操作成功", null).toJson());
                    }

                    #region  除人脸
                    if (string.IsNullOrEmpty(Face))
                    {
                        // 更新显示图片
                        IMoredianApiClient client = new DefaultMoredianApiClient(TianChengEntranceSyncService.Config.MoreDian.APIURL);
                        MoredianDeleteMemberVerifyFaceRequest request = new MoredianDeleteMemberVerifyFaceRequest
                        {
                            memberId = moredianMember.memberId,
                        };
                        MoredianDeleteMemberVerifyFaceResponse response = client.Execute(request, app_token, access_token);
                        if (!response.IsSucc())
                        {
                            return(new WxResponse(0, "删除人脸信息失败", response.Message).toJson());
                        }
                        erpConn.Execute("UPDATE Tb_HSPR_Entrance_Member SET Face = @Face WHERE Mobile = @Mobile AND MemberId = @MemberId", new { Mobile, Face, MemberId = moredianMember.memberId });
                        moredianMember = MemberRedis.UpdateMoredianMember(Mobile);
                        return(new WxResponse(200, "删除人脸信息成功", moredianMember).toJson());
                    }
                    #endregion


                    #region 更新成员人脸
                    {
                        // 更新显示图片
                        IMoredianApiClient client = new DefaultMoredianApiClient(TianChengEntranceSyncService.Config.MoreDian.APIURL);
                        MoredianUpdateMemberVerifyFaceRequest request = new MoredianUpdateMemberVerifyFaceRequest
                        {
                            memberId = moredianMember.memberId,
                            face     = showFace
                        };
                        MoredianUpdateMemberVerifyFaceResponse response = client.Execute(request, app_token, access_token);
                        if (!response.IsSucc())
                        {
                            return(new WxResponse(0, "更新人脸信息失败,请重试", response.Message).toJson());
                        }
                    }
                    {
                        // 更新显示图片
                        IMoredianApiClient client = new DefaultMoredianApiClient(TianChengEntranceSyncService.Config.MoreDian.APIURL);
                        MoredianUpdateMemberShowFaceRequest request = new MoredianUpdateMemberShowFaceRequest
                        {
                            memberId = moredianMember.memberId,
                            face     = showFace
                        };
                        MoredianUpdateMemberShowFaceResponse response = client.Execute(request, app_token, access_token);
                        // 显示图片不处理失败情况
                    }
                    erpConn.Execute("UPDATE Tb_HSPR_Entrance_Member SET Face = @Face WHERE Mobile = @Mobile AND MemberId = @MemberId", new { Mobile, Face, MemberId = moredianMember.memberId });
                    moredianMember = MemberRedis.UpdateMoredianMember(Mobile);
                    return(new WxResponse(200, "更新人脸信息成功", moredianMember).toJson());

                    #endregion
                }
            }
            catch (Exception ex)
            {
                GetLog().Error(ex.Message + Environment.CommandLine + ex.StackTrace);
                return(new WxResponse(0, "响应异常", null).toJson());
            }
        }
示例#5
0
        public static bool Run(MoredianOrg moredianOrg)
        {
            if (null == moredianOrg)
            {
                return(false);
            }
            try
            {
                #region 获取AppToken
                string app_token = AppTokenRedis.GetAppToken();
                if (string.IsNullOrEmpty(app_token))
                {
                    return(false);
                }
                #endregion

                #region 获取AccessToken
                string access_token = AccessTokenRedis.GetAccessToken(Convert.ToString(moredianOrg.orgId), moredianOrg.orgAuthKey);
                if (string.IsNullOrEmpty(access_token))
                {
                    return(false);
                }
                #endregion
                using (IDbConnection erpConn = new SqlConnection(Config.EntranceConnectionStr))
                {
                    #region 初始化设备信息
                    // 先查询设备列表,如果不存在设备,后续都不用进行了
                    List <dynamic> DeviceList = erpConn.Query("SELECT Id, DeviceSn, DeviceId, CommID, BuildSNum, UnitSNum FROM Tb_HSPR_Entrance_Device WITH(NOLOCK)").ToList();
                    if (null == DeviceList || DeviceList.Count <= 0)
                    {
                        // 如果不存在设备,直接返回,不再进行下一步
                        return(false);
                    }
                    // 先查询未配置DeviceId的列表,去查询DeviceId信息
                    DeviceList = erpConn.Query("SELECT Id, DeviceSn, DeviceId FROM Tb_HSPR_Entrance_Device WITH(NOLOCK) WHERE ISNULL(DeviceId, 0) = 0").ToList();
                    // 检查设备配置信息,如果未获取DeveceId,调用接口查询一下
                    ConcurrentBag <Dictionary <string, string> > CreatedDeviceList = new ConcurrentBag <Dictionary <string, string> >();
                    Parallel.ForEach(new ConcurrentBag <dynamic>(DeviceList), (item) =>
                    {
                        try
                        {
                            string Id                            = Convert.ToString(item.Id);
                            string DeviceSn                      = Convert.ToString(item.DeviceSn);
                            IMoredianApiClient client            = new DefaultMoredianApiClient(Config.MoreDian.APIURL);
                            MoredianQueryDeviceIdRequest request = new MoredianQueryDeviceIdRequest
                            {
                                deviceSn = DeviceSn
                            };
                            MoredianQueryDeviceIdResponse response = client.Execute(request, app_token, access_token);
                            if (response.IsSucc())
                            {
                                string DeviceId = Convert.ToString(response.deviceId);
                                CreatedDeviceList.Add(new Dictionary <string, string>
                                {
                                    { "DeviceId", DeviceId },
                                    { "DeviceSn", DeviceSn },
                                    { "Id", Id }
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex.Message);
                        }
                    });
                    #endregion

                    #region 对查询结果回写进数据库
                    List <Dictionary <string, string> > CreatedDeviceArray = new List <Dictionary <string, string> >(CreatedDeviceList);
                    if (null != CreatedDeviceArray)
                    {
                        CreatedDeviceArray.ForEach(item =>
                        {
                            string DeviceId = item["DeviceId"];
                            string DeviceSn = item["DeviceSn"];
                            string Id       = item["Id"];
                            erpConn.Execute("UPDATE Tb_HSPR_Entrance_Device SET DeviceId = @DeviceId WHERE DeviceSn = @DeviceSn AND Id = @Id", new { DeviceId, DeviceSn, Id });
                        });
                    }
                    #endregion
                    return(true);
                }
            }
            catch (Exception ex)
            {
                // 内部会往外部抛异常,由外层统一接收处理
                Log.WriteLog(ex.Message);
                return(false);
            }
        }
示例#6
0
        /// <summary>
        /// 外部串行控制,不需要再开线程
        /// </summary>
        /// <returns>是否继续执行后续任务</returns>
        public static bool Run(MoredianOrg moredianOrg)
        {
            if (null == moredianOrg)
            {
                return(false);
            }
            try
            {
                #region 获取AppToken
                string app_token = AppTokenRedis.GetAppToken();
                if (string.IsNullOrEmpty(app_token))
                {
                    return(false);
                }
                #endregion

                #region 获取AccessToken
                string access_token = AccessTokenRedis.GetAccessToken(Convert.ToString(moredianOrg.orgId), moredianOrg.orgAuthKey);
                if (string.IsNullOrEmpty(access_token))
                {
                    return(false);
                }
                #endregion

                /* 2.按照规则初始化群组结构*/
                /* 2.1需要先判断是否存在成员,存在成员的话,根据成员手机号,查询WChat2020的Tb_User_Bind表绑定关系,根据绑定关系进行分类,聚合楼栋单元信息,进行创建群组以及权限分配*/
                using (IDbConnection conn = new SqlConnection(Config.WChat2020ConnectionStr)
                       , erpConn = new SqlConnection(Config.EntranceConnectionStr))
                {
                    // 需要添加的群组列表
                    List <Dictionary <string, string> > NeedAddGroupList = new List <Dictionary <string, string> >();

                    #region 建立每个小区的大门群组,如果数据库已存在,就不再创建了
                    List <dynamic> CommGroupInfoList = erpConn.Query("SELECT CommID, CommName FROM Tb_HSPR_Community WITH(NOLOCK) WHERE ISNULL(IsDelete,0) = 0").ToList();
                    if (null != CommGroupInfoList)
                    {
                        CommGroupInfoList.ForEach((item) =>
                        {
                            string CommID    = Convert.ToString(item.CommID);
                            string CommName  = Convert.ToString(item.CommName);
                            string BuildSNum = "0";
                            string UnitSNum  = "0";
                            // 如果已经创建过了,就不再创建了
                            if (erpConn.QueryFirstOrDefault <int>("SELECT COUNT(1) FROM Tb_HSPR_Entrance_Group WITH(NOLOCK) WHERE CommID = @CommID AND ISNULL(BuildSNum,0) = 0 AND ISNULL(UnitSNum,0) = 0", new { CommID }) <= 0)
                            {
                                NeedAddGroupList.Add(new Dictionary <string, string>
                                {
                                    { "CommID", CommID },
                                    { "CommName", CommName },
                                    { "BuildSNum", BuildSNum },
                                    { "UnitSNum", UnitSNum },
                                });
                            }
                        });
                    }
                    #endregion

                    #region 建立每个小区的单元群组
                    // 查询系统上所有的CommID,CommName, BuildSNum,UnitSNum
                    List <dynamic> GroupInfoList = erpConn.Query("SELECT CommID,CommName,BuildSNum,UnitSNum FROM view_HSPR_Room_Filter WITH(NOLOCK) WHERE ISNULL(IsDelete,0) = 0 GROUP BY CommID,CommName,BuildSNum,UnitSNum").ToList();
                    if (null != GroupInfoList)
                    {
                        GroupInfoList.ForEach(item =>
                        {
                            string CommID    = Convert.ToString(item.CommID);
                            string CommName  = Convert.ToString(item.CommName);
                            string BuildSNum = Convert.ToString(item.BuildSNum);
                            string UnitSNum  = Convert.ToString(item.UnitSNum);
                            // 如果已经创建过了,就不再创建了
                            if (erpConn.QueryFirstOrDefault <int>("SELECT COUNT(1) FROM Tb_HSPR_Entrance_Group WITH(NOLOCK) WHERE CommID = @CommID AND BuildSNum = @BuildSNum AND UnitSNum = @UnitSNum", new { CommID, BuildSNum, UnitSNum }) <= 0)
                            {
                                NeedAddGroupList.Add(new Dictionary <string, string>
                                {
                                    { "CommID", CommID },
                                    { "CommName", CommName },
                                    { "BuildSNum", BuildSNum },
                                    { "UnitSNum", UnitSNum },
                                });
                            }
                        });
                    }
                    #endregion

                    #region 批量创建群组
                    ConcurrentBag <Dictionary <string, string> > CreatedGroupList = new ConcurrentBag <Dictionary <string, string> >();
                    DateTime DateNow = DateTime.Now;
                    // 开始时间限制必须大于当前时间,所以限定生效时间为10分钟后
                    DateNow = DateNow.AddMinutes(10);
                    long beginDay = DateHelper.Get13TimeStamp(DateNow);
                    // 默认10年
                    long endDay = DateHelper.Get13TimeStamp(DateNow.AddYears(10));
                    Parallel.ForEach(new ConcurrentBag <Dictionary <string, string> >(NeedAddGroupList), (item) =>
                    {
                        try
                        {
                            string CommID    = item["CommID"];
                            string CommName  = item["CommName"];
                            string BuildSNum = item["BuildSNum"];
                            string UnitSNum  = item["UnitSNum"];
                            string groupName = $"{CommName}";
                            if (!"0".Equals(BuildSNum) || !"0".Equals(UnitSNum))
                            {
                                groupName += $"-{BuildSNum}-{UnitSNum}";
                            }
                            IMoredianApiClient client          = new DefaultMoredianApiClient(Config.MoreDian.APIURL);
                            MoredianCreateGroupRequest request = new MoredianCreateGroupRequest
                            {
                                moredianGroup = new MoredianGroup
                                {
                                    groupName       = groupName,
                                    allMemberStatus = 1,
                                    dayBeginTime    = "00:00",
                                    dayEndTime      = "00:01",
                                    beginDay        = beginDay,
                                    endDay          = endDay
                                }
                            };
                            MoredianCreateGroupResponse response = client.Execute(request, app_token, access_token);
                            if (response.IsSucc())
                            {
                                string GroupId = Convert.ToString(response.groupId);
                                CreatedGroupList.Add(new Dictionary <string, string>
                                {
                                    { "CommID", CommID },
                                    { "BuildSNum", BuildSNum },
                                    { "UnitSNum", UnitSNum },
                                    { "GroupId", GroupId }
                                });
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex.Message);
                        }
                    });
                    #endregion

                    #region 对创建结果回写进数据库
                    List <Dictionary <string, string> > CreatedGroupArray = new List <Dictionary <string, string> >(CreatedGroupList);
                    if (null != CreatedGroupArray)
                    {
                        CreatedGroupArray.ForEach(item =>
                        {
                            string CommID    = item["CommID"];
                            string BuildSNum = item["BuildSNum"];
                            string UnitSNum  = item["UnitSNum"];
                            string GroupId   = item["GroupId"];
                            erpConn.Execute("INSERT INTO Tb_HSPR_Entrance_Group(CommID, BuildSNum, UnitSNum, GroupId) VALUES (@CommID, @BuildSNum, @UnitSNum, @GroupId)", new { CommID, BuildSNum, UnitSNum, GroupId });
                        });
                    }
                    #endregion
                    // 群组创建完成

                    #region 更新设备与群组的关系
                    Dictionary <long, long[]> DeviceBind = new Dictionary <long, long[]>();
                    // 查询已更新设备ID的设备信息
                    List <long> DeviceList = erpConn.Query <long>("SELECT DeviceId FROM Tb_HSPR_Entrance_Device WITH(NOLOCK) WHERE ISNULL(DeviceId, 0) != 0").ToList();
                    if (null != DeviceList)
                    {
                        DeviceList.ForEach(DeviceId =>
                        {
                            long[] GroupIdList = erpConn.Query <long>("SELECT b.GroupId FROM Tb_HSPR_Entrance_Device a WITH(NOLOCK) LEFT JOIN Tb_HSPR_Entrance_Group b ON a.CommID = b.CommID AND a.BuildSNum = b.BuildSNum AND a.UnitSNum = b.UnitSNum WHERE a.DeviceId = @DeviceId", new { DeviceId }).ToArray();
                            if (null != GroupIdList && GroupIdList.Length > 0)
                            {
                                DeviceBind.Add(DeviceId, GroupIdList);
                            }
                        });
                    }
                    Parallel.ForEach(DeviceBind, (item) =>
                    {
                        try
                        {
                            long deviceId             = item.Key;
                            long[] groupIdList        = item.Value;
                            IMoredianApiClient client = new DefaultMoredianApiClient(Config.MoreDian.APIURL);
                            MoredianUpdateDeviceBindRequest request = new MoredianUpdateDeviceBindRequest
                            {
                                deviceId    = deviceId,
                                groupIdList = groupIdList
                            };
                            MoredianUpdateDeviceBindResponse response = client.Execute(request, app_token, access_token);
                            // 不处理结果,后续可能会记录绑定关系到数据库
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex.Message);
                        }
                    });
                    #endregion
                    // 后续绑定成员的时候进行更新群组
                    return(true);
                }
            }
            catch (Exception ex)
            {
                // 内部会往外部抛异常,由外层统一接收处理
                Log.WriteLog(ex.Message);
                return(false);
            }
        }
示例#7
0
        public static MoredianOrg GetMoredianOrg()
        {
            #region 先从Redis取值
            if (mRedis.KeyExists(KEY_MOREDIAN_ORG))
            {
                string json = mRedis.StringGet(KEY_MOREDIAN_ORG);
                try
                {
                    MoredianOrg moredianOrg = JsonConvert.DeserializeObject <MoredianOrg>(json);
                    // 检查是否存在OrgId以及OrgAuthKey这2个重要参数
                    if (null != moredianOrg && 0 != moredianOrg.orgId && !string.IsNullOrEmpty(moredianOrg.orgAuthKey))
                    {
                        return(moredianOrg);
                    }
                }
                catch (Exception)
                {
                }
            }
            #endregion

            #region  存在的情况下去数据库查询
            using (IDbConnection conn = new SqlConnection(Config.EntranceConnectionStr))
            {
                MoredianOrg moredianOrg = null;
                dynamic     info        = conn.QueryFirstOrDefault("SELECT OrgId,OrgAuthKey FROM Tb_HSPR_Entrance_Org WITH(NOLOCK)");
                if (null == info)
                {
                    #region 数据库也不存在,进行创建
                    IMoredianApiClient       client  = new DefaultMoredianApiClient(Config.MoreDian.APIURL);
                    MoredianCreateOrgRequest request = new MoredianCreateOrgRequest
                    {
                        moredianOrg = new MoredianOrg
                        {
                            orgName = Config.CorpName,
                            tpId    = Config.CorpID
                        }
                    };
                    MoredianCreateOrgResponse response = client.Execute(request);
                    if (null == response || !response.IsSucc())
                    {
                        // 创建失败,需要排查错误信息
                        Log.WriteLog($"创建机构失败({JsonConvert.SerializeObject(response)})");
                        return(null);
                    }
                    moredianOrg = new MoredianOrg
                    {
                        orgId      = response.orgId,
                        orgAuthKey = response.orgAuthKey
                    };
                    #endregion
                }
                else
                {
                    moredianOrg = new MoredianOrg
                    {
                        orgId      = Convert.ToInt64(info.OrgId),
                        orgAuthKey = Convert.ToString(info.OrgAuthKey),
                    };
                }
                // 刷新缓存值
                mRedis.StringSet(KEY_MOREDIAN_ORG, JsonConvert.SerializeObject(moredianOrg));
                return(moredianOrg);
            }
            #endregion
        }
示例#8
0
        public static bool Run(MoredianOrg moredianOrg)
        {
            if (null == moredianOrg)
            {
                return(false);
            }
            try
            {
                #region 获取AppToken
                string app_token = AppTokenRedis.GetAppToken();
                if (string.IsNullOrEmpty(app_token))
                {
                    return(false);
                }
                #endregion

                #region 获取AccessToken
                string access_token = AccessTokenRedis.GetAccessToken(Convert.ToString(moredianOrg.orgId), moredianOrg.orgAuthKey);
                if (string.IsNullOrEmpty(access_token))
                {
                    return(false);
                }
                #endregion

                using (IDbConnection conn = new SqlConnection(Config.WChat2020ConnectionStr)
                       , erpConn = new SqlConnection(Config.EntranceConnectionStr))
                {
                    #region 根据成员列表对应的手机号查询WChat2020公众号中绑定的所有房屋列表
                    List <string> MobileList = erpConn.Query <string>("SELECT Mobile FROM Tb_HSPR_Entrance_Member WITH(NOLOCK) GROUP BY Mobile").ToList();
                    if (null == MobileList || MobileList.Count <= 0)
                    {
                        // 如果不存在成员,直接返回,不再进行下一步
                        return(false);
                    }
                    // 根据手机号查询对于用户绑定的所有房屋并去重
                    List <string> RoomIDList = conn.Query <string>("SELECT a.RoomID FROM Tb_User_Bind a WITH(NOLOCK) JOIN Tb_User b WITH(NOLOCK) ON a.UserID = b.Id WHERE ISNULL(a.IsDelete,0) = 0 AND b.Mobile IN @MobileList GROUP BY a.RoomID", new { MobileList }).ToList();
                    if (null == RoomIDList || RoomIDList.Count <= 0)
                    {
                        // 如果不存在房屋,直接返回,不再进行下一步
                        return(false);
                    }
                    #endregion

                    #region 根据群组查出要关联的房屋信息,通过房屋RoomID查询出要关联的MemberId
                    // 后面要遍历更新权限的内容
                    Dictionary <long, long[]> MemberBindList = new Dictionary <long, long[]>();
                    // 先查询所有的群组信息
                    List <EntranceGroup> EntranceGroupList = erpConn.Query <EntranceGroup>("SELECT Id, CommID, BuildSNum, UnitSNum, GroupId FROM Tb_HSPR_Entrance_Group WITH(NOLOCK)").ToList();
                    if (null == EntranceGroupList || EntranceGroupList.Count <= 0)
                    {
                        // 不存在群组信息,不进行下一步
                        return(false);
                    }
                    // 查询所有应该分配权限的房间列表
                    List <EntranceRoom> EntranceRoomList = erpConn.Query <EntranceRoom>("SELECT CommID, BuildSNum, UnitSNum, RoomID FROM view_HSPR_Room_Filter WITH(NOLOCK) WHERE ISNULL(IsDelete, 0) = 0 AND RoomID IN @RoomIDList", new { RoomIDList }).ToList();
                    if (null == EntranceRoomList || EntranceRoomList.Count <= 0)
                    {
                        // 如果不存在房屋,直接返回,不再进行下一步
                        return(false);
                    }
                    // 遍历所有群组,将需要更新的权限写入
                    EntranceGroupList.ForEach(item =>
                    {
                        List <EntranceRoom> RoomList;
                        if (item.BuildSNum == 0 && item.UnitSNum == 0)
                        {
                            // 大门
                            RoomList = EntranceRoomList.Where(Room => Room.CommID == item.CommID).ToList();
                        }
                        else
                        {
                            // 单元门
                            RoomList = EntranceRoomList.Where(Room => Room.CommID == item.CommID && Room.BuildSNum == item.BuildSNum && Room.UnitSNum == item.UnitSNum).ToList();
                        }
                        if (null == RoomList || RoomList.Count <= 0)
                        {
                            // 如果没有房屋列表,不进行操作
                            return;
                        }
                        // 根据房屋列表信息,查询对应的手机号
                        List <string> RoomMobileList = conn.Query <string>("SELECT Mobile FROM Tb_User a WITH(NOLOCK) JOIN Tb_User_Bind b WITH(NOLOCK) ON a.Id = b.UserID WHERE ISNULL(b.IsDelete, 0) = 0 AND b.RoomID IN @RoomIDList", new { RoomIDList = RoomList.ConvertAll(room => room.RoomID).ToArray() }).ToList();
                        if (null == RoomList || RoomList.Count <= 0)
                        {
                            // 如果没有手机号列表,不进行操作
                            return;
                        }
                        long[] MemberList = erpConn.Query <long>("SELECT MemberId FROM Tb_HSPR_Entrance_Member WITH(NOLOCK) WHERE Mobile IN @RoomMobileList", new { RoomMobileList }).ToArray();
                        if (null == MemberList || MemberList.Length <= 0)
                        {
                            // 如果没有成员列表,不进行操作
                            return;
                        }
                        MemberBindList.Add(item.GroupId, MemberList);
                    });
                    DateTime DateNow = DateTime.Now;
                    // 开始时间限制必须大于当前时间,所以限定生效时间为10分钟后
                    DateNow = DateNow.AddMinutes(10);
                    long beginDay = DateHelper.Get13TimeStamp(DateNow);
                    // 默认10年
                    long endDay = DateHelper.Get13TimeStamp(DateNow.AddYears(10));
                    // 进行遍历关联
                    Parallel.ForEach(MemberBindList, (item) =>
                    {
                        try
                        {
                            long groupId                       = item.Key;
                            long[] memberIdList                = item.Value;
                            IMoredianApiClient client          = new DefaultMoredianApiClient(Config.MoreDian.APIURL);
                            MoredianUpdateGroupRequest request = new MoredianUpdateGroupRequest
                            {
                                moredianGroup = new
                                {
                                    groupId,
                                    allMemberStatus = 0,
                                    dayBeginTime    = "00:00",
                                    dayEndTime      = "23:59",
                                    beginDay        = beginDay,
                                    endDay          = endDay,
                                    memberIdList,
                                }
                            };
                            MoredianUpdateGroupResponse response = client.Execute(request, app_token, access_token);
                            // 不处理结果,后续可能会记录绑定关系到数据库
                        }
                        catch (Exception ex)
                        {
                            Log.WriteLog(ex.Message);
                        }
                    });
                    #endregion
                }
                return(true);
            }
            catch (Exception ex)
            {
                // 内部会往外部抛异常,由外层统一接收处理
                Log.WriteLog(ex.Message);
                return(false);
            }
        }