public RestJiraApi(IJiraApiSettings jiraApiSettings, LocalDirs localDirs, CancellationToken cancellationToken) { _jiraApiSettings = jiraApiSettings ?? throw new ArgumentNullException(nameof(jiraApiSettings)); _localDirs = localDirs ?? throw new ArgumentNullException(nameof(localDirs)); _cancellationToken = cancellationToken; _apiUrl = "/rest/api/2/"; _jiraClient = Atlassian.Jira.Jira.CreateRestClient(jiraApiSettings.JiraUrl, jiraApiSettings.JiraUsername, jiraApiSettings.JiraToken.Value); _restClient = _jiraClient.RestClient; }
public JiraApi(IOptions <JCredentials> credentials) { var cred = credentials; _jira = Atlassian.Jira.Jira.CreateRestClient( cred.Value.Url, cred.Value.UserName, cred.Value.Password ); }
// // Authenticates against the given Jira server // private static Result Authenticate(string server, string username, string password, Logging.Logging logger) { // Check we have the properties we need bool validServer = string.IsNullOrWhiteSpace(server) == false; bool validUser = string.IsNullOrWhiteSpace(username) == false; bool validPassword = string.IsNullOrWhiteSpace(password) == false; // If it's not valid, throw and we're done if (validServer == false || validUser == false || validPassword == false) { logger.Log("Invalid server, username or password requested"); throw new ArgumentException("Invalid server, username or password requested"); } // Create our rest client Atlassian.Jira.Jira jiraInstance = null; try { jiraInstance = Atlassian.Jira.Jira.CreateRestClient(server, username, password); } catch (Exception e) { string message = string.Format("Unable to generate Jira instance for user '{0}'\n\n{1}", username, e.InnerException.Message); logger.Log(message); throw new InvalidOperationException(message); } // Check we can access this user try { // Pull out the user Task <Atlassian.Jira.JiraUser> thisUser = jiraInstance.Users.GetUserAsync(username); thisUser.Wait(); // If we get here, the user exists and is fine } catch (Exception) { string message = string.Format("Unable to access Jira user '{0}'\n\nIf your username and password is correct, it is likely you have been locked out of your account.\n\nPlease visit {1} to unlock your account and then try again", username, server); logger.Log(message); throw new InvalidOperationException(message); } // Return the result return(new Result(true, "Successfully authenticated against the Jira server")); }
private static Atlassian.Jira.Jira GetJiraInstance(Simple credentials) { if (_jiraInstance != null) { return(_jiraInstance); } try { _jiraInstance = Atlassian.Jira.Jira.CreateRestClient(credentials.Server, credentials.User, credentials.Password); } catch (Exception e) { string message = string.Format("Unable to generate Jira instance for user '{0}'\n\n{1}", credentials.User, e.InnerException.Message); throw new InvalidOperationException(message); } return(_jiraInstance); }
public IEnumerable <OnlineIssue> GetClosedIssues(Context context, DateTimeOffset?since) { var jira = new Atlassian.Jira.Jira(context.Jira.JiraServer, context.Authentication.Username, context.Authentication.Password); var jql = context.Jira.Jql; if (string.IsNullOrEmpty(jql)) { jql = string.Format("project = {0}", context.ProjectId); var issueTypes = jira.GetIssueTypes(context.ProjectId); jql += string.Format(" AND issuetype in ({0})", string.Join(", ", issueTypes.Select(x => string.Format("\"{0}\"", x.Name)))); var issueStatuses = jira.GetIssueStatuses(); jql += string.Format(" AND status in ({0})", string.Join(", ", issueStatuses.Where(x => _knownIssueStatuses.Contains(x.Name.ToLower())).Select(x => string.Format("\"{0}\"", x.Name)))); } if (since.HasValue) { var sinceFormatted = since.Value.ToString("yyyy-MM-d HH:mm"); jql += string.Format(" AND updated > '{0}'", sinceFormatted).Replace("\"", "\\\""); } // Update back so every component is aware of the new jql context.Jira.Jql = jql; var issues = jira.GetIssuesFromJql(jql); foreach (var issue in issues) { var summary = issue.Summary; var id = issue.Key.Value; //var issueType = issue.Type.Name; yield return(new OnlineIssue(id, issue.GetResolutionDate().Value) { Title = summary, IssueType = IssueType.Issue, HtmlUrl = new Uri(new Uri(context.Jira.JiraServer), string.Format("browse/{0}", id)) }); } }
public IEnumerable<OnlineIssue> GetClosedIssues(Context context, DateTimeOffset? since) { var jira = new Atlassian.Jira.Jira(context.Jira.JiraServer, context.Authentication.Username, context.Authentication.Password); var jql = context.Jira.Jql; if (string.IsNullOrEmpty(jql)) { jql = string.Format("project = {0}", context.ProjectId); var issueTypes = jira.GetIssueTypes(context.ProjectId); jql += string.Format(" AND issuetype in ({0})", string.Join(", ", issueTypes.Select(x => string.Format("\"{0}\"", x.Name)))); var issueStatuses = jira.GetIssueStatuses(); jql += string.Format(" AND status in ({0})", string.Join(", ", issueStatuses.Where(x => _knownIssueStatuses.Contains(x.Name.ToLower())).Select(x => string.Format("\"{0}\"", x.Name)))); } if (since.HasValue) { var sinceFormatted = since.Value.ToString("yyyy-MM-d HH:mm"); jql += string.Format(" AND updated > '{0}'", sinceFormatted).Replace("\"", "\\\""); } // Update back so every component is aware of the new jql context.Jira.Jql = jql; var issues = jira.GetIssuesFromJql(jql); foreach (var issue in issues) { var summary = issue.Summary; var id = issue.Key.Value; //var issueType = issue.Type.Name; yield return new OnlineIssue(id, issue.GetResolutionDate().Value) { Title = summary, IssueType = IssueType.Issue, HtmlUrl = new Uri(new Uri(context.Jira.JiraServer), string.Format("browse/{0}", id)) }; } }
/// <summary> /// Posts a message to a set of given jira tickets as a comment /// </summary> /// <param name="credentials">Users jira credentials</param> /// <param name="message">Message to be posted as a comment</param> /// <param name="ticketId">Jira ticket ID to post comment on, can be multiple comma seperated ticket ids</param> /// <returns>bool indicating success of posting a comment.</returns> public async static Task <bool> PostMessageToJiraTicket(Simple credentials, string message, string ticketId) { Atlassian.Jira.Jira jiraInstance = GetJiraInstance(credentials); var tickets = ticketId.Split(',').Select(x => x.Trim()).ToArray(); foreach (var ticket in tickets) { try { var issueTask = await jiraInstance.Issues.GetIssueAsync(ticket); await issueTask.AddCommentAsync(message); } catch (Exception e) { string exceptionMessage = string.Format("Unable to post log message to jira ticket '{0}'\n\n{1}", ticket, e.InnerException.Message); throw new InvalidOperationException(exceptionMessage); } } return(true); }
// // Validates if a set of Jira tickets exists // where ticketId is a comma seperated list of jira tickets ids public async static Task <bool> ValidateJiraTicker(Simple credentials, string ticketId) { // Create our rest client Atlassian.Jira.Jira jiraInstance = GetJiraInstance(credentials); var tickets = ticketId.Split(',').Select(x => x.Trim()).ToArray(); foreach (var ticket in tickets) { try { var issueTask = await jiraInstance.Issues.GetIssueAsync(ticket); } catch (Exception e) { string message = string.Format("Unable to find Jira ticket '{0}'\n\n{1}", ticket, e.InnerException.Message); throw new InvalidOperationException(message); } } // We found it just fine return(true); }
public JiraRestApiIssueIdEnumerator(Atlassian.Jira.Jira jiraClient, CancellationToken cancellationToken) { _cancellationToken = cancellationToken; _jiraClient = jiraClient; }
async public Task <LoginState> Login(Profile profile) { profile.LoginInit(); //opens new connection jira = Jira.CreateRestClient(profile.Uri, profile.Username, profile.Password); jira.RestClient.RestSharpClient.Timeout = 3000; try { //tries to load projects var projects = await jira.Projects.GetProjectsAsync(); profile.Projects.Clear(); foreach (JiraProject project in projects) { var newProject = new Project(); newProject.Key = project.Key; newProject.Value = project.Name; profile.Projects.Add(project.Id, newProject); } //attempt to load statuses possible in the jira var statuses = await jira.Statuses.GetStatusesAsync(); profile.Statuses.Clear(); foreach (JiraStatus status in statuses) { var issueStatusItem = new Status(); issueStatusItem.Key = status.Name; issueStatusItem.Value = status.Name; profile.Statuses.Add(status.Id, issueStatusItem); } var types = await jira.IssueTypes.GetIssueTypesAsync(); profile.IssueTypes.Clear(); foreach (JiraIssueType issueType in types) { var issueTypeItem = new IssueType(); issueTypeItem.Key = issueType.Id; issueTypeItem.Value = issueType.Name; profile.IssueTypes.Add(issueType.Id, issueTypeItem); } } catch (AuthenticationException e) { AppState.Logger.Log(this, "Login,Auth", e.Message); return(LoginState.INVALID_CREDENTIALS); } catch (Exception e) { AppState.Logger.Log(this, "Login,Other", e.Message); return(LoginState.NETWORK_ERROR); } //store any updates to the profile AppState.Profiles.Save(); //mark the last selected profile in settings AppState.Settings.LastSelectedProfile = profile.GetId(); AppState.Settings.Save(); return(LoginState.SUCCESS); }
public IEnumerable <OnlineIssue> GetClosedIssues(IIssueTrackerContext context, DateTimeOffset?since) { var jiraContext = (JiraContext)context; Atlassian.Jira.Jira jira = null; if (!string.IsNullOrWhiteSpace(jiraContext.Token)) { Log.WriteLine("Using jira with authentication token"); jira = new Atlassian.Jira.Jira(jiraContext.Url, jiraContext.Token); } else if (!string.IsNullOrWhiteSpace(jiraContext.Username) && !string.IsNullOrWhiteSpace(jiraContext.Password)) { Log.WriteLine("Using jira with username and password"); jira = new Atlassian.Jira.Jira(jiraContext.Url, jiraContext.Username, jiraContext.Password); } else { Log.WriteLine("Using jira without authentication"); jira = new Atlassian.Jira.Jira(jiraContext.Url); } var jql = jiraContext.Jql; if (string.IsNullOrEmpty(jql)) { jql = string.Format("project = {0}", jiraContext.ProjectId); try { var issueTypes = jira.GetIssueTypes(jiraContext.ProjectId); jql += string.Format(" AND issuetype in ({0})", string.Join(", ", issueTypes.Select(x => string.Format("\"{0}\"", x.Name)))); } catch (Exception ex) { Log.WriteLine("Failed to retrieve issue types, defaulting to all issue types"); } try { var issueStatuses = jira.GetIssueStatuses(); jql += string.Format(" AND status in ({0})", string.Join(", ", issueStatuses.Where(x => _knownIssueStatuses.Contains(x.Name.ToLower())).Select(x => string.Format("\"{0}\"", x.Name)))); } catch (Exception ex) { Log.WriteLine("Failed to retrieve issue statuses, defaulting to issue statuses issue 'Closed'"); jql += " AND status in (Closed)"; } } if (since.HasValue) { var sinceFormatted = since.Value.ToString("yyyy-MM-d HH:mm"); jql += string.Format(" AND updated > '{0}'", sinceFormatted).Replace("\"", "\\\""); } // Update back so every component is aware of the new jql jiraContext.Jql = jql; var issues = jira.GetIssuesFromJql(jql, 200); foreach (var issue in issues) { var summary = issue.Summary; var id = issue.Key.Value; //var issueType = issue.Type.Name; var closedDate = issue.Created ?? DateTime.Today; try { closedDate = issue.GetResolutionDate() ?? DateTime.Today; } catch (Exception) { Log.WriteLine("Failed to retrieve the resolution date of '{0}', falling back to creation date", id); } yield return(new OnlineIssue(id, new DateTimeOffset(closedDate)) { Title = summary, IssueType = IssueType.Issue, HtmlUrl = new Uri(new Uri(jiraContext.Url), string.Format("browse/{0}", id)) }); } }