private async Task CreateOrUpdateKnownCommentersFile(KnownCommenterResponse knownCommenterResponse, string branch)
        {
            var message = $"Add known commenter '{knownCommenterResponse.Username}'";
            var content = AddKnownCommenterToCsvContent(knownCommenterResponse);

            if (knownCommenterResponse.FileExists)
            {
                var updateFileRequest = new UpdateFileRequest(message, content, knownCommenterResponse.Sha, branch);
                await _github.Repository.Content.UpdateFile(_owner, _repo, _knownCommentersPath, updateFileRequest);
            }
            else
            {
                var createFileRequest = new CreateFileRequest(message, content, branch);
                await _github.Repository.Content.CreateFile(_owner, _repo, _knownCommentersPath, createFileRequest);
            }
        }
Example #2
0
        /// <summary>
        /// Upload image to N2SOURCE/{id}.gif
        /// 上傳圖片至 N2SOURCE/{id}.gif
        /// </summary>
        /// <param name="id"></param>
        /// <param name="imageBytes"></param>
        /// <param name="message"></param>
        public void UpoloadImageToSource(string id, byte[] imageBytes, string message)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException("id");
            }
            if (imageBytes == null)
            {
                throw new ArgumentNullException("imageBytes");
            }

            DeleteSource(id);
            var updateRequest = new UpdateFileRequest(message, Convert.ToBase64String(imageBytes), "SHA", false);

            var res = GithubClient.Repository.Content.UpdateFile(Repo.Id, "N2SOURCE" + "/" + id + ".gif", updateRequest).Result;
        }
Example #3
0
        public Node UpdateFile(UpdateFileRequest request)
        {
            _client.Executor.CheckApiServerVersion();

            #region Parameter Validation

            request.MustNotNull(nameof(request));
            request.Id.MustPositive(nameof(request.Id));
            request.Name.MustNotNullOrEmptyOrWhitespace(nameof(request.Name), true);

            #endregion

            ApiUpdateFileRequest apiUpdateFileRequest = FileMapper.ToApiUpdateFileRequest(request);
            IRestRequest         restRequest          = _client.Builder.PutFile(request.Id, apiUpdateFileRequest);
            ApiNode result = _client.Executor.DoSyncApiCall <ApiNode>(restRequest, RequestType.PutFile);
            return(NodeMapper.FromApiNode(result));
        }
Example #4
0
        public async Task <ActionResult <File> > UpdateFile()
        {
            var assetClient = _mindSphereSdkService.GetAssetManagementClient();
            var fs          = new FileStream("updated-test.txt", FileMode.Open);

            var request = new UpdateFileRequest()
            {
                Id          = "d50316fdc608471c97cbe9a92a7ac4fc",
                File        = fs,
                Name        = "updated-test.txt",
                Description = "updated file",
                Scope       = "private",
                IfMatch     = "0"
            };
            var file = await assetClient.UpdateFileAsync(request);

            return(StatusCode(200, file));
        }
        //a16e3baf8fa8784dc45ec4f49a9856c239992818
        //
        public static void UploadFile(string token, string userName, string reponame, string repoId, string localPath, string ownerId)
        {
            //這 DONMATEST 可以任意都可以
            var client = new GitHubClient(new ProductHeaderValue("GISL"));

            //從網站上取得的 personal access token https://github.com/settings/tokens
            var tokenAuth = new Credentials(token);

            client.Credentials = tokenAuth;

            //try
            //{
            //    var existingFiles = client.Repository.Content.GetAllContentsByRef(userName, reponame, "imgs", "master").Result;
            //    //如果有找到已存在就刪除
            //    foreach (var f in existingFiles)
            //    {
            //        if (f.Name == Path.GetFileName(localPath))
            //        {
            //            await client.Repository.Content.DeleteFile(long.Parse(repoId), "imgs/" + Path.GetFileName(localPath), new DeleteFileRequest("delete file", f.Sha));
            //            break;
            //        }
            //    }
            //}
            //catch
            //{

            //}


            //最後一個參數是否要轉成 base64
            var updateRequest = new UpdateFileRequest("Hi , Upload by GISL Tool. " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Convert.ToBase64String(File.ReadAllBytes(localPath)), "SHA", false);

            var res = client.Repository.Content.UpdateFile(long.Parse(repoId), "imgs/" + Path.GetFileName(localPath), updateRequest).Result;

            var img = new Models.ImageInfo();

            img.Id         = Path.GetFileNameWithoutExtension(localPath);
            img.LastUpdate = DateTime.Now;
            img.GitPath    = res.Content.DownloadUrl;
            img.Length     = Convert.ToDecimal(res.Content.Size) / ((1024m * 1024m));
            img.Owner      = ownerId;
            img.TokenId    = userName + repoId;
            Global._Role.GetOp("IMAGES").Update(img.Id, img);
        }
Example #6
0
        private static void UploadToGithub(string path, string filename)
        {
            string githubOAuthToken = ConfigurationManager.AppSettings.Get("SerivceGithubOAuthToken");
            string githubUploadUser = ConfigurationManager.AppSettings.Get("SerivceGithubUploadUsername");
            string githubUploadRepo = ConfigurationManager.AppSettings.Get("SerivceGithubUploadRepositoryName");
            string githubUploadDir  = ConfigurationManager.AppSettings.Get("SerivceGithubUploadDirectoryName");

            if (!string.IsNullOrEmpty(githubOAuthToken))
            {
                var client    = new GitHubClient(new ProductHeaderValue("xprl-crawler"));
                var tokenAuth = new Credentials(githubOAuthToken);
                client.Credentials = tokenAuth;

                string data          = File.ReadAllText(path + filename);
                var    file          = client.Repository.Content.GetAllContentsByRef(githubUploadUser, githubUploadRepo, githubUploadDir + filename, "master").GetAwaiter().GetResult();
                var    updateRequest = new UpdateFileRequest("Weekly auto update", data, file[0].Sha);

                client.Repository.Content.UpdateFile(githubUploadUser, githubUploadRepo, githubUploadDir + filename, updateRequest).GetAwaiter().GetResult();
            }
        }
Example #7
0
        public static async Task Func([ActivityTrigger] string[] contests, ILogger log)
        {
            var json = JsonSerializer.Serialize(contests);

            var ghClient = GitHubUtil.Client;


            log.LogInformation("fetching all contents..");
            var contestsJson = (await ghClient.Repository.Content.GetAllContents(GitHubUtil.Owner, GitHubUtil.Repo, "contests.json")).First();

            log.LogInformation("fetched");
            var request = new UpdateFileRequest($"update contests.json", json, contestsJson.Sha)
            {
                Committer = GitHubUtil.Comitter
            };

            log.LogInformation("updating contests...");
            await ghClient.Repository.Content.UpdateFile(GitHubUtil.Owner, GitHubUtil.Repo, "contests.json", request);

            log.LogInformation("updated");
        }
Example #8
0
        internal static ApiUpdateFileRequest ToApiUpdateFileRequest(UpdateFileRequest updateFileRequest)
        {
            ApiExpiration apiExpiration = null;

            if (updateFileRequest.Expiration.HasValue)
            {
                apiExpiration = new ApiExpiration()
                {
                    ExpireAt         = updateFileRequest.Expiration,
                    EnableExpiration = updateFileRequest.Expiration.Value.Ticks != 0
                };
            }

            ApiUpdateFileRequest apiUpdateFileRequest = new ApiUpdateFileRequest {
                Name           = updateFileRequest.Name,
                Notes          = updateFileRequest.Notes,
                Classification = EnumConverter.ConvertClassificationEnumToValue(updateFileRequest.Classification),
                Expiration     = apiExpiration
            };

            return(apiUpdateFileRequest);
        }
Example #9
0
        /// <summary>
        /// Upload image to N2SOURCE/{id}.gif
        /// 上傳圖片至 N2SOURCE/{id}.gif
        /// </summary>
        /// <param name="id">圖片編號</param>
        /// <param name="localImagePath">本地圖片位置</param>
        /// <param name="message">comment</param>
        public void UpoloadImageToSource(string id, string localImagePath, string message)
        {
            if (string.IsNullOrEmpty(localImagePath))
            {
                throw new ArgumentNullException("localImagePath");
            }
            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentNullException("id");
            }

            if (!File.Exists(localImagePath))
            {
                throw new FileNotFoundException("local image not found.");
            }

            DeleteSource(id);

            var updateRequest = new UpdateFileRequest(message, Convert.ToBase64String(File.ReadAllBytes(localImagePath)), "SHA", false);

            var res = GithubClient.Repository.Content.UpdateFile(Repo.Id, "N2SOURCE" + "/" + id + ".gif", updateRequest).Result;
        }
Example #10
0
        public async void NullOutMetadata()
        {
            var md = TestMetadata;
            var f1 = await _hiarc.CreateFile(_hiarc.BuildPath(TEST_FILE_TINY), md);

            var updatedMD = new Dictionary <string, object>
            {
                { "department", null },
                { "quotaCarrying", null }
            };

            var request = new UpdateFileRequest
            {
                Metadata = updatedMD
            };

            var updatedFile = await _hiarc.UpdateFile(f1.Key, request);

            Assert.Equal(3, updatedFile.Metadata.Keys.Count);

            updatedMD = new Dictionary <string, object>
            {
                { "targetRate", null },
                { "level", null },
                { "startDate", null }
            };

            request = new UpdateFileRequest
            {
                Metadata = updatedMD
            };

            updatedFile = await _hiarc.UpdateFile(f1.Key, request);

            Assert.Null(updatedFile.Metadata);

            await _hiarc.DeleteFile(f1.Key);
        }
Example #11
0
        public void ToApiUpdateFileRequest()
        {
            // ARRANGE
            ApiUpdateFileRequest expected = FactoryFile.ApiUpdateFileRequest;

            expected.Classification = 2;

            UpdateFileRequest param = new UpdateFileRequest(24654)
            {
                Classification = (Classification)Enum.ToObject(typeof(Classification), expected.Classification),
                Expiration     = expected.Expiration.ExpireAt,
                Name           = expected.Name,
                Notes          = expected.Notes
            };

            Mock.Arrange(() => EnumConverter.ConvertClassificationEnumToValue(param.Classification)).Returns(expected.Classification);

            // ACT
            ApiUpdateFileRequest actual = FileMapper.ToApiUpdateFileRequest(param);

            // ASSERT
            Assert.Equal(expected, actual, new ApiUpdateFileRequestComparer());
        }
Example #12
0
        private void UpdateFile(UpdateFileRequest updateFileMessage)
        {
            Action commit = () =>
            {
                var fileName = updateFileMessage.Name;

                Logging.Log($"Update file: {fileName}");

                var containedMethods =
                    updateFileMessage.File.Classes.SelectMany(
                        updatedClass => myProgramBuilder.UpdateClass(updatedClass));

                myProgramBuilder.UpdateFile(fileName, containedMethods);
            };

            if (!myProgramLock)
            {
                commit();
            }
            else
            {
                myQueuedCommits.Enqueue(commit);
            }
        }
Example #13
0
        static async Task Main()
        {
            var badiInfoScraper = new BadiInfoScraper();
            var results         = await badiInfoScraper.GetBadiInfo();

            ConsoleTable.From(results).Write();

            var github    = new GitHubClient(new ProductHeaderValue("BadiInfoUpdater"));
            var tokenAuth = new Credentials(Environment.GetEnvironmentVariable("GH_TOKEN"));

            github.Credentials = tokenAuth;

            var jsonContent = JsonSerializer.Serialize(results, new JsonSerializerOptions {
                WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            });

            var existingFile = await github.Repository.Content.GetAllContents("evolvedlight", "ZhBadiStatus", "latest.json");

            var upReq = new UpdateFileRequest("Update Badi Statuses", jsonContent, existingFile.First().Sha, "main");

            var res = await github.Repository.Content.UpdateFile("evolvedlight", "ZhBadiStatus", "latest.json", upReq);

            Console.WriteLine(res.Commit.Sha);
        }
        /// <summary>
        /// Creates a commit that updates the contents of a file in a repository.
        /// </summary>
        /// <param name="owner">The owner of the repository</param>
        /// <param name="name">The name of the repository</param>
        /// <param name="path">The path to the file</param>
        /// <param name="request">Information about the file to update</param>
        /// <returns>The updated content</returns>
        public IObservable<RepositoryContentChangeSet> UpdateFile(string owner, string name, string path, UpdateFileRequest request)
        {
            Ensure.ArgumentNotNullOrEmptyString(owner, "owner");
            Ensure.ArgumentNotNullOrEmptyString(name, "name");
            Ensure.ArgumentNotNullOrEmptyString(path, "path");
            Ensure.ArgumentNotNull(request, "request");

            return _client.Repository.Content.UpdateFile(owner, name, path, request).ToObservable();
        }
Example #15
0
        public static async Task <bool> Run([ActivityTrigger] string contestScreenName, ILogger log)
        {
            var startTime = DateTime.Now;

            log.LogInformation("start updating {0}", contestScreenName);
            var ghClient = GitHubUtil.Client;
            var acClient = new AtCoderClient();

            var session = Secrets.GetSecret("AtCoderCSRFToken");
            await acClient.LoginAsync(session);

            var standings = await acClient.GetStandingsAsync(contestScreenName);

            var jsonPath = $"aperfs/{contestScreenName}.json";

            bool found;
            RepositoryContent content;

            try
            {
                content = (await ghClient.Repository.Content.GetAllContents(GitHubUtil.Owner, GitHubUtil.Repo, jsonPath)).First();
                found   = true;
            }
            catch (NotFoundException)
            {
                content = null;
                found   = false;
            }
            var dic = content is null ? new Dictionary <string, double>() : JsonSerializer.Deserialize <Dictionary <string, double> >(content.Content);

            log.LogInformation("start crawling.");
            bool abort = false;

            foreach (var standingData in standings.StandingsData)
            {
                if ((DateTime.Now - startTime).TotalMinutes >= 8)
                {
                    log.LogWarning("time limit is nearing. abort.");
                    abort = true;
                    break;
                }
                if (standingData.UserIsDeleted ||
                    standingData.Competitions == 0 ||
                    !standingData.IsRated ||
                    dic.ContainsKey(standingData.UserScreenName))
                {
                    continue;
                }
                var history = await acClient.GetCompetitionHistoryAsync(standingData.UserScreenName);

                var beforeContestPerfs = history?.TakeWhile(x => x.ContestScreenName.Split('.', 2).First() != contestScreenName)?.Where(x => x.IsRated)?.Select(x => x.InnerPerformance)?.ToArray();
                var aperf = Rating.CalcAPerf(beforeContestPerfs);
                if (aperf is null)
                {
                    log.LogWarning($"aperf is null. screenName: {standingData.UserScreenName}");
                    continue;
                }
                dic.Add(standingData.UserScreenName, aperf.Value);
                await Task.Delay(100);
            }
            log.LogInformation("end crawling.");

            var options = new JsonSerializerOptions();

            options.Converters.Add(new TruncateDoubleConverter());
            var json = JsonSerializer.Serialize(dic, options);

            if (!found)
            {
                var request = new CreateFileRequest($"add aperfs data of {contestScreenName}", json)
                {
                    Committer = GitHubUtil.Comitter
                };
                await ghClient.Repository.Content.CreateFile(GitHubUtil.Owner, GitHubUtil.Repo, jsonPath, request);
            }
            else
            {
                var request = new UpdateFileRequest($"update aperfs data of {contestScreenName}", json, content.Sha)
                {
                    Committer = GitHubUtil.Comitter
                };
                await ghClient.Repository.Content.UpdateFile(GitHubUtil.Owner, GitHubUtil.Repo, jsonPath, request);
            }

            return(abort || !standings.Fixed);
        }
Example #16
0
        public void UpdateFile(string name, File file)
        {
            var request = new UpdateFileRequest(name, file);

            myClient.EnqueueRequest(request, _ => { });
        }
Example #17
0
        /// <summary>
        /// Creates a commit that updates the contents of a file in a repository.
        /// </summary>
        /// <param name="repositoryId">The Id of the repository</param>
        /// <param name="path">The path to the file</param>
        /// <param name="request">Information about the file to update</param>
        public IObservable <RepositoryContentChangeSet> UpdateFile(long repositoryId, string path, UpdateFileRequest request)
        {
            Ensure.ArgumentNotNullOrEmptyString(path, nameof(path));
            Ensure.ArgumentNotNull(request, nameof(request));

            return(_client.Repository.Content.UpdateFile(repositoryId, path, request).ToObservable());
        }
Example #18
0
        public override async Task <Empty> UpdateFile(UpdateFileRequest updateFileRequest, ServerCallContext context)
        {
            var updateFile = _mapper.Map <UpdateFileRequest, UpdateFile>(updateFileRequest);

            return(_mapper.Map <Unit, Empty>(await _mediator.Send(updateFile)));
        }
Example #19
0
 private static async Task UpdateFile(this GitHubClient client, Repository repo, string text, string path, string sha)
 {
     var updateFileReq = new UpdateFileRequest("V2Ray config changed.", text, sha, true);
     await client.Repository.Content.UpdateFile(repo.Id, path, updateFileReq);
 }
        /// <summary>
        /// Creates a commit that updates the contents of a file in a repository.
        /// </summary>
        /// <param name="owner">The owner of the repository</param>
        /// <param name="name">The name of the repository</param>
        /// <param name="path">The path to the file</param>
        /// <param name="request">Information about the file to update</param>
        /// <returns>The updated content</returns>
        public IObservable<RepositoryContentChangeSet> UpdateFile(string owner, string name, string path, UpdateFileRequest request)
        {
            Ensure.ArgumentNotNullOrEmptyString(owner, "owner");
            Ensure.ArgumentNotNullOrEmptyString(name, "name");
            Ensure.ArgumentNotNullOrEmptyString(path, "path");
            Ensure.ArgumentNotNull(request, "request");

            return _client.Repository.Content.UpdateFile(owner, name, path, request).ToObservable();
        }
        /// <summary>
        /// Creates a commit that updates the contents of a file in a repository.
        /// </summary>
        /// <param name="repositoryId">The Id of the repository</param>
        /// <param name="path">The path to the file</param>
        /// <param name="request">Information about the file to update</param>
        public IObservable<RepositoryContentChangeSet> UpdateFile(int repositoryId, string path, UpdateFileRequest request)
        {
            Ensure.ArgumentNotNullOrEmptyString(path, "path");
            Ensure.ArgumentNotNull(request, "request");

            return _client.Repository.Content.UpdateFile(repositoryId, path, request).ToObservable();
        }