Beispiel #1
0
        /// <summary>
        /// 获取空间文件信息
        /// </summary>
        /// <param name="bucket">空间名称</param>
        /// <param name="key">文件key</param>
        /// <returns>文件信息获取结果</returns>
        public StatResult Stat(string bucket, string key)
        {
            StatResult result = new StatResult();

            try
            {
                string statUrl = string.Format("{0}{1}", this.config.RsHost(this.mac.AccessKey, bucket),
                                               StatOp(bucket, key));
                string token = auth.CreateManageToken(statUrl);

                HttpResult hr = httpManager.Get(statUrl, token);
                result.Shadow(hr);
            }
            catch (QiniuException ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("[{0}] [stat] Error:  ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"));
                Exception e = ex;
                while (e != null)
                {
                    sb.Append(e.Message + " ");
                    e = e.InnerException;
                }
                sb.AppendLine();

                result.Code     = ex.HttpResult.Code;
                result.RefCode  = ex.HttpResult.Code;
                result.Text     = ex.HttpResult.Text;
                result.RefText += sb.ToString();
            }

            return(result);
        }
Beispiel #2
0
        /// <summary>
        /// 查询pfop操作处理结果(或状态)
        /// </summary>
        /// <param name="persistentId">持久化ID</param>
        /// <returns>操作结果</returns>
        public static HttpResult Prefop(string persistentId)
        {
            HttpResult result = new HttpResult();

            try
            {
                string prefopUrl = string.Format("{0}/status/get/prefop?id={1}", Config.ZONE.ApiHost, persistentId);

                HttpManager httpMgr = new HttpManager();
                result = httpMgr.Get(prefopUrl, null);
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("[{0}] [prefop] Error:  ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"));
                Exception e = ex;
                while (e != null)
                {
                    sb.Append(e.Message + " ");
                    e = e.InnerException;
                }
                sb.AppendLine();

                result.RefCode  = (int)HttpCode.USER_EXCEPTION;
                result.RefText += sb.ToString();
            }

            return(result);
        }
Beispiel #3
0
        public void Login()
        {
            string homepageResponse = httpManager.Get("http://www.darkorbit.com/");
            Match  match            = Regex.Match(homepageResponse, "class=\"bgcdw_login_form\" action=\"(.*)\">");

            if (!match.Success)
            {
                LoginFailed?.Invoke(this, EventArgs.Empty);
                return;
            }

            string loginResponse = httpManager.Post(WebUtility.HtmlDecode(match.Groups[1].ToString()), $"username={Username}&password={Password}");

            match = Regex.Match(httpManager.lastURL, "https://(.*).darkorbit.bigpoint.com");

            if (!match.Success)
            {
                match = Regex.Match(httpManager.lastURL, "https://(.*).darkorbit.com");
            }
            if (!match.Success)
            {
                LoginFailed?.Invoke(this, EventArgs.Empty);
                return;
            }

            Server = match.Groups[1].ToString();

            string mapResponse = httpManager.Get($"{match.Value}/indexInternal.es?action=internalMapRevolution");

            match = Regex.Match(mapResponse, "{\"pid\":([0-9]+),\"uid\":([0-9]+)[\\w,\":]+sid\":\"([0-9a-z]+)\"");

            Match pid = Regex.Match(mapResponse, "basePath\": \"spacemap\",\"pid\": \"([0-9]+)");

            if (!match.Success || !pid.Success)
            {
                LoginFailed?.Invoke(this, EventArgs.Empty);
                return;
            }

            InstanceID = int.Parse(pid.Groups[1].ToString());
            UserID     = int.Parse(match.Groups[2].ToString());
            SID        = match.Groups[3].ToString();
            match      = Regex.Match(mapResponse, "mapID\": \"([0-9]*)\"");
            Map        = int.Parse(match.Groups[1].ToString());

            LoginSucceed?.Invoke(this, EventArgs.Empty);
        }
Beispiel #4
0
        public void GetTest()
        {
            HttpManager target = new HttpManager();
            HttpResult  result = target.Get(TestURL1, null);

            //Assert.AreEqual((int)HttpCode.OK, result.Code);
            Assert.AreNotEqual((int)HttpCode.USER_EXCEPTION, result.Code);
        }
Beispiel #5
0
        public OperationResult <string> Authorization()
        {
            var url = StringManager.BuildString(new List <string> {
                Oauth, @"authorize?client_id=", _appId, "&scope=PERMISSIONS&redirect_uri=", _redirectUri, "&response_type=code"
            });

            return(_httpManager.Get(url));
        }
        /// <summary>
        /// 查询pfop操作处理结果(或状态)
        /// </summary>
        /// <param name="persistentId">持久化ID</param>
        /// <returns>操作结果</returns>
        public PrefopResult Prefop(string persistentId)
        {
            PrefopResult result = new PrefopResult();

            string scheme    = this.config.UseHttps ? "https://" : "http://";
            string prefopUrl = string.Format("{0}{1}/status/get/prefop?id={2}", scheme, Config.DefaultApiHost, persistentId);

            HttpManager httpMgr    = new HttpManager();
            HttpResult  httpResult = httpMgr.Get(prefopUrl, null);

            result.Shadow(httpResult);

            return(result);
        }
Beispiel #7
0
        private static global::System.Collections.Generic.List <T> PerformQuery <T>(string query)
        {
            Log.ForContext <SoqlApi>().Debug("SOQL Query {query}", query);

            HttpManager httpManager = new HttpManager();
            var         json        = httpManager.Get($"query/?q={query}");

            RecordReadList <T> returnData = JsonConvert.DeserializeObject <RecordReadList <T> >(json,
                                                                                                new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            });

            return(returnData.records);
        }
Beispiel #8
0
 public OperationResult <bool> SendSms(string from, string to, string sms)
 {
     try {
         var data   = "version=http&login="******"&password="******"&key=" + _apiKey + "&command=send&from=" + from + "&to=38" + to + "&message=" + sms;
         var result = _httpManager.Get(SmsUrn + "?" + data);
         if (result.IsSuccess && result.Data.Contains("id:"))
         {
             return(new OperationResult <bool>(true));
         }
         return(new OperationResult <bool>(new Exception("SMS sending error")));
     }
     catch (Exception ex) {
         return(new OperationResult <bool>(ex));
     }
 }
Beispiel #9
0
        public Task <bool> BucketExistsAsync(string bucketName)
        {
            string     bucketsUrl = QiniuApi.GetBaseApi(_config.Zone.RsHost, Options) + "/bucket/" + bucketName;
            string     token      = _auth.CreateManageToken(bucketsUrl);
            HttpResult hr         = _http.Get(bucketsUrl, token);

            if (hr.Code == (int)HttpCode.OK && !string.IsNullOrEmpty(hr.Text))
            {
                return(Task.FromResult(true));
            }
            else if (hr.Code == 612)
            {
                return(Task.FromResult(false));
            }
            else
            {
                if (!string.IsNullOrEmpty(hr.Text))
                {
                    QiniuError error = JsonUtil.DeserializeObject <QiniuError>(hr.Text);
                    throw new Exception($"Get bucket exist status failed, error code: {hr.Code}, error msg: {error.error}");
                }
                throw new Exception($"Get bucket exist status failed, error code: {hr.Code}, text: {hr.Text}");
            }
        }
        public async Task WhenHttpManagerIsExecuted_ManagerReturnsCorrectCompetitionDto()
        {
            var url               = "https://validurl.com";
            var competition       = CompetitionSource.competitions().Where(x => x.code == "CL").FirstOrDefault();
            var httpClientMock    = IHttpClientFactoryFake.Get(competition);
            var configurationMock = IConfigurationFake.Get();

            var httpManagerMock   = new HttpManager(configurationMock, httpClientMock);
            var competitionResult = await httpManagerMock.Get <CompetitionDto>(url);

            Assert.IsType <CompetitionDto>(competitionResult);
            Assert.NotNull(competitionResult);
            Assert.Equal("CL", competitionResult.code);
            Assert.Equal("Champions League", competitionResult.name);
            Assert.NotNull(competitionResult.area);
            Assert.Equal("Europe", competitionResult.area.name);
        }
Beispiel #11
0
        /// <summary>
        /// 从uc.qbox.me查询得到回复后,解析出upHost,然后根据upHost确定Zone
        /// </summary>
        /// <param name="accessKey">AccessKek</param>
        /// <param name="bucket">空间名称</param>
        public static ZoneID QueryZone(string accessKey, string bucket)
        {
            ZoneID zoneId = ZoneID.Invalid;

            try
            {
                // HTTP/GET https://uc.qbox.me/v1/query?ak=(AK)&bucket=(Bucket)
                string queryUrl = string.Format("https://uc.qbox.me/v1/query?ak={0}&bucket={1}", accessKey, bucket);

                HttpManager httpManager = new HttpManager();
                var         hr          = httpManager.Get(queryUrl, null);
                if (hr.Code == (int)HttpCode.OK)
                {
                    ZoneInfo zInfo = null;
                    if (JsonHelper.Deserialize(hr.Text, out zInfo))
                    {
                        string upHost = zInfo.HTTP.UP[0];
                        zoneId = ZONE_DICT[upHost];
                    }
                    else
                    {
                        throw new Exception("JSON Deserialize failed: " + hr.Text);
                    }
                }
                else
                {
                    throw new Exception("code: " + hr.Code + ", text: " + hr.Text + ", ref-text:" + hr.RefText);
                }
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("[{0}] QueryZone Error:  ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"));
                Exception e = ex;
                while (e != null)
                {
                    sb.Append(e.Message + " ");
                    e = e.InnerException;
                }
                sb.AppendLine();

                throw new Exception(sb.ToString());
            }

            return(zoneId);
        }
        public async Task WhenHttpManagerIsExecuted_ManagerReturnsCorrectTeamCompetitionDto()
        {
            var url               = "https://validurl.com";
            var teamCompetition   = TeamCompetitionSource.teamCompetitions().Where(x => x.competition.code == "CL").ToList();
            var httpClientMock    = IHttpClientFactoryFake.Get(teamCompetition);
            var configurationMock = IConfigurationFake.Get();

            var httpManagerMock   = new HttpManager(configurationMock, httpClientMock);
            var competitionResult = await httpManagerMock.Get <List <TeamCompetitionDto> >(url);

            Assert.IsType <List <TeamCompetitionDto> >(competitionResult);
            Assert.Equal(12, CompetitionSource.competitions().Count());
            var expectedCompetition = CompetitionSource.competitions().Where(x => x.code == "CL").FirstOrDefault();

            foreach (var item in competitionResult)
            {
                Assert.Equal(expectedCompetition.code, item.competition.code);
            }
        }
Beispiel #13
0
        /// <summary>
        /// 下载文件到本地
        /// </summary>
        /// <param name="url">(可访问的或者已授权的)链接</param>
        /// <param name="saveasFile">(另存为)本地文件名</param>
        /// <returns>下载资源的结果</returns>
        public static HttpResult Download(string url, string saveasFile)
        {
            HttpResult result = new HttpResult();

            try
            {
                HttpManager httpManager = new HttpManager();

                result = httpManager.Get(url, null, true);
                if (result.Code == (int)HttpCode.OK)
                {
                    using (FileStream fs = File.Create(saveasFile, result.Data.Length))
                    {
                        fs.Write(result.Data, 0, result.Data.Length);
                        fs.Flush();
                    }
                    result.RefText += string.Format("[{0}] [Download] Success: (Remote file) ==> \"{1}\"\n",
                                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), saveasFile);
                }
                else
                {
                    result.RefText += string.Format("[{0}] [Download] Error: code = {1}\n",
                                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), result.Code);
                }
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("[{0}] [Download] Error:  ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"));
                Exception e = ex;
                while (e != null)
                {
                    sb.Append(e.Message + " ");
                    e = e.InnerException;
                }
                sb.AppendLine();

                result.RefCode  = (int)HttpCode.USER_UNDEF;
                result.RefText += sb.ToString();
            }

            return(result);
        }
Beispiel #14
0
        /// <summary>
        /// 下载文件到本地
        /// </summary>
        /// <param name="url">(可访问的或者已授权的)链接</param>
        /// <param name="downloadProgress">下载</param>
        /// <returns>下载资源的结果</returns>
        public static HttpResult Download(string url, IProgress <double> downloadProgress = null)
        {
            HttpResult result = new HttpResult();

            try
            {
                HttpManager httpManager = new HttpManager();
                result = httpManager.Get(url, null, true, downloadProgress);
                if (result.Code == (int)HttpCode.OK)
                {
                    result.RefText += string.Format("[{0}] [Download] Success: (Remote file) ==> \"{1}\"\n",
                                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), url);
                }
                else
                {
                    result.RefText += string.Format("[{0}] [Download] Error: code = {1}\n",
                                                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"), result.Code);
                }
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("[{0}] [Download] Error:  ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"));
                Exception e = ex;
                while (e != null)
                {
                    sb.Append(e.Message + " ");
                    e = e.InnerException;
                }
                sb.AppendLine();

                result.RefCode  = (int)HttpCode.USER_UNDEF;
                result.RefText += sb.ToString();
            }

            return(result);
        }
Beispiel #15
0
        /// <summary>
        /// 从uc.qbox.me查询得到回复后,解析出upHost,然后根据upHost确定Zone
        /// </summary>
        /// <param name="accessKey">AccessKek</param>
        /// <param name="bucket">空间名称</param>
        public static Zone QueryZone(string accessKey, string bucket)
        {
            Zone zone = null;

            string cacheKey = string.Format("{0}:{1}", accessKey, bucket);

            //check from cache
            lock (rwLock)
            {
                if (zoneCache.ContainsKey(cacheKey))
                {
                    zone = zoneCache[cacheKey];
                }
            }

            if (zone != null)
            {
                return(zone);
            }

            //query from uc api
            HttpResult hr = null;

            try
            {
                string      queryUrl    = string.Format("https://uc.qbox.me/v2/query?ak={0}&bucket={1}", accessKey, bucket);
                HttpManager httpManager = new HttpManager();
                hr = httpManager.Get(queryUrl, null);
                if (hr.Code == (int)HttpCode.OK)
                {
                    ZoneInfo zInfo = JsonConvert.DeserializeObject <ZoneInfo>(hr.Text);
                    if (zInfo != null)
                    {
                        zone            = new Zone();
                        zone.SrcUpHosts = zInfo.Up.Src.Main;
                        zone.CdnUpHosts = zInfo.Up.Acc.Main;
                        zone.IovipHost  = zInfo.Io.Src.Main[0];
                        if (zone.IovipHost.Contains("z1"))
                        {
                            zone.ApiHost = "api-z1.qiniu.com";
                            zone.RsHost  = "rs-z1.qiniu.com";
                            zone.RsfHost = "rsf-z1.qiniu.com";
                        }
                        else if (zone.IovipHost.Contains("z1"))
                        {
                            zone.ApiHost = "api-z2.qiniu.com";
                            zone.RsHost  = "rs-z2.qiniu.com";
                            zone.RsfHost = "rsf-z2.qiniu.com";
                        }
                        else if (zone.IovipHost.Contains("na0"))
                        {
                            zone.ApiHost = "api-na0.qiniu.com";
                            zone.RsHost  = "rs-na0.qiniu.com";
                            zone.RsfHost = "rsf-na0.qiniu.com";
                        }
                        else
                        {
                            zone.ApiHost = "api.qiniu.com";
                            zone.RsHost  = "rs.qiniu.com";
                            zone.RsfHost = "rsf.qiniu.com";
                        }

                        lock (rwLock)
                        {
                            zoneCache[cacheKey] = zone;
                        }
                    }
                    else
                    {
                        throw new Exception("JSON Deserialize failed: " + hr.Text);
                    }
                }
                else
                {
                    throw new Exception("code: " + hr.Code + ", text: " + hr.Text + ", ref-text:" + hr.RefText);
                }
            }
            catch (Exception ex)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendFormat("[{0}] QueryZone Error:  ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"));
                Exception e = ex;
                while (e != null)
                {
                    sb.Append(e.Message + " ");
                    e = e.InnerException;
                }
                sb.AppendLine();

                throw new QiniuException(hr, sb.ToString());
            }

            return(zone);
        }
Beispiel #16
0
        void DownloadPatch(Dictionary <string, Patch> .Enumerator enumerator, int i, int totalToDownload)
        {
            if (!enumerator.MoveNext())
            {
                //下载完毕,将新版本号写入patchIndex,并保存
                _patchIndexLocal.Version      = VersionCode;
                _patchIndexLocal.PatchVersion = _patchIndexNew.PatchVersion;
                _patchIndexLocal.WriteToFile();
                ResManager.Ins.ReadDownloadDir();
                if (Listener != null)
                {
                    Listener.OnPatchDownloadFinish();
                }
                CheckUpdate();                //补丁更新结束后再次检查更新
                return;
            }
            i++;
            var patchKV = enumerator.Current;
            var name    = patchKV.Key;
            var patch   = patchKV.Value;

            if (patch.NeedDelete)              //如果这个补丁是删除更新,则删除
            {
                FileInfo file = UResources.ReqFile(name);
                if (file != null)
                {
                    File.Delete(file.FullName);
                }
                if (Listener != null)
                {
                    Listener.OnPatchDownloadProgress(name, 1, i, totalToDownload);
                }
                _patchIndexLocal.UpdatePatch(name, patch);
                _patchIndexLocal.WriteToFile();
                DownloadPatch(enumerator, i, totalToDownload);
                return;
            }
            //下载更新
            string url = String.Format(_patchIndexNew.PatchBaseURL, name, patch.Version);

            HttpManager.Get(url, (error, www) => {
                if (!string.IsNullOrEmpty(error))
                {
                    UpdaterLog.LogError("下载补丁包出错" + name + "  " + www.error + "  url:" + www.url);
                    if (Listener != null)
                    {
                        Listener.OnPatchDownloadFail(error);
                    }
                    return;
                }
                string filePath = ResManager.FullDownloadDir + name;
                File.WriteAllBytes(filePath, www.bytes);
                //下载完一个文件后立刻写入PatchIndex,这样中途断开网络后重新下载可以不下载该文件
                _patchIndexLocal.UpdatePatch(name, patch);
                _patchIndexLocal.WriteToFile();
                DownloadPatch(enumerator, i, totalToDownload);
                return;
            }, progress => {
                if (Listener != null)
                {
                    Listener.OnPatchDownloadProgress(name, progress, i, totalToDownload);
                }
            });
        }