private string GetIssueIdFromDescriptionOrDefaultIssueId(BearerTokenConnection connection, ClockifyWebhookModel clockifyWebhook, ClockifyYouTrackAssociation association, User user) { // Выделяем issueId из описания вебхука, // если в переданном нам YouTrack он есть - возвращаем его, // иначе смотрим на defaultIssueId. var issueId = GetYouTrackIssueId(clockifyWebhook.description); if (IsIssueExists(connection, issueId)) { return(issueId); } // Смотрим defaultIssueId. if (!string.IsNullOrEmpty(user.defaultIssueId)) { return(user.defaultIssueId); } if (!string.IsNullOrEmpty(association.defaultIssueId)) { return(association.defaultIssueId); } // Если ничего не нашли возвращаем null. return(null); }
public void DeleteWorkItemInIssue(ClockifyYouTrackAssociation association, ClockifyWebhookModel clockifyWebhook) { // Ищем от какого пользователя идет запрос, некая аутентификация и авторизация. var user = association.users.FirstOrDefault(u => u.clockifyUserId == clockifyWebhook.userId); if (user == null) { return; } // Создаем подключение к YouTrack. var connection = new BearerTokenConnection(association.domain, association.permToken); // Берем issueId из описания вебхука или берем // запасной issueId (пользовательский или основной). var issueId = GetIssueIdFromDescriptionOrDefaultIssueId(connection, clockifyWebhook, association, user); // Если найти issueId не удалось, завершаем метод - // мы не знаем где удалять отметку времени. if (string.IsNullOrEmpty(issueId)) { return; } // Получаем отметку времени из YouTrack, еслии ее нет, завершаем метод - удалять нечего. var workItem = GetWorkItemFromIssue(connection, issueId, clockifyWebhook); if (workItem == null) { return; } // Удаляем отметку времени в YouTrack. DeleteWorkItemForIssue(connection, issueId, workItem.Id); }
public void CreateWorkItemInIssue(ClockifyYouTrackAssociation association, ClockifyWebhookModel clockifyWebhook) { // Ищем от какого пользователя идет запрос, некая аутентификация и авторизация. var user = association.users.FirstOrDefault(u => u.clockifyUserId == clockifyWebhook.userId); if (user == null) { return; } // Создаем подключение к YouTrack. var connection = new BearerTokenConnection(association.domain, association.permToken); // Берем issueId из описания вебхука или берем // запасной issueId (пользовательский или основной). var issueId = GetIssueIdFromDescriptionOrDefaultIssueId(connection, clockifyWebhook, association, user); // Если найти issueId не удалось, завершаем метод - // мы не знаем куда добавлять отметку времени. if (string.IsNullOrEmpty(issueId)) { return; } // Создаем отметку времени, которая будет отправлена в YouTrack. var workItem = CreateWorkItem(clockifyWebhook, user); // Отправляем отметку времени в конкретный issue в конкретном YouTrack. CreateWorkItemForIssue(connection, issueId, workItem); }
// CreateIssue public static bool CreateIssue(BearerTokenConnection connection, Issue issue) { // Create new YoutrackSharp Issue and Set Standard Fields var newIssue = new YouTrackSharp.Issues.Issue() { Summary = issue.Summary, Description = issue.Description, }; // Set CustomFields foreach (var customField in issue.CustomFields) { newIssue.SetField(customField.Name, customField.Value); } try { connection.CreateIssuesService().CreateIssue("OTHER", newIssue).Wait(); } catch (Exception) { return(false); } return(true); }
private WorkItem GetWorkItemFromIssue(BearerTokenConnection connection, string issueId, ClockifyWebhookModel clockifyWebhook) { var timeTrackingService = connection.CreateTimeTrackingService(); var workItems = timeTrackingService.GetWorkItemsForIssue(issueId).Result.ToList(); var workItem = workItems.FirstOrDefault(item => IsTimeStampIdExists(item.Description, clockifyWebhook.id)); return(workItem); }
public YouTrackService() { serverUrl = "https://kpfu-net.myjetbrains.com/youtrack"; connection = new BearerTokenConnection(serverUrl, "perm:YW5nZWxh.NTUtMw==.PBKFTDQmoWvoxdzM7t5TPWPtKrTeOI"); issueService = connection.CreateIssuesService(); timeService = connection.CreateTimeTrackingService(); projectService = connection.CreateProjectsService(); }
private bool OpenConnection() { try { // Change so they are injected var uri = System.Configuration.ConfigurationManager.AppSettings["YoutrackUri"]; var token = System.Configuration.ConfigurationManager.AppSettings["YoutrackToken"]; connection = new BearerTokenConnection(uri, token); return(true); } catch (Exception ex) { Console.WriteLine(ex.Message); return(false); } }
public static async Task Main(string[] args) { try { await Task.Run(() => Parser.Default.ParseArguments <Config>(args) .WithParsed(c => { ourConfig = c; }) .WithNotParsed(HandleParseError)); if (ourConfig == null) { return; } var textBuilder = new TextBuilder(); var connection = new BearerTokenConnection(ourConfig.HostUrl, ourConfig.Token); var commentThreshold = ourConfig.CommentThreshold; var sw = Stopwatch.StartNew(); var issuesService = connection.CreateIssuesService(); var taggedIssues = new List <Issue>(); if (!string.IsNullOrEmpty(ourConfig.TagForHotIssues)) { taggedIssues.AddRange(await issuesService.GetIssues($"tag: {ourConfig.TagForHotIssues}", take: 100)); } var list = new List <Issue>(); for (int i = 0; i < 20; i++) { try { var dexpIssues = await issuesService.GetIssuesInProject( "DEXP", $"{SearchFiler} {ourConfig.SearchCondition}", skip : i *100, take : 100, updatedAfter : DateTime.Now - TimeThreshold); list.AddRange(dexpIssues); } catch (Exception e) { Console.Error.WriteLine(e); } } await RemoveTags(taggedIssues, list, issuesService); var dexpHotIssues = list .Where(it => it.Comments.Count > commentThreshold || it.GetField("created").AsDateTime() > DateTime.Now - TimeSpan.FromDays(15) && it.Comments.Count > commentThreshold / 2) .OrderByDescending(it => it.Comments.Count) .ToList(); if (!string.IsNullOrEmpty(ourConfig.TagForHotIssues)) { var tasks = dexpHotIssues.Select(issue => issuesService.SetTag(issue, ourConfig.TagForHotIssues)); //await Task.WhenAll(tasks); // too many network requests simultaneously would fail Console.WriteLine($"Setting tags {ourConfig.TagForHotIssues}"); foreach (var task in tasks) { Console.Write("."); await task; } Console.WriteLine("Finished."); } var topHotTextBuilder = new TextBuilder(); var dexpTopHotIssues = dexpHotIssues.Take(ourConfig.HotIssuesAmount); var dexpHotAggregated = Aggregate(dexpHotIssues); var dexpTopAggregated = AggregateTop(dexpTopHotIssues); sw.Stop(); textBuilder.AppendHeader("DEXP HOT (" + dexpHotIssues.Count + ")"); var maxCount = dexpHotIssues.Count >= ourConfig.HotIssuesAmount ? ourConfig.HotIssuesAmount : dexpHotIssues.Count; topHotTextBuilder.AppendHeader($"Top {maxCount} of {dexpHotIssues.Count} hot issues"); textBuilder.AppendLine(dexpHotAggregated.ToPlainText(), dexpHotAggregated.ToHtml()); textBuilder.AppendHeader("Statistics"); textBuilder.AppendKeyValue("Time", $"{sw.Elapsed.TotalSeconds:0.00} sec"); textBuilder.AppendKeyValue("dexpIssues.Count", list.Count.ToString()); textBuilder.AppendKeyValue("dexpHotIssues.Count", dexpHotIssues.Count.ToString()); topHotTextBuilder.AppendLine(dexpTopAggregated, dexpTopAggregated); await File.WriteAllTextAsync("report.html", textBuilder.ToHtml()); await File.WriteAllTextAsync("report.txt", textBuilder.ToPlainText()); Console.WriteLine(topHotTextBuilder.ToPlainText()); using (var writer = new TeamCityServiceMessages().CreateWriter(Console.WriteLine)) { writer.WriteBuildParameter("env.short_report", topHotTextBuilder.ToPlainText()); } } catch (UnauthorizedConnectionException e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Can't establish a connection to YouTrack"); Console.WriteLine(e.Demystify()); Console.ResetColor(); } }
// GetProjectCustomField public static YouTrackSharp.Projects.CustomField GetIssueCustomField(BearerTokenConnection connection, string projectId, string fieldId) { var customField = connection.ProjectCustomFieldsService().GetProjectCustomField(projectId, fieldId); return(customField.Result); }
// GetIssues public static ICollection <YouTrackSharp.Issues.Issue> GetIssues(BearerTokenConnection connection, string query) { var issues = connection.CreateIssuesService().GetIssues(query); return(issues.Result); }
// GetIssue public static YouTrackSharp.Issues.Issue GetIssue(BearerTokenConnection connection, string issueId) { var issue = connection.CreateIssuesService().GetIssue(issueId); return(issue.Result); }
private bool IsIssueExists(BearerTokenConnection connection, string issueId) { var issueService = connection.CreateIssuesService(); return(issueService.Exists(issueId).Result); }
// GetProjectCustomFields public static ICollection <YouTrackSharp.Projects.CustomField> GetIssueCustomFields(BearerTokenConnection connection, string projectId) { var customFields = connection.ProjectCustomFieldsService().GetProjectCustomFields(projectId); return(customFields.Result); }
// GetProjects public static ICollection <YouTrackSharp.Projects.Project> GetProjects(BearerTokenConnection connection) { var projects = connection.CreateProjectsService().GetAccessibleProjects(); return(projects.Result); }
public YouTrackLoader(string url, string token) { this.connection = new BearerTokenConnection(url, token); }
public YouTrackPoster(CustomSettings settings) { Settings = settings; Connection = new BearerTokenConnection(Settings.YouTrackUrl, Settings.YouTrackToken); }
private void DeleteWorkItemForIssue(BearerTokenConnection connection, string issueId, string workItemId) { var timeTrackingService = connection.CreateTimeTrackingService(); timeTrackingService.DeleteWorkItemForIssue(issueId, workItemId); }
private void UpdateWorkItemForIssue(BearerTokenConnection connection, string issueId, WorkItem workItem) { var timeTrackingService = connection.CreateTimeTrackingService(); timeTrackingService.UpdateWorkItemForIssue(issueId, workItem.Id, workItem); }