public SpotifyHelper(HttpListener listener, IConfiguration configuration, HttpClient client, GitHubHelper github) { this.listener = listener; this.configuration = configuration; this.client = client; this.github = github; }
/// <summary> /// Fetches available releases from Github. /// </summary> private async void GetReleases() { _webClient = new WebClient { CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore) }; _webClient.Headers.Add("User-Agent", GitHubHelper.SQRLInstallerUserAgent); this.Releases = await GitHubHelper.GetReleases(this.EnablePreReleases); this.HasReleases = this.Releases.Length > 0; if (this.HasReleases) { this.SelectedRelease = this.Releases.OrderByDescending(r => r.published_at).FirstOrDefault(); Log.Information($"Found {this.Releases?.Count()} Releases"); PathByPlatform(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Log.Information($"We are on Windows, checking to see if an existing version of SQRL exists"); if (Registry.ClassesRoot.OpenSubKey(@"sqrl") != null) { Log.Information($"Display Warning that we may over-write the existing SQRL Install"); this.Warning = _loc.GetLocalizationValue("SchemaRegistrationWarning"); } } } this.InstallationPath = Environment.GetCommandLineArgs().Length > 1 ? Environment.GetCommandLineArgs()[1] : this.InstallationPath; }
public async Task <ActionResult> Save(string fileName, string fileContent) { if (Session["OAuthToken"] is string accessToken) { // This allows the client to make requests to the GitHub API on the user's behalf // without ever having the user's OAuth credentials. Client.Credentials = new Credentials(accessToken); } else { return(Redirect(GetOauthLoginUrl())); } try { var repository = (await GetRepo(RepoForTesting)).First(); User user = await Client.User.Current(); try { Reference reference = await GitHubHelper.UpdateContent(Client, RepoForTesting, RepoForTestingOwner, FileNameForTesting, fileContent); return(RedirectToAction("Index", new { id = repository.Id, name = repository.Name, referrer = "save_success", reason = reference.Object.Sha, user = user.Login })); } catch (Exception e) { Console.WriteLine(e); return(RedirectToAction("Index", new { id = repository.Id, name = repository.Name, referrer = "save_fail", reason = e.Message, user = user.Name })); } } catch (AuthorizationException) { // Either the accessToken is null or it's invalid. This redirects // to the GitHub OAuth login page. That page will redirect back to the // Authorize action. return(Redirect(GetOauthLoginUrl())); } }
public async Task <Models.User> Get(string login) { GitHubClient github = GitHubHelper.GetClient(); Octokit.User userBase = await github.User.Get(login); Models.User user = new Models.User(userBase); return(user); }
/// <summary> /// Installs the app in <paramref name="downloadedFileName"/> on Linux. /// </summary> /// <param name="downloadedFileName">The downloaded application files to install.</param> private void InstallOnLinux(string downloadedFileName) { Log.Information("Installing on Linux"); _executable = Path.Combine(this.InstallationPath, "SQRLDotNetClientUI"); if (!Directory.Exists(this.InstallationPath)) { Directory.CreateDirectory(this.InstallationPath); } this.DownloadPercentage = 20; //File.Move(downloadedFileName, Executable, true); ExtractZipFile(downloadedFileName, string.Empty, this.InstallationPath); try { Log.Information("Copying installer into installation location (for auto update)"); //Copy the installer but don't over-write the one included in the zip since it will likely be newer File.Copy(Process.GetCurrentProcess().MainModule.FileName, Path.Combine(this.InstallationPath, Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName)), false); } catch (Exception fc) { Log.Warning($"File copy exception: {fc}"); } using (StreamWriter sw = new StreamWriter(Path.Combine(this.InstallationPath, "sqrlversion.json"))) { sw.Write(Newtonsoft.Json.JsonConvert.SerializeObject(this.SelectedRelease.tag_name)); sw.Close(); } this.DownloadPercentage += 20; _bridgeSystem = BridgeSystem.Bash; _shell = new ShellConfigurator(_bridgeSystem); Log.Information("Creating Linux desktop icon, application and registering SQRL invokation scheme"); GitHubHelper.DownloadFile(@"https://github.com/sqrldev/SQRLDotNetClient/raw/master/SQRLDotNetClientUI/Assets/SQRL_icon_normal_64.png", Path.Combine(this.InstallationPath, "SQRL.png")); StringBuilder sb = new StringBuilder(); sb.AppendLine($"[Desktop Entry]"); sb.AppendLine("Name=SQRL"); sb.AppendLine("Type=Application"); sb.AppendLine($"Icon={(Path.Combine(this.InstallationPath, "SQRL.png"))}"); sb.AppendLine($"Exec={_executable} %u"); sb.AppendLine("Categories=Internet"); sb.AppendLine("Terminal=false"); sb.AppendLine("MimeType=x-scheme-handler/sqrl"); File.WriteAllText(Path.Combine(this.InstallationPath, "sqrldev-sqrl.desktop"), sb.ToString()); _shell.Term($"chmod -R 755 {this.InstallationPath}", Output.Internal); _shell.Term($"chmod a+x {_executable}", Output.Internal); _shell.Term($"chmod +x {Path.Combine(this.InstallationPath, "sqrldev-sqrl.desktop")}", Output.Internal); _shell.Term($"chmod a+x {Path.Combine(this.InstallationPath, Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName))}", Output.Internal); _shell.Term($"xdg-desktop-menu install {Path.Combine(this.InstallationPath, "sqrldev-sqrl.desktop")}", Output.Internal); _shell.Term($"gio mime x-scheme-handler/sqrl sqrldev-sqrl.desktop", Output.Internal); _shell.Term($"xdg-mime default sqrldev-sqrl.desktop x-scheme-handler/sqrl", Output.Internal); _shell.Term($"update-desktop-database ~/.local/share/applications/", Output.Internal); }
// GET: Repository public async Task <ActionResult> Index(long id, string name, string referrer = "edit", string reason = "", string user = "") { if (Session["OAuthToken"] is string accessToken) { // This allows the client to make requests to the GitHub API on the user's behalf // without ever having the user's OAuth credentials. Client.Credentials = new Credentials(accessToken); } else { return(Redirect(GetOauthLoginUrl())); } try { if (string.IsNullOrEmpty(user)) { var githubUser = await Client.User.Current(); user = githubUser.Login; } IReadOnlyList <RepositoryContributor> contributors = await Client.Repository.GetAllContributors(RepoForTestingOwner, RepoForTesting); if (contributors.All(c => c.Login != user)) { referrer = "not_authorized"; reason = $"{user} is not a contributor for {RepoForTesting} repository. Please send request to " + $"{RepoForTestingOwner} at <a href=" + $"'https://github.com/{RepoForTestingOwner}/{RepoForTesting}/graphs/contributors'>" + $"https://github.com/{RepoForTestingOwner}/{RepoForTesting}/graphs/contributors</a> "; } var originContent = await GitHubHelper.GetOriginContentForRepo(Client, RepoForTesting, RepoForTestingOwner, FileNameForTesting); var model = new RepositoryViewModel(id, name, new List <RepositoryFileViewModel> { originContent }, referrer, reason, user); return(View(model)); } catch (AuthorizationException) { // Either the accessToken is null or it's invalid. This redirects // to the GitHub OAuth login page. That page will redirect back to the // Authorize action. return(Redirect(GetOauthLoginUrl())); } }
public async Task FunctionHandler(ILambdaContext context) { var sw = Stopwatch.StartNew(); _context = context; _logger = _context.Logger; _logger.Log($"{context?.FunctionName} => {nameof(FunctionHandler)} => Started"); _verbose = Environment.GetEnvironmentVariable("verbose").ToBoolOrDefault(true); var githubToken = Environment.GetEnvironmentVariable("github_token"); if (githubToken.IsNullOrEmpty()) { throw new Exception("Environment Variable 'github-token' was not defined!"); } if (Environment.GetEnvironmentVariable("test_connection").ToBoolOrDefault(false)) { Log($"Your Internet Connection is {(SilyWebClientEx.CheckInternetAccess(timeout: 5000) ? "" : "NOT")} available."); } string accessToken; if (githubToken.IsHex()) { Log($"Property 'githubToken' was determined to be a hexadecimal and will be used as accessToken"); accessToken = githubToken; } else { Log($"Fetching github access token '{githubToken ?? "undefined"}' from secrets manager."); accessToken = (await _SM.GetSecret(githubToken)).JsonDeserialize <AmazonSecretsToken>()?.token; } var rateLimit = Environment.GetEnvironmentVariable("github_rate_limit").ToIntOrDefault(1000); _GIT = new GitHubHelper(new GITWrapper.GitHub.Models.GitHubRepoConfig(accessToken: accessToken, maxRatePerHour: rateLimit) { user = Environment.GetEnvironmentVariable("github_user"), branch = Environment.GetEnvironmentVariable("github_branch"), repository = Environment.GetEnvironmentVariable("github_repository"), userAgent = Environment.GetEnvironmentVariable("user_agent") ?? "Asmodat Launcher Toolkit", }); try { Log($"Processing..."); await Processing(); } finally { _logger.Log($"{context?.FunctionName} => {nameof(FunctionHandler)} => Stopped, Eveluated within: {sw.ElapsedMilliseconds} [ms]"); await Task.Delay(2500); } }
public Given_a_GitHub_ClientState() { _linkFactory = new LinkFactory(); GitHubHelper.RegisterGitHubLinks(_linkFactory); _clientstate = new GithubClientState(_linkFactory); _httpClient = new HttpClient(); _httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MyAmazingApp", "1.0")); }
public ExampleRangeTester(string workingFolder, string branchName, string prHeader, string repoFullName, int pullRequestNumber, string pullRequestCreator, string pullRequestCreatorGit) : base(workingFolder, new RangeExampleTesterConfiguration()) { BranchName = branchName; string[] repoNameParts = repoFullName.Split('/'); TestedRepoOwner = repoNameParts[0]; TestedRepoName = repoNameParts[1]; PRHeader = prHeader; PullRequestNumber = pullRequestNumber; PullRequestCreatorUser = pullRequestCreator; PullRequestCreatorGit = pullRequestCreatorGit; GitHelper = new GitHelper(workingFolder, TesterConfig.GitUserName, "fakeEmail"); GitHubHelper = new GitHubHelper(TesterConfig.GitHubToken); verifiedBuilds = BuildsHelper.GetBuilds(branchName, workingFolder, GetPlatformSpecificRemoteDXDependenciesDirectoryPath()); }
// GET: Language badge public async Task <ActionResult> GetLanguageBadge() { Response.ContentType = "image/svg+xml"; var req = System.Web.HttpContext.Current.Request; var bqd = new BadgeQueryData(req); var c = await GitHubHelper.GetClient(); var rData = await c.GetRepoData(bqd); var badge = new LanguageBadge(bqd, rData.Lang); var viewModel = new LanguageBadgeViewModel(badge); return(View("LanguageBadge", viewModel)); }
//Set data: public async Task <ActionResult> SetData(FormCollection form) { var cd = new ClientData { ClientId = form["txtId"], ClientSecret = form["txtSecret"], Login = form["txtLogin"], Password = form["txtPassword"] }; var res = await GitHubHelper.SaveClientDataAsync(cd); var model = new AdminViewModel(res); TempData["setResultModel"] = model; return(RedirectToAction("Admin", model)); }
public static async Task <IActionResult> Run( [HttpTrigger( AuthorizationLevel.Anonymous, "post", Route = "githubhelper/test/{milestones}")] HttpRequest req, string milestones, ILogger log) { string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var info = JsonConvert.DeserializeObject <GitHubInfo>(requestBody); var token = req.Headers[GitHubTokenHaderKey]; var forMilestones = (milestones == "all") ? null : milestones.Split(new char[] { ',' }).ToList(); var helper = new GitHubHelper(); var releaseNotes = await helper.CreateReleaseNotesMarkdown( info.AccountName, info.RepoName, info.BranchName, info.Projects, forMilestones, info.SinglePage, token); var resultBuilder = new StringBuilder(); foreach (var page in releaseNotes.CreatedPages) { resultBuilder .AppendLine($"> {page.FilePath}") .AppendLine() .AppendLine(page.Markdown) .AppendLine(); } return(new OkObjectResult(resultBuilder.ToString())); }
// GET: Top rated badge public async Task <ActionResult> GetTopRatedBadge() { Response.ContentType = "image/svg+xml"; var req = System.Web.HttpContext.Current.Request; var bqd = new BadgeQueryData(req); var c = await GitHubHelper.GetClient(); var repoData = await c.GetRepoData(bqd); var langTopRatedData = await GitHubHelper.GetTopCategories(repoData.Lang); foreach (var cat in langTopRatedData.Categories) { Debug.WriteLine($"cp: {cat.PercentageString}, f: {cat.From}, t: {cat.To}"); } var badge = new TopRatedBadge(bqd, "0.05%", repoData.Lang); var viewModel = new TopRatedBadgeViewModel(badge); return(View("TopRatedBadge", viewModel)); }
/// <summary> /// Installs the app in <paramref name="downloadedFileName"/> on MacOSX. /// </summary> /// <param name="downloadedFileName">The downloaded application files to install.</param> private void InstallOnMac(string downloadedFileName) { Log.Information("Installing on MacOSX"); string fileName = Path.GetTempFileName().Replace(".tmp", ".zip"); Log.Information("Downloading Mac app folder structure from Github"); GitHubHelper.DownloadFile("https://github.com/sqrldev/SQRLDotNetClient/raw/PlatformInstaller/Installers/MacOsX/SQRL.app.zip", fileName); Log.Information("Creating initial SQRL application template"); ExtractZipFile(fileName, string.Empty, this.InstallationPath); _executable = Path.Combine(this.InstallationPath, "SQRL.app/Contents/MacOS", "SQRLDotNetClientUI"); Log.Information($"Excecutable location:{_executable}"); this.DownloadPercentage = 20; ExtractZipFile(downloadedFileName, string.Empty, Path.Combine(this.InstallationPath, "SQRL.app/Contents/MacOS")); //File.Move(downloadedFileName, Executable, true); try { Log.Information("Copying installer into installation location (for auto update)"); File.Copy(Process.GetCurrentProcess().MainModule.FileName, Path.Combine(this.InstallationPath, "SQRL.app/Contents/MacOS", Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName)), false); } catch (Exception fc) { Log.Error($"File copy exception: {fc}"); } using (StreamWriter sw = new StreamWriter(Path.Combine(this.InstallationPath, "SQRL.app/Contents/MacOS", "sqrlversion.json"))) { Log.Information($"Finished installing SQRL version: {this.SelectedRelease.tag_name}"); sw.Write(Newtonsoft.Json.JsonConvert.SerializeObject(this.SelectedRelease.tag_name)); sw.Close(); } this.DownloadPercentage += 20; _bridgeSystem = BridgeSystem.Bash; _shell = new ShellConfigurator(_bridgeSystem); Log.Information("Changing executable file to be executable a+x"); _shell.Term($"chmod a+x {_executable}", Output.Internal); _shell.Term($"chmod a+x {Path.Combine(this.InstallationPath, "SQRL.app/Contents/MacOS", Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName))}", Output.Internal); }
// GET: Top 1000 badge public async Task <ActionResult> GetTop1000Badge() { Response.ContentType = "image/svg+xml"; var req = System.Web.HttpContext.Current.Request; var bqd = new BadgeQueryData(req); var c = await GitHubHelper.GetClient(); //var repoData = await GitHubHelper.GetRepoData(bqd.User, bqd.Repo); var repoData = await c.GetRepoData(bqd); Debug.Write("GOOOOO!!!!!!!!!!"); foreach (var l in Languages.All) { Debug.WriteLine("l: " + l.Name); var repos = c.Search.SearchRepo(new SearchRepositoriesRequest { Language = l.OctokitLanguage, Order = SortDirection.Descending, SortField = RepoSearchSort.Stars, PerPage = 100, Page = 1 }).Result.Items; Debug.WriteLine("repo: " + repos.FirstOrDefault()?.FullName); } var top1000 = await DataGetter.GetTop1000(repoData.Lang.ApiName); var place = top1000?.Repos?.FirstOrDefault(r => r.UserName.Equals(repoData.UserName) && r.RepoName.Equals(repoData.RepoName))?.Place ?? 0; var badge = new Top1000Badge(bqd, place.ToString(), repoData.Lang); var viewModel = new Top1000BadgeViewModel(badge); return(View("Top1000Badge", viewModel)); }
/// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel(IDialogCoordinator dialogCoordinator) { Release razor = GitHubHelper.GetLatestRazorVersion(false); Release cuo = GitHubHelper.GetLatestClassicUOVersion(false); RazorVersion = $"Razor {razor.TagName} ({razor.PublishedAt:g})"; CUOVersion = $"ClassicUO {cuo.TagName} ({cuo.PublishedAt:g})"; InstallUpdateCommand = new RelayCommand(DoConfirmInstallUpdate); BrowseInstallPathCommand = new RelayCommand(DoSetInstallPath); BrowseUOPathCommand = new RelayCommand(DoSetUODataPath); WebsiteCommand = new RelayCommand(DoWebsite); _dialogCoordinator = dialogCoordinator; IsButtonEnabled = true; InstallCUO = true; InstallPath = ConfigurationManager.AppSettings["InstallPath"]; UODataPath = ConfigurationManager.AppSettings["UODataPath"]; ServerHost = ConfigurationManager.AppSettings["ServerHost"]; ServerPort = ConfigurationManager.AppSettings["ServerPort"]; ClientVersion = ConfigurationManager.AppSettings["ClientVersion"]; }
public void GetURL_Deve_Retornar_URL_Correta() { var obj = new GitHubHelper(); Assert.Equal(GitHubHelper.GITHUB_URL, obj.GetURL()); }
public async Task <Organization> Get(string name) { Organization org = await GitHubHelper.GetOrganizationByName(name); return(org); }
public static async Task <IActionResult> Run( [HttpTrigger( AuthorizationLevel.Function, "post", Route = "autocommit")] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var data = JsonConvert.DeserializeObject <CommitData>(requestBody); if (data == null) { return(new BadRequestObjectResult("No data")); } if (string.IsNullOrEmpty(data.Message)) { data.Message = "Committed by AutoCommit"; } if (string.IsNullOrEmpty(data.Account)) { return(new BadRequestObjectResult("Account may not be empty")); } if (string.IsNullOrEmpty(data.Repo)) { return(new BadRequestObjectResult("Repo may not be empty")); } if (data.Files == null || data.Files.Count == 0) { return(new BadRequestObjectResult("No files to commit")); } var token = Environment.GetEnvironmentVariable(GitHubTokenVariableName); if (string.IsNullOrEmpty(token)) { return(new BadRequestObjectResult("GitHub token must be configured in the App Settings")); } var commitFilesData = data.Files .Select(f => (f.Path, f.Content)) .ToList(); var helper = new GitHubHelper(); var error = await helper.CommitFiles( data.Account, data.Repo, data.Branch ?? DefaultBranchName, token, data.Message, commitFilesData); // TODO Allow function to receive a list of path / content objects if (!string.IsNullOrEmpty(error)) { if (error.StartsWith("Error getting heads:")) { return(new BadRequestObjectResult($"Branch not found: {data.Branch}")); } return(new BadRequestObjectResult(error)); } return(new OkObjectResult("Done")); }
private void InstallUpdateBackgroundWorkerDoWork(object sender, DoWorkEventArgs e) { try { IsButtonEnabled = false; if (string.IsNullOrEmpty(UODataPath) || !InstallerHelper.CheckUoPath(UODataPath)) { MessageBox.Show($"'{UODataPath}' doesn't appear to be a valid UO installation path."); return; } InstallerHelper.ValidatePath(InstallPath); ReleaseAsset razor = GitHubHelper.GetLatestRazorVersion(UseRazorPreview).Assets[0]; ReleaseAsset cuo = GitHubHelper.GetLatestClassicUOVersion(UseCUOPreview).Assets[0]; DownloadFile(razor.BrowserDownloadUrl, Path.Combine(InstallPath, razor.Name)); DownloadFile(cuo.BrowserDownloadUrl, Path.Combine(InstallPath, cuo.Name)); ZipArchive razorZip = ZipFile.OpenRead(Path.Combine(InstallPath, razor.Name)); foreach (ZipArchiveEntry entry in razorZip.Entries) { string full = Path.Combine(InstallPath, "Razor", entry.FullName); string dirName = Path.GetDirectoryName(full); if (!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } if (!string.IsNullOrEmpty(Path.GetFileName(full))) { entry.ExtractToFile(full, true); } } if (InstallCUO) { ZipArchive cuoZip = ZipFile.OpenRead(Path.Combine(InstallPath, cuo.Name)); foreach (ZipArchiveEntry entry in cuoZip.Entries) { string full = Path.Combine(InstallPath, entry.FullName); string dirName = Path.GetDirectoryName(full); if (!Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } if (!string.IsNullOrEmpty(Path.GetFileName(full))) { entry.ExtractToFile(full, true); } } ClassicUoModel settings = new ClassicUoModel { UltimaOnlineDirectory = UODataPath, IP = ServerHost, Port = Convert.ToInt32(ServerPort), ClientVersion = ClientVersion, Plugins = new[] { Path.Combine(InstallPath, "Razor", "Razor.exe") } }; File.WriteAllText(Path.Combine(InstallPath, "settings.json"), JsonConvert.SerializeObject(settings)); } InstallerHelper.UpdateSetting("InstallPath", InstallPath); InstallerHelper.UpdateSetting("UODataPath", UODataPath); InstallerHelper.UpdateSetting("ServerHost", ServerHost); InstallerHelper.UpdateSetting("ServerPort", ServerPort); InstallerHelper.UpdateSetting("ClientVersion", ClientVersion); if (ShowLaunchDialogCommand.CanExecute(null)) { ShowLaunchDialogCommand.Execute(null); } } catch (Exception ex) { MessageBox.Show($"Unexpected error. {ex.Message}"); } }
public void GetURL_Deve_Retornar_URL_Valida() { var obj = new GitHubHelper(); Assert.True(Uri.IsWellFormedUriString(obj.GetURL(), UriKind.Absolute)); }