예제 #1
0
        public async Task <GitHubResponse <Authorization> > CreateAuthorizationTokenForAppAsync(AuthorizeParameters parameters, string username, string password, string twoFactorAuthorizationCode = null)
        {
            GitHubResponse <Authorization> response = new GitHubResponse <Authorization>();

            using (HttpClient client = CreateHttpClient())
            {
                // create a basic auth header.
                byte[] authroizationHeader = Encoding.ASCII.GetBytes($"{username}:{password}");
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authroizationHeader));

                if (!String.IsNullOrWhiteSpace(twoFactorAuthorizationCode))
                {
                    client.DefaultRequestHeaders.Add("X-GitHub-OTP", twoFactorAuthorizationCode);
                }

                string requestUri = $"https://api.github.com/authorizations/clients/{parameters.Client_Id}";
                // post content.
                HttpResponseMessage responseMessage = await client.PutAsJsonAsync(requestUri, new
                {
                    client_secret = parameters.Client_Secret,
                    scopes        = parameters.Scopes
                });

                if (responseMessage.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                {
                    response.Headers = new GitHubHeaders(responseMessage.Headers);
                    return(response);
                }

                responseMessage.EnsureSuccessStatusCode();
                response.Response = await responseMessage.Content.ReadAsAsync <Authorization>();

                return(response);
            }
        }
예제 #2
0
    private IEnumerator CheckVersion()
    {
        // /repos/{owner}/{repo}/releases
        var web = UnityWebRequest.Get("https://api.github.com/repos/GlowPuff/ImperialCommander/releases/latest");

        yield return(web.SendWebRequest());

        if (web.result == UnityWebRequest.Result.ConnectionError)
        {
            Debug.Log("network error");
            networkStatus = NetworkStatus.Error;
            busyIconTF.GetComponent <Image>().color = new Color(1, 0, 0);
            gitHubResponse = null;
        }
        else
        {
            //parse JSON response
            gitHubResponse = JsonConvert.DeserializeObject <GitHubResponse>(web.downloadHandler.text);

            if (gitHubResponse.tag_name == DataStore.appVersion)
            {
                networkStatus = NetworkStatus.UpToDate;
                busyIconTF.GetComponent <Image>().color = new Color(0, 1, 0);
            }
            else
            {
                networkStatus = NetworkStatus.WrongVersion;
                busyIconTF.GetComponent <Image>().color = new Color(1, 0.5586207f, 0);
            }
        }

        yield return(null);
    }
예제 #3
0
        private async Task <GitHubResponse <T> > QueryAsync <T>(string query)
        {
            GitHubResponse <T> result = new GitHubResponse <T>();

            using (HttpClient client = CreateHttpClient("2e895067dd3aa04fb26253852580a387b09b5404"))
            {
                StringBuilder stringBuilder = new StringBuilder();
                using (StringReader reader = new StringReader(query))
                {
                    while (reader.Peek() != -1)
                    {
                        string line = reader.ReadLine();
                        stringBuilder.Append(line.Trim());
                    }
                };

                query = stringBuilder.ToString();

                HttpResponseMessage response = await client.PostAsync(API_ENDPOINT, new StringContent(query));

                result.Headers = new Models.Headers.GitHubHeaders(response.Headers);
                var content = await response.Content.ReadAsStringAsync();

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    result.Response = await response.Content.ReadAsAsync <T>();
                }

                return(result);
            }
        }
        public void Parse()
        {
            var item = GitHubResponse.Parse("access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&token_type=bearer");

            Assert.AreEqual <string>("e72e16c7e42f292c6912e7710c838347ae178b4a", item.AccessToken);
            Assert.AreEqual <string>("bearer", item.TokenType);
        }
        public void TokenType()
        {
            var item = new GitHubResponse();
            var data = StringHelper.ValidString();

            item.TokenType = data;
            Assert.AreEqual <string>(data, item.TokenType);
        }
        public async Task GetUserProfileTest()
        {
            ProfileService           service  = new ProfileService();
            GitHubResponse <Profile> response = await service.GetUserProfileAsync("RyanThiele");

            Assert.NotNull(response);
            Assert.NotNull(response.Response);
        }
        public void AccessToken()
        {
            var item = new GitHubResponse();
            var data = StringHelper.ValidString();

            item.AccessToken = data;
            Assert.AreEqual <string>(data, item.AccessToken);
        }
예제 #8
0
        public async Task <ActionResult> GetDataByRequest(string queryText)
        {
            GitHubResponse result = null;

            if (!string.IsNullOrEmpty(queryText))
            {
                result = await manager.GetDataResponse(queryText);
            }
            return(View("Result", result));
        }
예제 #9
0
        public void Content_ShouldReturnResponseContent()
        {
            string expectedContent = "foo";
            var mockResp = new Mock<IRestResponse<object>>(MockBehavior.Strict);
            mockResp.Setup(r => r.Content)
                .Returns(expectedContent);
            var resp = new GitHubResponse<object>(mockResp.Object);

            Assert.AreEqual(expectedContent, resp.Content);
        }
예제 #10
0
        public async Task <JsonResult> GetGitHubData(string queryTxt)
        {
            GitHubResponse result = null;

            if (!string.IsNullOrEmpty(queryTxt))
            {
                result = await manager.GetDataResponse(queryTxt);
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
예제 #11
0
        public void Data_ShouldContainTheResponseData()
        {
            var expectedData = new object();
            var mockResp = new Mock<IRestResponse<object>>(MockBehavior.Strict);
            mockResp.Setup(r => r.Data)
                .Returns(expectedData);
            var resp = new GitHubResponse<object>(mockResp.Object);

            Assert.AreSame(expectedData, resp.Data);
        }
예제 #12
0
        public void ResponseStatus_ShouldReturnTheConvertedResponseResponseStatus()
        {
            ResponseStatus expectedResponseStatus = ResponseStatus.Completed;
            var mockResp = new Mock<IRestResponse<object>>(MockBehavior.Strict);
            mockResp.Setup(r => r.ResponseStatus)
                .Returns(RestSharp.ResponseStatus.Completed);
            var resp = new GitHubResponse<object>(mockResp.Object);

            Assert.AreEqual(expectedResponseStatus, resp.ResponseStatus);
        }
예제 #13
0
        public void ErrorMessage_ShouldContainTheResponseErrorMessage()
        {
            string expectedErrorMessage = "foo";
            var mockResp = new Mock<IRestResponse<object>>(MockBehavior.Strict);
            mockResp.Setup(r => r.ErrorMessage)
                .Returns(expectedErrorMessage);
            var resp = new GitHubResponse<object>(mockResp.Object);

            Assert.AreEqual(expectedErrorMessage, resp.ErrorMessage);
        }
예제 #14
0
        public void ErrorException_ShouldContainTheResponseErrorException()
        {
            var expectedException = new Exception();
            var mockResp = new Mock<IRestResponse<object>>(MockBehavior.Strict);
            mockResp.Setup(r => r.ErrorException)
                .Returns(expectedException);
            var resp = new GitHubResponse<object>(mockResp.Object);

            Assert.AreEqual(expectedException, resp.ErrorException);
        }
예제 #15
0
        private async Task PostProcessResponse(GitHubResponse response)
        {
            // Token revocation handling and abuse.
            var            abuse      = false;
            DateTimeOffset?limitUntil = null;

            if (response?.Status == HttpStatusCode.Unauthorized)
            {
                using (var ctx = _shipContextFactory.CreateInstance()) {
                    var changes = await ctx.RevokeAccessTokens(UserId);

                    await _queueClient.NotifyChanges(changes);
                }
                DeactivateOnIdle();
            }
            else if (response.Error?.IsAbuse == true)
            {
                abuse      = true;
                limitUntil = response.RetryAfter ?? DateTimeOffset.UtcNow.AddSeconds(60); // Default to 60 seconds.
            }
            else if (_rateLimit?.IsExceeded == true)
            {
                limitUntil = _rateLimit.Reset;
            }

            if (limitUntil != null)
            {
                // Don't set _lastRequestLimited until an error is logged
                _dropRequestAbuse  = abuse;
                _dropRequestsUntil = limitUntil;
                using (var context = _shipContextFactory.CreateInstance()) {
                    var oldRate = _rateLimit;
                    var newRate = new GitHubRateLimit(
                        oldRate.AccessToken,
                        oldRate.Limit,
                        Math.Min(oldRate.Remaining, GitHubRateLimit.RateLimitFloor - 1),
                        limitUntil.Value);
                    UpdateRateLimit(newRate);

                    // Record in DB for sync notification
                    await context.UpdateRateLimit(newRate);
                }

                // Force sync notification
                var changes = new dmt.ChangeSummary();
                changes.Users.Add(UserId);
                await _queueClient.NotifyChanges(changes);
            }
            else if (response.RateLimit != null)
            {
                _lastRequestLimited = false;
                // Normal rate limit tracking
                UpdateRateLimit(response.RateLimit);
            }
        }
예제 #16
0
        public void Data_ShouldContainTheResponseData()
        {
            var expectedData = new object();
            var mockResp     = new Mock <IRestResponse <object> >(MockBehavior.Strict);

            mockResp.Setup(r => r.Data)
            .Returns(expectedData);
            var resp = new GitHubResponse <object>(mockResp.Object);

            Assert.AreSame(expectedData, resp.Data);
        }
예제 #17
0
        public void ErrorMessage_ShouldContainTheResponseErrorMessage()
        {
            var expectedErrorMessage = "foo";
            var mockResp             = new Mock <IRestResponse <object> >(MockBehavior.Strict);

            mockResp.Setup(r => r.ErrorMessage)
            .Returns(expectedErrorMessage);
            var resp = new GitHubResponse <object>(mockResp.Object);

            Assert.AreEqual(expectedErrorMessage, resp.ErrorMessage);
        }
예제 #18
0
        public void ErrorException_ShouldContainTheResponseErrorException()
        {
            var expectedException = new Exception();
            var mockResp          = new Mock <IRestResponse <object> >(MockBehavior.Strict);

            mockResp.Setup(r => r.ErrorException)
            .Returns(expectedException);
            var resp = new GitHubResponse <object>(mockResp.Object);

            Assert.AreEqual <Exception>(expectedException, resp.ErrorException);
        }
예제 #19
0
        public void ContentType_ShouldReturnResponseContentType()
        {
            var expectedContentType = "foo";
            var mockResp            = new Mock <IRestResponse <object> >(MockBehavior.Strict);

            mockResp.Setup(r => r.ContentType)
            .Returns(expectedContentType);
            var resp = new GitHubResponse <object>(mockResp.Object);

            Assert.AreEqual(expectedContentType, resp.ContentType);
        }
예제 #20
0
        public void ResponseStatus_ShouldReturnTheConvertedResponseResponseStatus()
        {
            var expectedResponseStatus = NGitHub.Web.ResponseStatus.Completed;
            var mockResp = new Mock <IRestResponse <object> >(MockBehavior.Strict);

            mockResp.Setup(r => r.ResponseStatus)
            .Returns(RestSharp.ResponseStatus.Completed);
            var resp = new GitHubResponse <object>(mockResp.Object);

            Assert.AreEqual <NGitHub.Web.ResponseStatus>(expectedResponseStatus, resp.ResponseStatus);
        }
예제 #21
0
        public void StatusCode_ShouldContainResponseStatus()
        {
            var expectedStatusCode = HttpStatusCode.Conflict;
            var mockResp           = new Mock <IRestResponse <object> >(MockBehavior.Strict);

            mockResp.Setup(r => r.StatusCode)
            .Returns(expectedStatusCode);
            var resp = new GitHubResponse <object>(mockResp.Object);

            Assert.AreEqual(expectedStatusCode, resp.StatusCode);
        }
예제 #22
0
        public async Task Get_ReturnRepositoryUrl()
        {
            HttpResponseMessage response = await _testContext.Client.GetAsync("/showmethecode");

            response.EnsureSuccessStatusCode();
            response.StatusCode.Should().Be(HttpStatusCode.OK);

            string bodyResponse = await response.Content.ReadAsStringAsync();

            GitHubResponse objectResponse = JsonConvert.DeserializeObject <GitHubResponse>(bodyResponse);

            objectResponse.Should().Match <GitHubResponse>(x => x.Repository == "https://github.com/ricardofanetto/dotnetcore.git");
        }
예제 #23
0
        //        public async Task<GitHubResponse<string>> GetCompanyHtmlAsync()
        //        {
        //            GitHubResponse<string> result = new GitHubResponse<string>();
        //            GitHubResponse<ViewerResponse> response = await QueryAsync<ViewerResponse>(@"
        //{
        //   ""query"": ""query { viewer { companyHTML } }"",
        //   ""variables"" : null

        //}");
        //            result.Response = response.Response.Data.Viewer.CompanyHtml;
        //            result.Headers = response.Headers;
        //            return result;
        //        }

        public async Task <GitHubResponse <string> > GetUserBioAsync()
        {
            GitHubResponse <string>         result   = new GitHubResponse <string>();
            GitHubResponse <ViewerResponse> response = await QueryAsync <ViewerResponse>(@"
{
   ""query"": ""query { viewer { bio } }"",
   ""variables"" : null

}");

            result.Response = response.Response.Data.Viewer.Bio;
            result.Headers  = response.Headers;
            return(result);
        }
예제 #24
0
        public async Task <GitHubResponse <Uri> > GetAvatarUrlAsync()
        {
            GitHubResponse <Uri>            result   = new GitHubResponse <Uri>();
            GitHubResponse <ViewerResponse> response = await QueryAsync <ViewerResponse>(@"
{
   ""query"": ""query { viewer { avatarUrl } }"",
   ""variables"" : null

}");

            result.Response = response.Response.Data.Viewer.AvatarUrl;
            result.Headers  = response.Headers;
            return(result);
        }
예제 #25
0
        public static void CreateMore <T>(this object viewModel, GitHubResponse <List <T> > response,
                                          Action <Func <Task> > assignMore, Action <List <T> > newDataAction) where T : new()
        {
            if (response.More == null)
            {
                assignMore(null);
                return;
            }

            assignMore(async() =>
            {
                response.More.UseCache = false;
                var moreResponse       = await Locator.Current.GetService <IApplicationService>().Client.ExecuteAsync(response.More);
                viewModel.CreateMore(moreResponse, assignMore, newDataAction);
                newDataAction(moreResponse.Data);
            });
        }
예제 #26
0
        public void GetAccessTokenAsync(string clientId,
                                        string clientSecret,
                                        string code,
                                        Action <string> callback,
                                        Action <GitHubException> onError)
        {
            Requires.ArgumentNotNull(clientId, "clientId");
            Requires.ArgumentNotNull(clientSecret, "clientSecret");
            Requires.ArgumentNotNull(code, "code");
            Requires.ArgumentNotNull(callback, "callback");
            Requires.ArgumentNotNull(onError, "onError");

            var request = new RestRequest {
                Resource = "/access_token",
                Method   = Method.POST
            };

            request.AddParameter("client_id", clientId);
            request.AddParameter("client_secret", clientSecret);
            request.AddParameter("code", code);

            var client = _factory.CreateRestClient(Constants.AuthorizeUrl);

            client.ExecuteAsync(
                request,
                (r, h) => {
                var response = new GitHubResponse(r);

                GitHubException ex = null;
                if (_processor.TryProcessResponseErrors(response, out ex))
                {
                    onError(ex);
                    return;
                }

                var parameters  = response.Content.Split('&');
                var accessToken = parameters.Where(p => p.StartsWith("access_token="))
                                  .Select(p => p.Substring(("access_token=").Length))
                                  .FirstOrDefault();

                Debug.Assert(accessToken != null, "");

                callback(accessToken);
            });
        }
예제 #27
0
        public async Task <GitHubResponse <Profile> > GetSelfProfileAsync(string token)
        {
            GitHubResponse <Profile> result = new GitHubResponse <Profile>();

            using (HttpClient client = CreateHttpClient())
            {
                HttpResponseMessage response = await client.GetAsync($"https://api.github.com/user");

                result.Headers = new Models.Headers.GitHubHeaders(response.Headers);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    result.Response = await response.Content.ReadAsAsync <Profile>();
                }

                return(result);
            }
        }
예제 #28
0
        public static void CreateMore <T>(this MvxViewModel viewModel, GitHubResponse <T> response,
                                          Action <Action> assignMore, Action <T> newDataAction) where T : new()
        {
            if (response.More == null)
            {
                assignMore(null);
                return;
            }

            Action task = () =>
            {
                var moreResponse = Mvx.Resolve <IApplicationService>().Client.ExecuteAsync(response.More).Result;
                viewModel.CreateMore(moreResponse, assignMore, newDataAction);
                newDataAction(moreResponse.Data);
            };

            assignMore(task);
        }
예제 #29
0
        public static void CreateMore <T>(this ViewModel viewModel,
                                          GitHubResponse <T> response,
                                          Action <Action> assignMore,
                                          Action <T> newDataAction) where T : new()
        {
            if (response.More == null)
            {
                assignMore(null);
                return;
            }

            assignMore(new Action(() => {
                response.More.UseCache = false;
                var moreResponse       = Application.Client.Execute(response.More);
                viewModel.CreateMore(moreResponse, assignMore, newDataAction);
                newDataAction(moreResponse.Data);
            }));
        }
예제 #30
0
        public async Task <GitHubResponse <Profile> > GetUserProfileAsync(string username)
        {
            GitHubResponse <Profile> result = new GitHubResponse <Profile>();

            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("User-Agent", "Git-Hub-Companion");
                HttpResponseMessage response = await client.GetAsync($"https://api.github.com/users/{username}");

                result.Headers = new Models.Headers.GitHubHeaders(response.Headers);

                if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    result.Response = await response.Content.ReadAsAsync <Profile>();
                }

                return(result);
            }
        }
예제 #31
0
        public void GetAccessTokenAsync(string clientId,
                                        string clientSecret,
                                        string code,
                                        Action<string> callback,
                                        Action<GitHubException> onError)
        {
            Requires.ArgumentNotNull(clientId, "clientId");
            Requires.ArgumentNotNull(clientSecret, "clientSecret");
            Requires.ArgumentNotNull(code, "code");
            Requires.ArgumentNotNull(callback, "callback");
            Requires.ArgumentNotNull(onError, "onError");

            var request = new RestRequest {
                Resource = "/access_token",
                Method = Method.POST
            };
            request.AddParameter("client_id", clientId);
            request.AddParameter("client_secret", clientSecret);
            request.AddParameter("code", code);

            var client = _factory.CreateRestClient(Constants.AuthorizeUrl);

            client.ExecuteAsync(
                request,
                (r, h) => {
                    var response = new GitHubResponse(r);

                    GitHubException ex = null;
                    if (_processor.TryProcessResponseErrors(response, out ex)) {
                        onError(ex);
                        return;
                    }

                    var parameters = response.Content.Split('&');
                    var accessToken = parameters.Where(p => p.StartsWith("access_token="))
                                                .Select(p => p.Substring(("access_token=").Length))
                                                .FirstOrDefault();

                    Debug.Assert(accessToken != null, "");

                    callback(accessToken);
                });
        }
예제 #32
0
    private IEnumerator StartVersionCheck()
    {
        //first check if internet is available
        var ping  = new System.Net.NetworkInformation.Ping();
        var reply = ping.Send(new IPAddress(new byte[] { 8, 8, 8, 8 }), 5000);

        if (reply.Status == IPStatus.Success)
        {
            //internet available, check for latest version
            StartCoroutine(CheckVersion());
        }
        else
        {
            networkStatus = NetworkStatus.Error;
            busyIconTF.GetComponent <Image>().color = new Color(1, 0, 0);
            gitHubResponse = null;
        }

        yield return(null);
    }
예제 #33
0
        public async Task <GitHubResponse <T> > Fetch <T>(IGitHubClient client, GitHubRequest request, CancellationToken cancellationToken)
        {
            GitHubResponse <T> result = null;

            for (var attempt = 0; attempt <= LastAttempt; ++attempt)
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (attempt > 0)
                {
                    await Task.Delay(RetryMilliseconds *attempt);
                }

                try {
                    result = await MakeRequest <T>(client, request, cancellationToken, null);
                } catch (HttpRequestException hre) {
                    if (attempt < LastAttempt)
                    {
                        hre.Report($"Error making GitHub request: {request.Uri}");
                        continue;
                    }
                    throw;
                }

                switch (result.Status)
                {
                case HttpStatusCode.BadGateway:
                case HttpStatusCode.GatewayTimeout:
                case HttpStatusCode.InternalServerError:
                case HttpStatusCode.ServiceUnavailable:
                    continue; // retry after delay

                default:
                    break; // switch
                }

                break; //for
            }

            return(result);
        }
        public async Task CreateAuthorizationTokenForAppAsync(int currentRow, string username, string password)
        {
            AuthorizationService           service = new AuthorizationService();
            GitHubResponse <Authorization> result  = await service.CreateAuthorizationTokenForAppAsync(
                new AuthorizeParameters()
            {
                Scopes = new List <string>()
                {
                    "user", "repo"
                },
                Note = $"Test Auth" + currentRow
            },
                username,
                password);


            Assert.NotNull(result);
            Assert.NotNull(result.Headers);
            Assert.NotNull(result.Headers.GitHubOptionHeader);
            Assert.False(result.Headers.GitHubOptionHeader.IsRequired);
        }
예제 #35
0
        public static GitHubMetadata FromResponse(GitHubResponse response, bool useDangerousFirstPage = false)
        {
            var cacheData = useDangerousFirstPage ? response?.DangerousFirstPageCacheData : response?.CacheData;

            if (response?.Succeeded != true || cacheData == null)
            {
                return(null);
            }

            return(new GitHubMetadata()
            {
                UserId = cacheData.UserId,
                AccessToken = cacheData.AccessToken,
                ETag = cacheData.ETag,
                Expires = cacheData.Expires,
                LastModified = cacheData.LastModified,
                LastRefresh = response.Date,
                PollInterval = cacheData.PollInterval,
                Path = cacheData.Path,
            });
        }
예제 #36
0
        public void StatusCode_ShouldContainResponseStatus()
        {
            HttpStatusCode expectedStatusCode = HttpStatusCode.Conflict;
            var mockResp = new Mock<IRestResponse<object>>(MockBehavior.Strict);
            mockResp.Setup(r => r.StatusCode)
                .Returns(expectedStatusCode);
            var resp = new GitHubResponse<object>(mockResp.Object);

            Assert.AreEqual(expectedStatusCode, resp.StatusCode);
        }
 public void ParseDataInvalid()
 {
     GitHubResponse.Parse(StringHelper.NullEmptyWhiteSpace());
 }