Ejemplo n.º 1
0
        internal static void HandleClient(NetStream stream, IPEndPoint ip)
        {
            try {
                var ssl = new SslStream(stream);
                ssl.AuthenticateAsServer(Certificate);
                stream = ssl;
            } catch (Exception e) {
                stream.Write("ERR_SSL\r\n");
                stream.Write(e.ToString());
                return;
            }

            stream.Encoding = Encoding.ASCII;
            var encdodingstring = stream.Read();
            int codepage;

            if (int.TryParse(encdodingstring, out codepage))
            {
                try {
                    var cpenc = Encoding.GetEncoding(codepage);
                    stream.Encoding = cpenc;
                    stream.Write("success");
                } catch {
                    stream.Write("ERR_ENCODING_NOT_FOUND");
                    stream.Close();
                    return;
                }
            }
            else
            {
                try {
                    var encoding = Encoding.GetEncoding(encdodingstring);
                    stream.Encoding = encoding;
                    stream.Write("success");
                } catch {
                    stream.Write("ERR_ENCODING_NOT_FOUND");
                    stream.Close();
                    return;
                }
            }

            try {
                var cred = Authenticate(stream);
                if (!cred.Successful)
                {
                    stream.Close();
                    return;
                }
                stream.Write("LOGIN_SUCCESS");
                ClientLoop.BeginClient(new Client(stream, cred.Username, cred.SecurityLevel, ip));
            } catch (Exception ex) {
                stream.Write("ERR\r\n");
                stream.Write(ex.ToString());
            }
        }
Ejemplo n.º 2
0
        //将jw2005.scuteo.com通过302重定向到指定的ip地址
        private void url_locate_callback(NetStream sender, object e)
        {
            //失败重试
            if (sender.HTTP_Response == null || (int)sender.HTTP_Response.StatusCode > 400)
            {
                if (sender.HTTP_Response == null)
                {
                    debug_output("重定向出错,3s后重试");
                }
                else
                {
                    debug_output("重定向出错:服务器返回状态码 " + (int)sender.HTTP_Response.StatusCode + "(" + sender.HTTP_Response.StatusCode.ToString() + "),3s后重试");
                }
                Thread.Sleep(3000);
                var url = sender.HTTP_Request.RequestUri.ToString();
                sender.Close();

                var ns = new NetStream();
                ns.HttpGetAsync(main_page_url, url_locate_callback, null);
                return;
            }

            //将主页url更改成30X跳转后响应的url
            main_page_url = sender.HTTP_Response.ResponseUri.ToString();
            //获取主页面的html信息(gb2312编码)
            var str_main_page = sender.ReadResponseString(Encoding.Default);

            //关闭http请求
            sender.Close();

            //正则匹配,获取viewstate
            var match = Regex.Match(str_main_page, "<input\\stype=\"hidden\"\\sname=\"__VIEWSTATE\"\\svalue=\"(?<value>[^\"]*?)\"\\s*/>");

            if (match.Success)
            {
                __VIEWSTATE = match.Result("${value}");
            }
            else
            {
                debug_output("获取VIEWSTATE属性值失败,3s后重试");
                Thread.Sleep(3000);
                var ns = new NetStream();
                ns.HttpGetAsync(main_page_url, url_locate_callback, null);
                return;
            }

            //刷新验证码
            refresh_captcha();
            //登陆按钮可点(委托到主线程)
            Invoke(new ThreadStart(delegate
            {
                login.Enabled = true;
            }));
        }
Ejemplo n.º 3
0
        //获取验证信息
        private static void _fetch_auth_info()
        {
            if (string.IsNullOrEmpty(_access_token))
            {
                throw new ArgumentNullException("Access Token could not be null or empty");
            }
            var ns    = new NetStream();
            var param = new Parameters();

            param.Add("access_token", _access_token);
            param.Add("appkey", APPKEY);
            param.Add("build", "513000");
            param.Add("mobi_app", "android");
            param.Add("platform", "android");
            param.Add("ts", (long)util.ToUnixTimestamp(DateTime.Now));
            param.Add("sign", CalculateSign(param));

            ns.UserAgent = ANDROID_USER_AGENT;
            try
            {
                ns.HttpGet(_URL_AUTH_INFO, urlParam: param);
                var response = ns.ReadResponseString();
                ns.Close();

                var json = JsonConvert.DeserializeObject(response) as JObject;
                int code = json.Value <int>("code");

                if (code != 0)
                {
                    Tracer.GlobalTracer.TraceError("Error code: " + code);
                    Tracer.GlobalTracer.TraceError(json.ToString());
                }
                else
                {
                    _appid = json["data"].Value <int>("appid");
                    var ts = util.FromUnixTimestamp(json.Value <long>("ts"));
                    _expire_time = ts.AddSeconds(json["data"].Value <int>("expires_in"));
                    _mid         = json["data"].Value <uint>("mid");
                    _uname       = json["data"].Value <string>("uname");
                    _userid      = json["data"].Value <string>("userid");
                }
            }
            catch (Exception ex)
            {
                Tracer.GlobalTracer.TraceError(ex.ToString());
                throw ex;
            }
            finally
            {
                ns.Close();
            }
        }
Ejemplo n.º 4
0
        public void Handle()
        {
            mClient.WriteString(this.Response);

            try
            {
                while (true)
                {
                    if (mRemotingHandler.StreamType == RemotingClientHandler.RemotingStreamType.Text)
                    {
                        string text = readSocketText();
                        if (text.Length == 0)
                        {
                            //客户端断开
                            mClient.Close();
                            continue;
                        }
                        try
                        {
                            mRemotingHandler.OnReceived(text);
                        }
                        catch
                        {
                        }
                    }
                    else
                    {
                        byte[] content = readSocketBytes();
                        if (content.Length == 0)
                        {
                            //客户端断开
                            mClient.Close();
                            continue;
                        }
                        try
                        {
                            mRemotingHandler.OnReceived(content);
                        }
                        catch
                        {
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                mRemotingHandler.OnDisconnected();
            }
        }
Ejemplo n.º 5
0
        public override void Handle(NetStream stream, Command command)
        {
            this.serverObj.AddPointToWatch(command, (index, valuetype, value) => {
                stream.Write(index);//写index
                stream.Write((int)valuetype);
                if (valuetype == PointValueType.Short)
                {
                    stream.Write((short)value);
                }
                else if (valuetype == PointValueType.Int)
                {
                    stream.Write((int)value);
                }
                else if (valuetype == PointValueType.Float)
                {
                    stream.Write((float)value);
                }
                else if (valuetype == PointValueType.String)
                {
                    byte[] bs = System.Text.Encoding.UTF8.GetBytes((string)value);
                    stream.Write(bs.Length);
                    stream.Write(bs);
                }
                else
                {
                    stream.Dispose();
                }
            });

            stream.Close();
        }
Ejemplo n.º 6
0
        private void TestFunc()
        {
            var url         = "https://pan.baidu.com/api/report/user";
            var query_param = new Parameters();

            query_param.Add("channel", "chunlei");
            query_param.Add("web", 1);
            query_param.Add("app_id", BaiduPCS.APPID);
            query_param.Add("bdstoken", _bdstoken);
            query_param.Add("logid", BaiduPCS.GetLogid());
            query_param.Add("clienttype", 0);

            var post_param = new Parameters();

            post_param.Add("timestamp", (long)util.ToUnixTimestamp(DateTime.Now));
            post_param.Add("action", "fm_self");

            var ns = new NetStream();

            ns.CookieKey = _cookie_identifier;

            var header = new Parameters();

            header.Add("X-Requested-With", "XMLHttpRequest");
            header.Add("Origin", "http://pan.baidu.com");
            header.Add("Referer", BaiduPCS.BAIDU_NETDISK_URL);

            ns.HttpPost(url, post_param, headerParam: header, urlParam: query_param);
            var rep = ns.ReadResponseString();

            ns.Close();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 从url处获取图像(经过memory缓存)
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private static Image _load_image_from_url(string url)
        {
            var req = new NetStream();

            req.RetryTimes = 3;
            var header = new Parameters();

            header.Add("Origin", "https://passport.bilibili.com");
            header.Add("Referer", "https://passport.bilibili.com/login");
            req.HttpGet(url, header);

            var stream     = req.Stream;
            var out_stream = new MemoryStream();
            int read       = 0;
            var buffer     = new byte[16384];

            do
            {
                read = stream.Read(buffer, 0, 16384);
                out_stream.Write(buffer, 0, read);
            } while (read > 0);

            out_stream.Seek(0, SeekOrigin.Begin);
            req.Close();
            return(Image.FromStream(out_stream));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Разорвать соединение
        /// </summary>
        public void Disconnect()
        {
            try { NetStream.Close(); }
            catch { }

            try { TcpClient.Close(); }
            catch { }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Закрыть соединение
        /// </summary>
        protected void InternalClose()
        {
            try { NetStream.Close(); }
            catch { }

            try { TcpClient.Close(); }
            catch { }
        }
Ejemplo n.º 10
0
        private bool submit_course_data(string course_id)
        {
            var url = get_session_url() + "/xf_xsqxxxk.aspx?xh=" + username.Text + "&gnmkdm=N121103";

            debug_output("发送选课请求");
            string course_time = "", course_name = "";

            Invoke(new ThreadStart(delegate
            {
                course_time = courseTime.Text;
                course_name = courseName.Text;
            }));

            var post_param = new Parameters();

            post_param.Add("__EVENTTARGET", "");
            post_param.Add("__EVENTARGUMENT", "");
            post_param.Add("__VIEWSTATE", __VIEWSTATE);
            post_param.Add("ddl_kcxz", "");
            post_param.Add("ddl_ywyl", "");
            post_param.Add("ddl_kcgs", "");
            post_param.Add("ddl_xqbs", 2);
            post_param.Add("ddl_sksj", "");
            post_param.Add("TextBox1", "");
            post_param.Add("dpkcmcGrid:txtChoosePage", 1);
            post_param.Add("dpkcmcGrid:txtPageSize", 200);
            post_param.Add(course_id, "on");
            post_param.Add("Button1", "++提交++");

            var post_data = Encoding.UTF8.GetBytes(post_param.BuildQueryString());


            //response_sr.Close();
            var ns     = new NetStream();
            var header = new Parameters();

            header.Add("Origin", get_origin_url());
            header.Add("Referer", url);
            try
            {
                ns.HttpPost(url, post_data, NetStream.DEFAULT_CONTENT_TYPE_PARAM, header);
                if (ns.HTTP_Response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    debug_output("HTTP错误:服务器返回" + (int)ns.HTTP_Response.StatusCode + "(" + ns.HTTP_Response.StatusDescription + ")");
                    return(false); //status check
                }
                var response_str = ns.ReadResponseString(Encoding.Default);
                return(check_course_selected(response_str.Replace("\r", "").Replace("\n", "")));
            }
            catch (Exception)
            {
                return(false);
            }
            finally
            {
                ns.Close();
            }
        }
Ejemplo n.º 11
0
        internal void CloseSocket()
        {
            mClient.Socket.Shutdown(System.Net.Sockets.SocketShutdown.Send);//表示发送数据完全结束
            Task.Run(() =>
            {
                mClient.Socket.Receive(new byte[1], 1, System.Net.Sockets.SocketFlags.None);
            }).Wait(3000);

            mClient.Close();
            mClient = null;
        }
Ejemplo n.º 12
0
        public void Dispose()
        {
            if (SslStream != null)
            {
                SslStream.Dispose();
                SslStream.Close();
            }
            NetStream.Dispose();
            NetStream.Close();

            Socket.Dispose();
            Socket.Close();
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Disconnects the client.
 /// </summary>
 public void Disconnect()
 {
     try
     {
         NetStream?.Close();
         TcpClient?.Close();
     }
     finally
     {
         NetStream = null;
         TcpClient = null;
     }
 }
Ejemplo n.º 14
0
 public void ClearNetConnect()
 {
     if (_tcp_connect != null)
     {
         _tcp_connect.Close();
         _tcp_connect = null;
     }
     if (_net_stream != null)
     {
         _net_stream.Close();
         _net_stream = null;
     }
 }
Ejemplo n.º 15
0
 public WebSocketHandler(Net.Request request)
 {
     this.Request = request;
     RemotingContext.Current.Request = request;
     mClient          = request.mClient;
     mRemotingHandler = new ScriptRemoting.RemotingClientHandler((string data) =>
     {
         byte[] bs = new DataFrame(data).GetBytes();
         mClient.Write(bs);
     }, () =>
     {
         mClient.Close();
     }, request.RemoteEndPoint.ToString().Split(':')[0], null, null);
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Disconnects the client only.
 /// </summary>
 public void Disconnect()
 {
     try
     {
         NetStream?.Close();
         TcpClient?.Close();
     }
     catch (Exception ex)
     {
         Log.WriteException(ex, Locale.IsRussian ?
                            "Ошибка при отключении" :
                            "Error disconnecting");
     }
 }
Ejemplo n.º 17
0
        //初始化token并返回token
        private string _get_token()
        {
            var ns = new NetStream();

            ns.CookieKey = _cookie_identifier;
            try
            {
                if (_token == null)
                {
                    Tracer.GlobalTracer.TraceInfo("Fetching netdisk main page");

                    ns.HttpGet("https://pan.baidu.com/");
                    ns.Close();

                    _token = _v2_api__getapi(_get_guid());
                }
            }
            finally
            {
                ns.Close();
            }
            return(_token);
        }
Ejemplo n.º 18
0
        // method implementation of GET /v2/api/?getapi
        private string _v2_api__getapi(string gid)
        {
            var ns = new NetStream();

            ns.CookieKey = _cookie_identifier;

            try
            {
                Tracer.GlobalTracer.TraceInfo("Fetching: getapi");

                var query_param = new Parameters();
                query_param.Add("tpl", "netdisk");
                query_param.Add("subpro", "netdisk_web");
                query_param.Add("apiver", "v3");
                query_param.Add("tt", (long)(util.ToUnixTimestamp(DateTime.Now) * 1000));
                query_param.Add("class", "login");
                query_param.Add("gid", gid);
                query_param.Add("loginversion", "v4");
                query_param.Add("logintype", "basicLogin");
                query_param.Add("traceid", "");
                query_param.Add("callback", "bd__cbs__abcdef");

                var referer = new Parameters();
                referer.Add("Referer", "https://pan.baidu.com/");

                ns.HttpGet("https://passport.baidu.com/v2/api/?getapi&" + query_param.BuildQueryString(), headerParam: referer);
                var api_result = ns.ReadResponseString();
                api_result = _escape_callback_function(api_result);
                var json_api_result = JsonConvert.DeserializeObject(api_result) as JObject;
                var errno           = json_api_result["errInfo"].Value <string>("no");
                if (errno != "0")
                {
                    throw new LoginFailedException("failed to get token: " + json_api_result.ToString());
                }

                return(json_api_result["data"].Value <string>("token"));
            }
            catch (LoginFailedException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {
                throw new LoginFailedException("getapi failed", ex);
            }
            finally
            {
                ns.Close();
            }
        }
Ejemplo n.º 19
0
        private _regetcodestr_result _v2__reggetcodestr(string token, string vcodetype)
        {
            var ns = new NetStream();

            ns.CookieKey = _cookie_identifier;

            try
            {
                Tracer.GlobalTracer.TraceInfo("Fetching: reggetcodestr");

                var param = new Parameters();
                param.Add("token", token);
                param.Add("tpl", "netdisk");
                param.Add("subpro", "netdisk_web");
                param.Add("apiver", "v3");
                param.Add("tt", (long)(util.ToUnixTimestamp(DateTime.Now) * 1000));
                param.Add("fr", "login");
                param.Add("loginversion", "v4");
                param.Add("vcodetype", vcodetype);
                param.Add("traceid", "");
                param.Add("callback", "bd__cbs__nyanya");

                var referer = new Parameters();
                referer.Add("Referer", "https://pan.baidu.com/");

                ns.HttpGet("https://passport.baidu.com/v2/?reggetcodestr&" + param.BuildQueryString(), headerParam: referer);

                var api_result = ns.ReadResponseString();
                api_result = _escape_callback_function(api_result);

                var json_api_result = JsonConvert.DeserializeObject(api_result) as JObject;

                var errno = json_api_result["errInfo"].Value <string>("no");
                if (errno != "0")
                {
                    throw new Exception("get captcha failed");
                }

                return(new _regetcodestr_result()
                {
                    verifysign = json_api_result["data"].Value <string>("verifySign"),
                    verifystr = json_api_result["data"].Value <string>("verifyStr")
                });
            }
            finally
            {
                ns.Close();
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Закрыть соединение, обнулить ссылки на соединение для КП
        /// </summary>
        public void Close()
        {
            if (relatedKPList != null)
            {
                lock (relatedKPList)
                    foreach (KPLogic kpLogic in relatedKPList)
                    {
                        kpLogic.Connection = null;
                    }
            }

            try { NetStream.Close(); }
            catch { }

            try { TcpClient.Close(); }
            catch { }
        }
Ejemplo n.º 21
0
        //获取rsa的加密密钥
        private static void _fetch_encrypt_key(out string hash, out string public_key)
        {
            var ns    = new NetStream();
            var param = new Parameters();

            param.Add("appkey", APPKEY);
            param.Add("build", "513000");
            param.Add("mobi_app", "android");
            param.Add("platform", "android");
            param.Add("ts", (long)util.ToUnixTimestamp(DateTime.Now));
            param.Add("sign", CalculateSign(param));

            ns.UserAgent = ANDROID_USER_AGENT;
            try
            {
                ns.HttpPost(_URL_AUTH_GET_KEY, param);
                ns.HttpPostClose();

                var response = ns.ReadResponseString();
                var json     = JsonConvert.DeserializeObject(response) as JObject;

                int code = json.Value <int>("code");
                if (code != 0)
                {
                    hash                = null;
                    public_key          = null;
                    _last_error_code    = code;
                    _last_error_message = json.Value <string>("message");
                }
                else
                {
                    hash       = json["data"].Value <string>("hash");
                    public_key = json["data"].Value <string>("key");
                }
            }
            catch (Exception ex)
            {
                Tracer.GlobalTracer.TraceError(ex.ToString());
                throw ex;
            }
            finally
            {
                ns.Close();
            }
        }
Ejemplo n.º 22
0
        private static NewClientCredentials ConfigAuth(NetStream stream)
        {
            var ncc = new NewClientCredentials {
                Successful = false, SecurityLevel = -1, Username = null
            };
            var userpass = stream.Read();
            var ups      = userpass.Split(new[] { ':' }, 2);

            if (ups.Length < 2)
            {
                stream.Write("ERR_AUTH_INVALID_USER_FORMAT");
                stream.Close();
                return(ncc);
            }
            if (Userconf["user." + ups[0] + ".enabled"] != "true")
            {
                stream.Write("ERR_AUTH_INVALID_CREDENTIALS");
                return(ncc);
            }
            var validhash = Userconf["user." + ups[0] + ".hash"];
            var thishash  = Hash(ups[1]);

            if (validhash != thishash)
            {
                stream.Write("ERR_AUTH_INVALID_CREDENTIALS");
                return(ncc);
            }
            var seclvlstr = Userconf["user." + ups[0] + ".sec"];
            int sec;

            if (!int.TryParse(seclvlstr, out sec))
            {
                stream.Write("ERR_ACCOUNT_NOT_AUTHORIZED");
                return(ncc);
            }

            ncc.Username      = ups[0];
            ncc.SecurityLevel = sec;
            ncc.Successful    = true;

            Thread.CurrentThread.Name = ncc.Username;

            return(ncc);
        }
Ejemplo n.º 23
0
        public void Disconnected()
        {
            try
            {
                TcpClient.Shutdown(SocketShutdown.Both);
                if (OnDisconnected != null)
                {
                    OnDisconnected.Invoke(this);
                }
            }
            catch { }

            try
            {
                NetStream.Close();
                TcpClient.Close();
                NetStream.Dispose();
                TcpClient.Dispose();
                ClientMS.Dispose();
            }
            catch { }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 关闭TCP连接
        /// </summary>
        /// <returns>假如关闭成功,返回1,否则返回0</returns>
        public int Close()
        {
            LastErrorMessage = string.Empty;
            int result = 1;

            try
            {
                if (BaseClient != null && BaseClient.Connected)
                {
                    ThreadAbort(); //终止重连线程

                    //关闭流并释放资源
                    NetStream.Close();
                    NetStream.Dispose();
                    BaseClient.Close();
                    ServerIp           = null;
                    ServerPort         = 0;
                    IsConnected        = false;
                    IsConnected_Socket = false;
                    //调用连接断开事件委托
                    if (Disconnected != null)
                    {
                        Disconnected.BeginInvoke(Name, new EventArgs(), null, null);
                    }

                    BaseClient = null;
                    raiser.Stop();
                }
            }
            catch (Exception e)
            {
                LastErrorMessage = string.Format("关闭TCP连接{0}失败:{1}", Name, e.Message);
                FileClient.WriteExceptionInfo(e, LastErrorMessage, false);
                result = 0;
                throw; //假如不需要抛出异常,注释此行
            }

            return(result);
        }
Ejemplo n.º 25
0
 /// <summary>
 /// 获取当前用户的名称
 /// </summary>
 /// <returns></returns>
 private void _init_user_nickname()
 {
     try
     {
         var ns = new NetStream();
         ns.CookieKey  = _cookie_identifier;
         ns.RetryDelay = 1000;
         ns.RetryTimes = 3;
         ns.HttpGet(_BAIDU_ROOT_URL);
         var response_data = ns.ReadResponseString().Replace("\r", "").Replace("\n", "");
         var reg           = Regex.Match(response_data, "bds\\.comm\\.user\\s*=\\s*\"(?<user>[^\"]*)\";");
         if (reg.Success)
         {
             _nickname = reg.Result("${user}");
         }
         ns.Close();
     }
     catch (Exception ex)
     {
         Tracer.GlobalTracer.TraceError(ex);
     }
 }
Ejemplo n.º 26
0
        // method implementation of /cgi-bin/genimage
        private Image _cgi_bin_genimage(string codestring)
        {
            var ns = new NetStream();

            ns.CookieKey = _cookie_identifier;
            try
            {
                Tracer.GlobalTracer.TraceInfo("Fetching: genimage");

                ns.HttpGet("https://passport.baidu.com/cgi-bin/genimage?" + codestring);
                var binary_data = ns.ReadResponseBinary();
                var ms          = new MemoryStream(binary_data);
                return(Image.FromStream(ms));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ns.Close();
            }
        }
Ejemplo n.º 27
0
        //刷新验证码
        private void refresh_captcha()
        {
            debug_output("获取验证码图片");
            var url = get_session_url() + "/CheckCode.aspx";

            var ns           = new NetStream();
            var header_param = new Parameters();

            header_param.Add("Origin", main_page_url);
            ns.HttpGetAsync(url, (_sender, _e) =>
            {
                var memstream    = new MemoryStream();
                int readed_bytes = 0;
                //从网络数据流转移到内存数据流中
                const int buffer_size = 4096;
                var buffer            = new byte[buffer_size];
                do
                {
                    readed_bytes = _sender.ResponseStream.Read(buffer, 0, buffer_size);
                    memstream.Write(buffer, 0, readed_bytes);
                } while (readed_bytes > 0);
                ns.Close();
                memstream.Seek(0, SeekOrigin.Begin);

                var img = Image.FromStream(memstream); //从内存流中创建图像
                //主线程委托
                Invoke(new ThreadStart(delegate
                {
                    captchaImg.Image = img;
                    if (ocr_wrapper != null)
                    {
                        capcha.Text = ocr_wrapper.OCR_Image(img);
                    }
                }));
            }, headerParam: header_param);
        }
Ejemplo n.º 28
0
        //获取选课课表回调
        private void get_public_course_callback(NetStream sender, object e)
        {
            var response_str = sender.ReadResponseString(Encoding.Default);

            sender.Close();


            //replacing crlf
            response_str = response_str.Replace("\r", "").Replace("\n", "");

            //解析上课时间
            var time_ptr        = "<select\\sname=\"ddl_sksj\"\\sonchange=\"__doPostBack\\('ddl_sksj',''\\)\"\\slanguage=\"javascript\"\\sid=\"ddl_sksj\">(?<data>.*?)</select>";
            var time_ptr2       = "<option\\svalue=\"(?<value>[^\"]+)\">.*?</option>";
            var time_spec_total = Regex.Match(response_str, time_ptr);
            var time_list       = new List <string>();

            if (time_spec_total.Success)
            {
                Invoke(new ThreadStart(delegate
                {
                    var match_string = time_spec_total.Result("${data}");
                    var time         = Regex.Match(match_string, time_ptr2);
                    while (time.Success)
                    {
                        time_list.Add(time.Result("${value}"));
                        time = time.NextMatch();
                    }
                }));
            }
            else
            {
                debug_output("获取选课失败,若重复出现,可重新启动程序重试");
                debug_output("返回内容:" + response_str);
                Thread.Sleep(3000);
                get_public_course((bool)e);
            }

            //parsing __VIEWSTATE
            var match = Regex.Match(response_str, "<input\\stype=\"hidden\"\\sname=\"__VIEWSTATE\"\\svalue=\"(?<value>[^\"]*?)\"\\s*/>");

            if (match.Success)
            {
                __VIEWSTATE = match.Result("${value}");
            }

            //总课程数
            match = Regex.Match(response_str, "<span\\sid=\"dpkcmcGrid_lblTotalRecords\">(?<record>\\d+)</span>");
            if (match.Success)
            {
                total_records = int.Parse(match.Result("${record}"));
            }

            //解析选课的各个字段
            course_list = new List <courses>();
            var ptn_course_table = "<fieldset><legend>可选课程</legend>(?<data>.*?)</fieldset>";
            var course_table_str = Regex.Match(response_str, ptn_course_table).Result("${data}");

            match = Regex.Match(course_table_str, "<tr(\\sclass=\"alt\")?>(?<data>.*?)</tr>");
            while (match.Success)
            {
                var crs      = new courses();
                var sub_info = Regex.Match(match.Result("${data}"), "<td.*?>(?<data>.*?)</td>");
                //sect 0 <input id="kcmcGrid__ctl2_xk" type="checkbox" name="kcmcGrid:_ctl2:xk" />
                var sub_info2 = Regex.Match(sub_info.Result("${data}"), "<input.*?name=\"(?<checkBox>.*?)\"\\s*/>");
                crs.CheckBoxStr = sub_info2.Result("${checkBox}");
                sub_info        = sub_info.NextMatch();
                //sect 1 course name
                sub_info2 = Regex.Match(sub_info.Result("${data}"), "<a.*?>(?<name>.+?)</a>");
                crs.Name  = sub_info2.Result("${name}");
                sub_info  = sub_info.NextMatch();
                //sect 2 code
                crs.Code = sub_info.Result("${data}");
                sub_info = sub_info.NextMatch();
                //sect 3 teacher
                sub_info2   = Regex.Match(sub_info.Result("${data}"), "<a.*?>(?<name>.+?)</a>");
                crs.Teacher = sub_info2.Result("${name}");
                sub_info    = sub_info.NextMatch();
                //sect 4 time
                var sub_info3 = Regex.Match(sub_info.Value, "<td\\stitle=\"(?<time>.*?)\">.*?</td>");
                crs.Time = sub_info3.Result("${time}");
                match    = match.NextMatch();
                //todo: add more column

                course_list.Add(crs);
            }

            if ((bool)e)
            {
                //获取完整的课表
                get_public_course(false);
            }
            else
            {
                //更新UI
                Invoke(new ThreadStart(delegate
                {
                    courseName.Items.Clear();
                    foreach (var item in course_list)
                    {
                        courseName.Items.Add(item.Name);
                    }
                    goFuck.Enabled = true;
                }));
                debug_output("获取完成");
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 将网盘的文件异步转换成秒传数据文件(将产生一个原文件名.symbollink的文件)
        /// </summary>
        /// <param name="path">原文件路径</param>
        /// <param name="callback">回调函数</param>
        /// <param name="dst_path">保存的文件名</param>
        /// <param name="state">附加参数</param>
        public void ConvertToSymbolLinkAsync(string path, ObjectMetaCallback callback = null, string dst_path = null, object state = null)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path");
            }
            ThreadPool.QueueUserWorkItem(delegate
            {
                if (_enable_function_trace)
                {
                    _trace.TraceInfo("BaiduPCS.ConvertToSymbolLinkAsync called: string path=" + path + "ObjectMetaCallback callback=" + callback?.ToString() + ", string dst_path=" + dst_path);
                }
                var url = GetLocateDownloadLink(path);
                if (url.Length == 0)
                {
                    _trace.TraceWarning("Locate url length is zero");
                    callback?.Invoke(false, new ObjectMetadata(), state);
                    return;
                }
                var ns        = new NetStream();
                ns.RetryTimes = 3;
                ns.CookieKey  = _auth.CookieIdentifier;
                try
                {
                    var buffer        = new byte[BUFFER_SIZE];
                    var md5           = new System.Security.Cryptography.MD5CryptoServiceProvider();
                    int rbytes, total = 0;
                    ns.HttpGet(url[0]);
                    var content_length = ns.HTTP_Response.ContentLength;
                    if (content_length < VALIDATE_SIZE)
                    {
                        _trace.TraceWarning("Content_length is too small, exited");
                        callback?.Invoke(false, new ObjectMetadata(), state);
                        return;
                    }

                    var stream = ns.ResponseStream;
                    do
                    {
                        rbytes = stream.Read(buffer, 0, BUFFER_SIZE);
                        rbytes = (int)Math.Min(VALIDATE_SIZE - total, rbytes);
                        md5.TransformBlock(buffer, 0, rbytes, buffer, 0);
                        total += rbytes;
                    } while (rbytes > 0 && total < VALIDATE_SIZE);
                    md5.TransformFinalBlock(buffer, 0, 0);

                    var slice_md5 = util.Hex(md5.Hash);

                    //从response处获取其他参数
                    var content_md5   = ns.HTTP_Response.Headers["Content-MD5"];
                    var content_crc32 = ns.HTTP_Response.Headers["x-bs-meta-crc32"];
                    uint int_crc32    = uint.Parse(content_crc32);
                    content_crc32     = int_crc32.ToString("X2").ToLower();

                    if (string.IsNullOrEmpty(content_crc32) || string.IsNullOrEmpty(content_md5))
                    {
                        _trace.TraceWarning("Empty content_crc32 or content_md5 detected, pls report this status to developer by opening new issue");
                        callback?.Invoke(false, new ObjectMetadata(), state);
                    }

                    //尝试发送rapid upload请求
                    var temp_path = "/BaiduCloudSyncCache/temp-rapid-upload-request-" + Guid.NewGuid().ToString();

                    var rapid_upload_info = RapidUploadRaw(temp_path, (ulong)content_length, content_md5, content_crc32, slice_md5);
                    DeletePath("/BaiduCloudSyncCache");

                    if (string.IsNullOrEmpty(rapid_upload_info.MD5) || rapid_upload_info.FS_ID == 0)
                    {
                        _trace.TraceWarning("Validate check: post rapid upload failed, operation aborted");
                        callback?.Invoke(false, new ObjectMetadata(), state);
                        return;
                    }

                    //rapid upload通过,整合成json格式的文件上传到服务器
                    var json = new JObject();
                    json.Add("content_length", content_length);
                    json.Add("content_md5", content_md5);
                    json.Add("content_crc32", content_crc32);
                    json.Add("slice_md5", slice_md5);
                    var str_json        = JsonConvert.SerializeObject(json);
                    var bytes_json      = Encoding.UTF8.GetBytes(str_json);
                    var stream_to_write = new MemoryStream();
                    stream_to_write.Write(bytes_json, 0, bytes_json.Length);
                    stream_to_write.Seek(0, SeekOrigin.Begin);

                    if (dst_path == null)
                    {
                        dst_path = path + ".symbollink";
                    }
                    var file_meta = UploadRaw(stream_to_write, (ulong)bytes_json.Length, dst_path);
                    stream_to_write.Close();
                    callback?.Invoke(true, file_meta, state);
                }
                catch (Exception ex)
                {
                    _trace.TraceError(ex);
                }
                finally
                {
                    ns.Close();
                }
            });
        }
Ejemplo n.º 30
0
        public static string DoChallenge()
        {
            _challenge = string.Empty;
            _validate  = string.Empty;
            try
            {
                //前戏: 获取有关geetest的参数

                //string gt & string challenge
                var challenge_url = string.Format(_challenge_url, Convert.ToInt64(util.ToUnixTimestamp(DateTime.Now) * 1000));
                var req           = new NetStream();
                var xhr_param     = new Parameters();
                xhr_param.Add("X-Requested-With", "XMLHttpRequest");
                xhr_param.Add("Referer", "https://passport.bilibili.com/login");
                req.HttpGet(challenge_url, xhr_param);
                var rep       = req.ReadResponseString();
                var json_rep  = JsonConvert.DeserializeObject(rep) as JObject;
                var challenge = json_rep["data"].Value <string>("challenge");
                var gt        = json_rep["data"].Value <string>("gt");
                req.Close();

                //string path & string static_server
                var ref_param = new Parameters();
                ref_param.Add("Referer", "https://passport.bilibili.com/login");
                var gettype_url = string.Format(_gettype_url, gt);
                req.HttpGet(gettype_url, ref_param);
                rep      = req.ReadResponseString();
                json_rep = JsonConvert.DeserializeObject(rep.Substring(3, rep.Length - 4)) as JObject;
                var path          = json_rep["data"].Value <string>("path");
                var static_server = json_rep["data"]["static_servers"].Value <string>(0);
                req.Close();

                //Image fullbg & Image slice & Image bg
                var get_url = string.Format(_get_url, gt, challenge, path);
                req.HttpGet(get_url, ref_param);
                rep      = req.ReadResponseString();
                json_rep = JsonConvert.DeserializeObject(rep.Substring(3, rep.Length - 4)) as JObject;
                var bg     = json_rep.Value <string>("bg"); //with source
                var fullbg = json_rep.Value <string>("fullbg");
                var slice  = json_rep.Value <string>("slice");
                challenge = json_rep.Value <string>("challenge");
                req.Close();

                //image downloading
                var fullbg_img = _load_image_from_url("https://" + static_server + "/" + fullbg);
                var bg_img     = _load_image_from_url("https://" + static_server + "/" + bg);
                var slice_img  = _load_image_from_url("https://" + static_server + "/" + slice);

                //sorting the images
                fullbg_img = _sort_image(fullbg_img);
                bg_img     = _sort_image(bg_img);

                //find difference
                var target_pos = _difference(fullbg_img, bg_img);

                //simulating mouse track
                var target_x     = target_pos.Left - 6;
                var sim_path     = _load_random_path(target_x);
                var sim_path_enc = _encrypt(sim_path);

                //building request data
                var passtime = 0;
                foreach (var item in sim_path)
                {
                    passtime += item[2];
                }
                var dst_target_x = -sim_path[0][0];
                foreach (var item in sim_path)
                {
                    dst_target_x += item[0];
                }
                var validate_param = new Parameters();
                validate_param.Add("gt", gt);
                validate_param.Add("challenge", challenge);
                validate_param.Add("userresponse", _get_user_response(dst_target_x, challenge));
                validate_param.Add("passtime", passtime);
                var imgload = _rnd.Next(0, 200) + 50;
                Thread.Sleep(passtime);
                validate_param.Add("imgload", imgload);
                validate_param.Add("a", sim_path_enc);
                validate_param.Add("callback", "cb");
                var ajax_url = _ajax_url;
                req.HttpGet(ajax_url, urlParam: validate_param, headerParam: ref_param);
                rep      = req.ReadResponseString();
                json_rep = JsonConvert.DeserializeObject(rep.Substring(3, rep.Length - 4)) as JObject;

                Debug.Print(json_rep.Value <string>("message"));
                int success = json_rep.Value <int>("success");
                if (success == 1)
                {
                    _validate  = json_rep.Value <string>("validate");
                    _challenge = challenge;
                    //writing data
                    //var str_json = JsonConvert.SerializeObject(sim_path);
                    //var json = new JObject();
                    //json.Add("length", target_x);
                    //json.Add("data", str_json);
                    //var fs = new StreamWriter("apis/traineddata.txt", true);
                    //fs.WriteLine(JsonConvert.SerializeObject(json));
                    //fs.Close();
                }
                req.Close();
            }
            catch (Exception)
            {
            }
            return(_validate);
        }