Пример #1
0
        /// <summary>
        /// 进行打卡
        /// </summary>
        /// <returns></returns>
        public bool Do()
        {
            GlobalVars.log.Info("正在进行打卡");
            FrmMain.statusHandler?.Invoke(null, new Msg("正在进行打卡"));
            // 先GET一下BASE,获取到WID、UID以及历史打卡数据
            HttpClientHandler handler = new HttpClientHandler
            {
                CookieContainer = this.cookie,
                UseCookies      = true
            };
            HttpClient client = new HttpClient(handler);

            client.Timeout = TimeSpan.FromSeconds(60);
            client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36");
            HttpResponseMessage res;

            try
            {
                res = client.GetAsync(IsBachelor ? BASE_BC : BASE).Result;
            }
            catch (AggregateException e)
            {
                GlobalVars.log.Error($"打卡凭据获取失败,请检查网络链接,详细信息:{e.Message}");
                FrmMain.statusHandler?.Invoke(null, new Msg("打卡凭据获取失败,请检查网络链接"));
                return(false);
            }
            // 把结果加载成HAP文档
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(res.Content.ReadAsStringAsync().Result);
            var scripts = doc.DocumentNode.Descendants()
                          .Where(n => n.Name == "script");
            string fullScript = "";

            foreach (var t in scripts)
            {
                if (t.InnerHtml.Length > 0)
                {
                    fullScript = t.InnerHtml;
                    break;
                }
            }
            // 解析WID和UID
            object result;
            string wid, uid;

            string[] fullScriptLines = fullScript.Split('\n');
            var      engine          = new Jurassic.ScriptEngine();

            try
            {
                result = engine.Evaluate("(function() { " + fullScriptLines[WIDLine] + "\n return _selfFormWid; })()");
                wid    = result.ToString();
                result = engine.Evaluate("(function() { " + fullScriptLines[UIDLine] + "\n return _userId; })()");
                uid    = result.ToString();
                // 检查uid是否合理
                long.Parse(uid);
            }
            catch (IndexOutOfRangeException e)
            {
                GlobalVars.log.Error($"解析WID和UID失败,错误类型1,详细信息:{e.Message}");
                FrmMain.statusHandler?.Invoke(null, new Msg("解析WID和UID失败"));
                return(false);
            }
            catch (Jurassic.JavaScriptException e)
            {
                GlobalVars.log.Error($"解析WID和UID失败,错误类型2,详细信息:{e.Message}");
                FrmMain.statusHandler?.Invoke(null, new Msg("解析WID和UID失败"));
                return(false);
            }
            catch (Exception e)
            {
                GlobalVars.log.Error($"解析WID和UID失败,错误类型3,详细信息:{e.Message}");
                FrmMain.statusHandler?.Invoke(null, new Msg("解析WID和UID失败"));
                return(false);
            }
            // 计算得到真正的API接口
            string realAPI = API + $"?wid={wid}&userId={uid}";
            // 取得往日填报信息
            StringBuilder sb = new StringBuilder();

            try
            {
                for (int i = FillBeginLine; i <= FillEndLine; i++)
                {
                    sb.Append(fullScriptLines[i]).Append("\n");
                }
            }
            catch (IndexOutOfRangeException e)
            {
                GlobalVars.log.Error($"解析历史打卡数据失败,详细信息:{e.Message}");
                FrmMain.statusHandler?.Invoke(null, new Msg("解析历史打卡数据失败"));
                return(false);
            }
            // 生成打卡信息
            BachelorCheckinData bachelorCheckinData = default(BachelorCheckinData);
            CheckinData         checkinData         = default(CheckinData);

            try
            {
                // 序列化填报信息
                result = engine.Evaluate("(function() { " + sb.ToString() + " return fillDetail; })()");
                string  json = JSONObject.Stringify(engine, result);
                dynamic fillDatas;
                // 将填报信息转换成打卡信息
                if (IsBachelor)
                {
                    fillDatas           = JsonConvert.DeserializeObject <List <BachelorFillData> >(json);
                    bachelorCheckinData = Utils.ChangeType <BachelorFillData, BachelorCheckinData>(fillDatas[0]);
                }
                else
                {
                    fillDatas   = JsonConvert.DeserializeObject <List <FillData> >(json);
                    checkinData = Utils.ChangeType <FillData, CheckinData>(fillDatas[0]);
                }
            }
            catch (Exception e)
            {
                GlobalVars.log.Error($"序列化历史打卡数据失败,详细信息:{e.Message}");
                FrmMain.statusHandler?.Invoke(null, new Msg("序列化历史打卡数据失败"));
                return(false);
            }
            // 赋值打卡数据的最后一项
            var now = DateTime.Now;
            var nvc = new List <KeyValuePair <string, string> >();

            if (IsBachelor)
            {
                bachelorCheckinData.DATETIME_CYCLE = now.ToString("yyyy/MM/dd");
                nvc = Utils.ConvertToKeyValuePairs <BachelorCheckinData>(bachelorCheckinData);
            }
            else
            {
                checkinData.DATETIME_CYCLE = now.ToString("yyyy/MM/dd");
                nvc = Utils.ConvertToKeyValuePairs <CheckinData>(checkinData);
            }
            // 打卡
            var req = new HttpRequestMessage(HttpMethod.Post, realAPI)
            {
                Content = new FormUrlEncodedContent(nvc)
            };

            try
            {
                res = client.SendAsync(req).Result;
            }
            catch (AggregateException e)
            {
                GlobalVars.log.Error($"传输打卡数据失败,请检查网络连接,详细信息:{e.Message}");
                FrmMain.statusHandler?.Invoke(null, new Msg("打卡失败,请检查网络链接"));
                return(false);
            }
            if (res.StatusCode == HttpStatusCode.OK)
            {
                GlobalVars.log.Info("打卡成功!");
                FrmMain.statusHandler?.Invoke(null, new Msg("打卡成功!"));
                return(true);
            }
            else
            {
                GlobalVars.log.Error($"打卡失败!服务器返回代码:{res.StatusCode}");
                FrmMain.statusHandler?.Invoke(null, new Msg("打卡失败,未知原因"));
                return(false);
            }
        }
Пример #2
0
        private void DataHandler(Message message)
        {
            StandardString standard = (StandardString)message;

            try
            {
                JObject stuff  = JObject.Parse(standard.data);
                var     status = (CLIENTCMD)((int)stuff["status"]);
                var     ip     = (string)stuff["ip"];
                switch (status)
                {
                case CLIENTCMD.REQUEST_PROFILE:
                    sendProfile(ip);
                    //dynamic product=new JOb
                    break;

                case CLIENTCMD.REQUEST_REG_PERSON_LIST:
                    List <CheckinData> personList = new List <CheckinData>();
                    try
                    {
                        JObject dataClient = JObject.Parse(standard.data);
                        if (dataClient["data"].Count() > 0)
                        {
                            foreach (var result in dataClient["data"])
                            {
                                string      serialId = (string)result["serialId"];
                                string      tick     = (string)result["tick"];
                                CheckinData person   = new CheckinData()
                                {
                                    SERIAL_ID = serialId, TIMECHECK = tick
                                };
                                personList.Add(person);
                            }
                            if (personList.Count > 0)
                            {
                                mainWindowModel.CheckinServer(personList);
                            }
                        }
                        try
                        {
                            dynamic product = new JObject();
                            product.status = SERVERRESPONSE.RESP_SUCCESS;
                            StandardString msg = new StandardString();
                            msg.data = product.ToString();
                            Publish(publishdata, msg);
                        }
                        catch (Exception ex)
                        {
                            logFile.Error(ex.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            dynamic product = new JObject();
                            product.status = SERVERRESPONSE.RESP_PERSONLIST_ERROR;
                            StandardString msg = new StandardString();
                            msg.data = product.ToString();
                            Publish(publishdata, msg);
                            logFile.Error(ex.Message);
                        }
                        catch (Exception exc)
                        {
                            logFile.Error(exc.Message);
                        }
                    }

                    break;
                }
            }
            catch (Exception ex)
            {
                logFile.Error(ex.Message);
            }
        }
Пример #3
0
        private void DataHandler(Message message)
        {
            StandardString standard = (StandardString)message;

            try
            {
                JObject stuff  = JObject.Parse(standard.data);
                var     status = (CLIENTCMD)((int)stuff["status"]);
                var     ip     = (string)stuff["ip"];
                switch (status)
                {
                case CLIENTCMD.REQUEST_PROFILE_ADD:
                    sendProfile(ip, SERVERRESPONSE.RESP_PROFILE_ADD, new List <ProfileRF>());
                    //dynamic product=new JOb
                    break;

                case CLIENTCMD.REQUEST_PROFILE_UPDATE:
                    sendProfile(ip, SERVERRESPONSE.RESP_PROFILE_UPDATE, new List <ProfileRF>());
                    //dynamic product=new JOb
                    break;

                case CLIENTCMD.REQUEST_PROFILE_DELETE:
                    sendProfile(ip, SERVERRESPONSE.RESP_PROFILE_DELETE, new List <ProfileRF>());
                    //dynamic product=new JOb
                    break;

                case CLIENTCMD.CONFIRM_SENT_PROFILE_SUCCESS:
                    OnFlagStatusClient.OnConfirmProfileSuccess = true;
                    break;

                case CLIENTCMD.REQUEST_SYNC_TIME:
                    dynamic productTimeSync = new JObject();
                    productTimeSync.status = (int)SERVERRESPONSE.RESP_SYNC_TIME;
                    productTimeSync.data   = DateTime.Now.Ticks;
                    StandardString msgTimeSync = new StandardString();
                    msgTimeSync.data = productTimeSync.ToString();
                    Publish(publishdata, msgTimeSync);
                    break;

                case CLIENTCMD.REQUEST_REG_PERSON_LIST:
                    List <CheckinData> personList = new List <CheckinData>();
                    try
                    {
                        JObject dataClient = JObject.Parse(standard.data);
                        if (dataClient["data"].Count() > 0)
                        {
                            foreach (var result in dataClient["data"])
                            {
                                string      serialId = (string)result["serialId"];
                                string      tick     = (string)result["tick"];
                                CheckinData person   = new CheckinData()
                                {
                                    SERIAL_ID = serialId, TIMECHECK = tick
                                };
                                personList.Add(person);
                            }
                            if (personList.Count > 0)
                            {
                                mainWindowModel.CheckinServer(ip, personList);
                            }
                        }
                        try
                        {
                            dynamic product = new JObject();
                            product.status = SERVERRESPONSE.RESP_SUCCESS;
                            StandardString msg = new StandardString();
                            msg.data = product.ToString();
                            Publish(publishdata, msg);
                        }
                        catch (Exception ex)
                        {
                            logFile.Error(ex.Message);
                            Constant.mainWindowPointer.WriteLog(ex.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            dynamic product = new JObject();
                            product.status = SERVERRESPONSE.RESP_PERSONLIST_ERROR;
                            StandardString msg = new StandardString();
                            msg.data = product.ToString();
                            Publish(publishdata, msg);
                            logFile.Error(ex.Message);
                            Constant.mainWindowPointer.WriteLog(ex.Message);
                        }
                        catch (Exception exc)
                        {
                            logFile.Error(exc.Message);
                            Constant.mainWindowPointer.WriteLog(ex.Message);
                        }
                    }

                    break;
                }
            }
            catch (Exception ex)
            {
                logFile.Error(ex.Message);
                Constant.mainWindowPointer.WriteLog(ex.Message);
            }
        }
Пример #4
0
        private async Task <string> MakeRegisterRequest(CheckinData checkinData, string appId)
        {
            Dictionary <string, string> postData = new Dictionary <string, string>();

            postData.Add("app", "org.chromium.linux");
            postData.Add("X-subtype", appId);
            postData.Add("device", checkinData.AndroidId.ToString());
            postData.Add("sender", Server.Base64Key);

            string token         = string.Empty;
            int    maxNumRetries = 5;
            int    numRetries    = 0;

            using (var httpClient = new HttpClient())
            {
                while (numRetries <= maxNumRetries)
                {
                    using (var content = new FormUrlEncodedContent(postData))
                    {
                        httpClient.DefaultRequestHeaders.Clear();
                        httpClient.DefaultRequestHeaders.ExpectContinue = false;
                        httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"AidLogin {checkinData.AndroidId}:{checkinData.SecurityToken}");
                        httpClient.DefaultRequestHeaders.ConnectionClose = true;

                        try
                        {
                            HttpResponseMessage response = await httpClient.PostAsync(registerUrl, content).ConfigureAwait(false);

                            if (response.StatusCode == HttpStatusCode.OK)
                            {
                                using (Stream stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                                {
                                    StreamReader reader         = new StreamReader(stream, Encoding.UTF8);
                                    var          responseString = reader.ReadToEnd();
                                    var          tokens         = responseString.Split('=');

                                    if (tokens[0] != "Error")
                                    {
                                        token = tokens[1];
                                        break;
                                    }
                                }
                            }
                            else
                            {
                                throw new InvalidOperationException("Cannot register to GCM");
                            }
                        }
                        catch (Exception ex)
                        {
                            if (numRetries >= maxNumRetries)
                            {
                                throw new InvalidOperationException("Cannot register to GCM", ex);;
                            }

                            await Task.Delay(1000);
                        }
                    }

                    numRetries++;
                }
            }

            return(token);
        }