gxc
2020-02-28 66a9965c44ecc32a6696abca876ab9d1cd091584
ZigbeeApp/Shared/Phone/UserCenter/CommonBase/Logic/UserCenterLogic.cs
old mode 100755 new mode 100644
@@ -29,6 +29,13 @@
        /// </param>
        public static async Task<bool> GetResultStatuByRequestHttps(string RequestName, bool checkAuthority, object obj, List<string> listNotShowError = null)
        {
            //检测是否已经完成账号信息初始化
            if (UserCenterResourse.UserInfo.InitUserInfoSuccess == false)
            {
                //不管结果怎么样,如果调用了这个函数,需要重头获取Token,所以必须返回失败
                await ReInitUserAccoutInfo();
                return false;
            }
            //获取接口的连接模式
            var connectMode = GetHttpConnectMode(checkAuthority);
            //获取从接口那里取到的比特数据
@@ -63,6 +70,14 @@
        /// </param>
        public static async Task<string> GetResultCodeByRequestHttps(string RequestName, bool checkAuthority, object obj, List<string> listNotShowError = null)
        {
            //检测是否已经完成账号信息初始化
            if (UserCenterResourse.UserInfo.InitUserInfoSuccess == false)
            {
                //不管结果怎么样,如果调用了这个函数,需要重头获取Token,所以必须返回失败
                await ReInitUserAccoutInfo();
                return "Error";
            }
            //获取接口的连接模式
            var connectMode = GetHttpConnectMode(checkAuthority);
            //获取从接口那里取到的比特数据
@@ -96,6 +111,13 @@
        /// </param>
        public static async Task<string> GetResponseDataByRequestHttps(string RequestName, bool checkAuthority, object obj, List<string> listNotShowError = null)
        {
            //检测是否已经完成账号信息初始化
            if (UserCenterResourse.UserInfo.InitUserInfoSuccess == false)
            {
                //不管结果怎么样,如果调用了这个函数,需要重头获取Token,所以必须返回失败
                await ReInitUserAccoutInfo();
                return null;
            }
            //获取接口的连接模式
            var connectMode = GetHttpConnectMode(checkAuthority);
            //获取从接口那里取到的比特数据
@@ -139,6 +161,13 @@
        /// </param>
        public static async Task<byte[]> GetByteResponseDataByRequestHttps(string RequestName, bool checkAuthority, object obj, List<string> listNotShowError = null)
        {
            //检测是否已经完成账号信息初始化
            if (UserCenterResourse.UserInfo.InitUserInfoSuccess == false)
            {
                //不管结果怎么样,如果调用了这个函数,需要重头获取Token,所以必须返回失败
                await ReInitUserAccoutInfo();
                return null;
            }
            //获取接口的连接模式
            var connectMode = GetHttpConnectMode(checkAuthority);
            //获取从接口那里取到的比特数据
@@ -259,6 +288,11 @@
        /// <param name="pra">请求的参数</param>
        public static bool CheckNotEorrorMsg(ResponsePack revertObj, string RequestName, List<string> listNotShowError = null, object pra = null)
        {
            if (listNotShowError != null && listNotShowError.Contains("NotCheck") == true)
            {
                //不检测
                return true;
            }
            if (revertObj == null)
            {
                Application.RunOnMainThread(() =>
@@ -345,7 +379,6 @@
            var formTemp = UserCenterResourse.DicActionForm[formName];
            formTemp.CloseForm();
            UserCenterResourse.DicActionForm.Remove(formName);
            formTemp = null;
            return true;
        }
@@ -402,11 +435,13 @@
                            {
                                try
                                {
                                    var Myform = UserCenterResourse.DicActionForm[UserCenterResourse.NowActionFormID];
                                    if (Myform is EditorCommonForm)
                                    EditorCommonForm Myform = UserCenterResourse.DicActionForm[UserCenterResourse.NowActionFormID] as EditorCommonForm;
                                    if (Myform != null)
                                    {
                                        //重置左滑使能
                                        Myform.ScrollEnabled = Myform.ScrollEnabled;
                                        //触发界面再次激活的事件
                                        int value = ((EditorCommonForm)Myform).FormActionAgainEvent();
                                        int value = Myform.FormActionAgainEvent();
                                        if (value == 1)
                                        {
                                            //Log出力
@@ -417,7 +452,7 @@
                                catch (Exception ex)
                                {
                                    //出现未知错误,数据丢失
                                    var alert = new ShowMsgControl(ShowMsgType.Error, Language.StringByID(R.MyInternationalizationString.uUnknownErrorAndDataLost));
                                    var alert = new ShowMsgControl(ShowMsgType.Error, Language.StringByID(R.MyInternationalizationString.uUnKnownError));
                                    alert.Show();
                                    //Log出力
@@ -437,11 +472,13 @@
                                {
                                    try
                                    {
                                        var Myform = UserCenterResourse.DicActionForm[UserCenterResourse.NowActionFormID];
                                        if (Myform is EditorCommonForm)
                                        EditorCommonForm Myform = UserCenterResourse.DicActionForm[UserCenterResourse.NowActionFormID] as EditorCommonForm;
                                        if (Myform != null)
                                        {
                                            //重置左滑使能
                                            Myform.ScrollEnabled = Myform.ScrollEnabled;
                                            //触发界面再次激活的事件
                                            int value = ((EditorCommonForm)Myform).FormActionAgainEvent();
                                            int value = Myform.FormActionAgainEvent();
                                            if (value == 1)
                                            {
                                                //Log出力
@@ -452,7 +489,7 @@
                                    catch (Exception ex)
                                    {
                                        //出现未知错误,数据丢失
                                        var alert = new ShowMsgControl(ShowMsgType.Error, Language.StringByID(R.MyInternationalizationString.uUnknownErrorAndDataLost));
                                        var alert = new ShowMsgControl(ShowMsgType.Error, Language.StringByID(R.MyInternationalizationString.uUnKnownError));
                                        alert.Show();
                                        //Log出力
@@ -466,9 +503,7 @@
                //移除ID
                UserCenterResourse.listActionFormId.Remove(UserCenterResourse.DicActionForm[formName].FormID);
                //移除画面
                var formTemp = UserCenterResourse.DicActionForm[formName];
                UserCenterResourse.DicActionForm.Remove(formName);
                formTemp = null;
            }
        }
@@ -520,6 +555,7 @@
            HdlGatewayLogic.Current.SynchronizeDbGateway();
            //从本地重新加载全部的房间
            Common.Room.RefreshAllRoomByLocation();
        }
        /// <summary>
@@ -615,8 +651,7 @@
            //关闭所有接收
            HdlGatewayReceiveLogic.Current.RemoveAllEvent();
            //清除升级列表
            FirmwareUpdateResourse.dicDeviceUpdateList.Clear();
            FirmwareUpdateResourse.dicGatewayUpdateList.Clear();
            FirmwareUpdateResourse.dicUpdateList.Clear();
            HdlThreadLogic.Current.RunThread(async () =>
            {
@@ -639,11 +674,6 @@
                }
                catch { }
                if (noticeDb == true)
                {
                    //通知云端,已经退出登陆
                    var result = await CommonPage.Instance.RequestHttpsZigbeeBytesResultAsync("ZigbeeUsers/SignOut", null, "GET");
                }
                HdlThreadLogic.Current.RunMain(() =>
                {
                    //关闭所有打开了的界面
@@ -654,6 +684,12 @@
                    Shared.Common.CommonPage.Instance.AddChidren(formLogin);
                    formLogin.Show(account);
                });
                if (noticeDb == true)
                {
                    //通知云端,已经退出登陆
                    var result = await CommonPage.Instance.RequestHttpsZigbeeBytesResultAsync("ZigbeeUsers/SignOut", null, "GET");
                }
            });
        }
@@ -800,10 +836,14 @@
        /// <summary>
        /// 异步方法执行(仅限切换住宅时调用),刷新个人中心的内存及线程
        /// </summary>
        public async static Task<bool> InitUserCenterMenmoryAndThread()
        /// <param name="ShowPrompted">新追加变量:是否显示提示自动备份的界面</param>
        /// <returns></returns>
        public async static Task<bool> InitUserCenterMenmoryAndThread(bool ShowPrompted = true)
        {
            //APP缓存加载开始
            UserCenterResourse.Option.AppCanSignout = false;
            //还原远程连接变量
            ZigBee.Device.ZbGateway.AllowRemoteCtrl = true;
            //只有在住宅ID不一样的时候才做这个操作
            if (Common.Config.Instance.HomeId != UserCenterResourse.Option.OldHomeStringId
@@ -812,12 +852,22 @@
                try
                {
                    //断开远程Mqtt连接
                    ZigBee.Device.ZbGateway.DisConnectRemoteMqttClient();
                    await ZigBee.Device.ZbGateway.DisConnectRemoteMqttClient();
                }
                catch { }
                //消息记录重新读取及检测
                ControlCommonResourse.ReadMessageAgain = true;
                ControlCommonResourse.HadNewMessage = false;
                HdlThreadLogic.Current.RunMain(() =>
                {
                    for (int i = 0; i < ControlCommonResourse.listMessageManaContr.Count; i++)
                    {
                        //显示角标特效
                        ControlCommonResourse.listMessageManaContr[i].IsSelected = false;
                    }
                });
                //加载账号配置信息
                var optionInfo = UserCenterResourse.Option.Load();
                UserCenterResourse.Option = optionInfo;
@@ -831,6 +881,8 @@
                {
                    //重新发送命令去绑定断网情况下备份的网关
                    HdlGatewayLogic.Current.ResetComandToBindBackupGateway();
                    //读取隐匿配置
                    await HdlBackupLogic.Current.LoadHideOption();
                }
                //初始化缓存成员的信息
@@ -868,9 +920,6 @@
                    HdlGatewayLogic.Current.SynchronizeDbGateway();
                }
                //初始化住宅对象
                Common.Config.Instance.Home = House.GetHouseByHouseId(Common.Config.Instance.HomeId);
                //初始化房间(郭雪城那边不做处理,需要这里特殊执行一步)
                Room.RefreshAllRoomByLocation();
@@ -878,11 +927,13 @@
                HdlGatewayLogic.Current.RefreshAppOldSelectGatewayId();
                //0:已经同步过,不需要同步,这个时候需要提示备份
                if (result == 0)
                if (result == 0 && ShowPrompted == true)
                {
                    //开启自动备份提示
                    HdlAutoBackupLogic.ShowAutoBackupPromptedForm();
                }
                //显示引导界面
                ShowGuideForm(result);
            }
            //APP缓存加载完成
            UserCenterResourse.Option.AppCanSignout = true;
@@ -900,22 +951,32 @@
        /// <returns></returns>
        private async static Task<bool> InitUserAccoutInfo()
        {
            //初始化个人信息的标识
            UserCenterResourse.UserInfo.InitUserInfoSuccess = false;
            //获取本地记录的用户信息
            UserCenterResourse.UserInfo = GetUserInformationFromLocation();
            UserCenterResourse.UserInfo.UserIconFile = System.IO.Path.Combine(UserCenterResourse.Option.UserPictruePath, "Admin.png");
            //先根据本地缓存设置初始值
            Config.Instance.isAdministrator = UserCenterResourse.UserInfo.AuthorityNo != 1;
            //获取登录账号的信息
            var pra = new AccountInfoPra();
            var listNotShow = new List<string>() { "NotSetAgain" };
            string result = await UserCenterLogic.GetResponseDataByRequestHttps("ZigbeeUsers/GetAccountInfo", false, pra, listNotShow);
            if (string.IsNullOrEmpty(result) == true)
            //序列化对象
            var requestJson = JsonConvert.SerializeObject(pra);
            //访问接口
            byte[] byteData = await CommonPage.Instance.RequestHttpsZigbeeBytesResultAsync("ZigbeeUsers/GetAccountInfo", Encoding.UTF8.GetBytes(requestJson));
            if (byteData == null)
            {
                //断网的话,该干嘛就干嘛吧,总之不能控主人的东西
                Config.Instance.isAdministrator = false;
                return false;
            }
            //检测错误
            var revertObj = JsonConvert.DeserializeObject<ResponsePack>(Encoding.UTF8.GetString(byteData));
            if (revertObj.StateCode.ToUpper() != "SUCCESS")
            {
                return false;
            }
            var userInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInformation>(result);
            var userInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInformation>(revertObj.ResponseData.ToString());
            userInfo.Account = Common.Config.Instance.Account;
            if (string.IsNullOrEmpty(userInfo.UserName) == true)
            {
@@ -948,22 +1009,23 @@
                string dirPath = CombinePath();
                if (System.IO.Directory.Exists(dirPath) == true)
                {
                    //先记录起住宅的一些信息
                    var house = House.GetHouseByHouseId(Config.Instance.HomeId);
                    //删除整个文件夹
                    System.IO.Directory.Delete(dirPath, true);
                    try
                    {
                        //同步数据的判断文件(以防万一删除整个文件夹失败的时候,这个文件被删的话,应该没什么大问题)
                        string SynchronizeFile = UserCenterLogic.CombinePath(DirNameResourse.LocalMemoryDirectory, DirNameResourse.AutoDownLoadBackupCheckFile);
                        //如果本地已经拥有了这个文件,则说明不是新手机,不再自动还原
                        if (System.IO.File.Exists(SynchronizeFile) == true)
                        {
                            System.IO.File.Delete(SynchronizeFile);
                        }
                        //删除整个文件夹
                        System.IO.Directory.Delete(dirPath, true);
                    }
                    catch { }
                    //创建住宅文件夹
                    Global.CreateHomeDirectory(Config.Instance.HomeId);
                    //预创建个人中心全部的文件夹
                    CreatAllUserCenterDirectory();
                    var newHouse = new House();
                    newHouse.Id = house.Id;
                    newHouse.Name = house.Name;
                    newHouse.IsOthreShare = house.IsOthreShare;
                    newHouse.AccountType = house.AccountType;
                    newHouse.MainUserDistributedMark = house.MainUserDistributedMark;
                    newHouse.Save(false);
                }
            }
            if (string.IsNullOrEmpty(userInfo.UserName) == true)
@@ -988,9 +1050,11 @@
            UserCenterResourse.UserInfo.StringPwd = null;
            //初始化管理员控制主人的连接地址(因为这个连接Token是不会改变的,所以只需要初始化一次)
            await InitAdminConnectMainInfo();
            bool flage = await InitAdminConnectMainInfo();
            //初始化个人信息的标识
            UserCenterResourse.UserInfo.InitUserInfoSuccess = flage;
            return true;
            return flage;
        }
        /// <summary>
@@ -1007,6 +1071,26 @@
            }
            var info = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInformation>(value);
            return info;
        }
        /// <summary>
        /// 重新初始化登陆账号的信息(旨在对应那一瞬间,网络不好,导致误判的情况)
        /// </summary>
        /// <returns></returns>
        private async static Task<bool> ReInitUserAccoutInfo()
        {
            //重新初始化账号信息
            var result = await InitUserAccoutInfo();
            if (result == false)
            {
                return result;
            }
            //同步云端的网关id,如果本地拥有云端不存在的id,则表示应该被换绑了,直接删除
            HdlGatewayLogic.Current.SynchronizeDbGateway();
            //初始化个人信息的标识
            UserCenterResourse.UserInfo.InitUserInfoSuccess = true;
            return true;
        }
        /// <summary>
@@ -1040,13 +1124,8 @@
        /// 初始化管理员权限远程连接主人的信息
        /// </summary>
        /// <returns></returns>
        public static async Task<bool> InitAdminConnectMainInfo()
        private static async Task<bool> InitAdminConnectMainInfo()
        {
            //先清空
            Config.Instance.isAdministrator = false;
            Config.Instance.AdminRequestBaseUrl = string.Empty;
            Config.Instance.AdminRequestToken = string.Empty;
            if (UserCenterResourse.UserInfo.AuthorityNo != 2 && UserCenterResourse.UserInfo.AuthorityNo != 3)
            {
                //时代变了,这里管理员和成员都能调用
@@ -1060,16 +1139,24 @@
                SharedHid = Config.Instance.Home.Id
            };
            var listNotShow = new List<string>() { "NotSetAgain" };
            var result = await GetResponseDataByRequestHttps("App/GetSharedHomeApiControl", false, pra, listNotShow);
            if (string.IsNullOrEmpty(result) == true)
            //序列化对象
            var requestJson = JsonConvert.SerializeObject(pra);
            //访问接口
            byte[] byteData = await CommonPage.Instance.RequestHttpsZigbeeBytesResultAsync("App/GetSharedHomeApiControl", Encoding.UTF8.GetBytes(requestJson));
            if (byteData == null)
            {
                return false;
            }
            //检测错误
            var revertObj = JsonConvert.DeserializeObject<ResponsePack>(Encoding.UTF8.GetString(byteData));
            if (revertObj.StateCode.ToUpper() != "SUCCESS")
            {
                return false;
            }
            Config.Instance.isAdministrator = true;
            //分享链接
            var info = JsonConvert.DeserializeObject<MemberAdministratorResult>(result);
            var info = JsonConvert.DeserializeObject<MemberAdministratorResult>(revertObj.ResponseData.ToString());
            Config.Instance.AdminRequestBaseUrl = info.RequestBaseUrl;
            Config.Instance.AdminRequestToken = info.RequestToken;
@@ -1177,6 +1264,36 @@
        #endregion
        #region ■ 引导界面___________________________
        /// <summary>
        /// 显示引导界面
        /// </summary>
        /// <param name="result">同步结果 -1:异常   0:已经同步过,不需要同步  1:正常同步  2:没有自动备份数据</param>
        private static void ShowGuideForm(int result)
        {
            var checkFile = System.IO.Path.Combine(Shared.IO.FileUtils.RootPath, DirNameResourse.GuideFile);
            if (System.IO.File.Exists(checkFile) == true)
            {
                //不需要显示
                return;
            }
            if (result == 2 && Config.Instance.Home.IsOthreShare == false)
            {
                HdlThreadLogic.Current.RunMain(() =>
                {
                    var form = new Guide.GuideHouseForm();
                    form.ShowFrom();
                });
            }
            //创建一个空文件(标识已经完成引导)
            var file = System.IO.File.Create(checkFile);
            file.Close();
        }
        #endregion
        #region ■ 16进制转化_________________________
        /// <summary>
@@ -1226,24 +1343,28 @@
        /// <returns></returns>
        public static string EncryptPassword(string keys, string strPsw)
        {
            if (strPsw == string.Empty)
            try
            {
                return strPsw;
                if (strPsw == string.Empty)
                {
                    return strPsw;
                }
                var des = new System.Security.Cryptography.DESCryptoServiceProvider();
                byte[] inputByteArray = Encoding.Default.GetBytes(strPsw);
                des.Key = ASCIIEncoding.ASCII.GetBytes(keys);
                des.IV = ASCIIEncoding.ASCII.GetBytes(keys);
                var ms = new System.IO.MemoryStream();
                var cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                foreach (byte b in ms.ToArray())
                {
                    ret.AppendFormat("{0:X2}", b);
                }
                return ret.ToString().ToLower();
            }
            var des = new System.Security.Cryptography.DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(strPsw);
            des.Key = ASCIIEncoding.ASCII.GetBytes(keys);
            des.IV = ASCIIEncoding.ASCII.GetBytes(keys);
            var ms = new System.IO.MemoryStream();
            var cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
            catch { return strPsw; }
        }
        /// <summary>
@@ -1253,32 +1374,51 @@
        /// <returns></returns>
        public static string DecryptPassword(string keys, string strPsw)
        {
            if (strPsw == string.Empty)
            try
            {
                return strPsw;
                if (strPsw == string.Empty)
                {
                    return strPsw;
                }
                var des = new System.Security.Cryptography.DESCryptoServiceProvider();
                byte[] inputByteArray = new byte[strPsw.Length / 2];
                for (int x = 0; x < strPsw.Length / 2; x++)
                {
                    int i = (Convert.ToInt32(strPsw.Substring(x * 2, 2), 16));
                    inputByteArray[x] = (byte)i;
                }
                des.Key = ASCIIEncoding.ASCII.GetBytes(keys);
                des.IV = ASCIIEncoding.ASCII.GetBytes(keys);
                var ms = new System.IO.MemoryStream();
                var cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                StringBuilder ret = new StringBuilder();
                return System.Text.Encoding.Default.GetString(ms.ToArray());
            }
            var des = new System.Security.Cryptography.DESCryptoServiceProvider();
            byte[] inputByteArray = new byte[strPsw.Length / 2];
            for (int x = 0; x < strPsw.Length / 2; x++)
            {
                int i = (Convert.ToInt32(strPsw.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }
            des.Key = ASCIIEncoding.ASCII.GetBytes(keys);
            des.IV = ASCIIEncoding.ASCII.GetBytes(keys);
            var ms = new System.IO.MemoryStream();
            var cs = new System.Security.Cryptography.CryptoStream(ms, des.CreateDecryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            return System.Text.Encoding.Default.GetString(ms.ToArray());
            catch { return strPsw; }
        }
        #endregion
        #region ■ 时间转换___________________________
        /// <summary>
        /// 将utc时间类型的字符串,转换为本地时间
        /// </summary>
        /// <param name="timeText"></param>
        /// <returns></returns>
        public static DateTime ConvertUtcTimeToLocalTime(string timeText)
        {
            var utcTime = Convert.ToDateTime(timeText);
            return TimeZoneInfo.ConvertTimeFromUtc(utcTime, TimeZoneInfo.Local);
        }
        #endregion
        #region ■ 文件保存和读取_____________________
        /// <summary>