PageRenderTime 62ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/app/models/project_services/jira_service.rb

https://gitlab.com/certik/gitlab-ce
Ruby | 315 lines | 238 code | 60 blank | 17 comment | 24 complexity | 0e134ae09ad291c64d1fa51cfa74b127 MD5 | raw file
  1. class JiraService < IssueTrackerService
  2. include Gitlab::Routing
  3. validates :url, url: true, presence: true, if: :activated?
  4. validates :api_url, url: true, allow_blank: true
  5. prop_accessor :username, :password, :url, :api_url, :jira_issue_transition_id, :title, :description
  6. before_update :reset_password
  7. # This is confusing, but JiraService does not really support these events.
  8. # The values here are required to display correct options in the service
  9. # configuration screen.
  10. def self.supported_events
  11. %w(commit merge_request)
  12. end
  13. # {PROJECT-KEY}-{NUMBER} Examples: JIRA-1, PROJECT-1
  14. def self.reference_pattern(only_long: true)
  15. @reference_pattern ||= %r{(?<issue>\b([A-Z][A-Z0-9_]+-)\d+)}
  16. end
  17. def initialize_properties
  18. super do
  19. self.properties = {
  20. title: issues_tracker['title'],
  21. url: issues_tracker['url'],
  22. api_url: issues_tracker['api_url']
  23. }
  24. end
  25. end
  26. def reset_password
  27. self.password = nil if reset_password?
  28. end
  29. def options
  30. url = URI.parse(client_url)
  31. {
  32. username: self.username,
  33. password: self.password,
  34. site: URI.join(url, '/').to_s,
  35. context_path: url.path,
  36. auth_type: :basic,
  37. read_timeout: 120,
  38. use_ssl: url.scheme == 'https'
  39. }
  40. end
  41. def client
  42. @client ||= JIRA::Client.new(options)
  43. end
  44. def help
  45. "You need to configure JIRA before enabling this service. For more details
  46. read the
  47. [JIRA service documentation](#{help_page_url('user/project/integrations/jira')})."
  48. end
  49. def title
  50. if self.properties && self.properties['title'].present?
  51. self.properties['title']
  52. else
  53. 'JIRA'
  54. end
  55. end
  56. def description
  57. if self.properties && self.properties['description'].present?
  58. self.properties['description']
  59. else
  60. 'Jira issue tracker'
  61. end
  62. end
  63. def self.to_param
  64. 'jira'
  65. end
  66. def fields
  67. [
  68. { type: 'text', name: 'url', title: 'Web URL', placeholder: 'https://jira.example.com', required: true },
  69. { type: 'text', name: 'api_url', title: 'JIRA API URL', placeholder: 'If different from Web URL' },
  70. { type: 'text', name: 'username', placeholder: '', required: true },
  71. { type: 'password', name: 'password', placeholder: '', required: true },
  72. { type: 'text', name: 'jira_issue_transition_id', title: 'Transition ID', placeholder: '' }
  73. ]
  74. end
  75. def issues_url
  76. "#{url}/browse/:id"
  77. end
  78. def new_issue_url
  79. "#{url}/secure/CreateIssue.jspa"
  80. end
  81. def execute(push)
  82. # This method is a no-op, because currently JiraService does not
  83. # support any events.
  84. end
  85. def close_issue(entity, external_issue)
  86. issue = jira_request { client.Issue.find(external_issue.iid) }
  87. return if issue.nil? || has_resolution?(issue) || !jira_issue_transition_id.present?
  88. commit_id = if entity.is_a?(Commit)
  89. entity.id
  90. elsif entity.is_a?(MergeRequest)
  91. entity.diff_head_sha
  92. end
  93. commit_url = build_entity_url(:commit, commit_id)
  94. # Depending on the JIRA project's workflow, a comment during transition
  95. # may or may not be allowed. Refresh the issue after transition and check
  96. # if it is closed, so we don't have one comment for every commit.
  97. issue = jira_request { client.Issue.find(issue.key) } if transition_issue(issue)
  98. add_issue_solved_comment(issue, commit_id, commit_url) if has_resolution?(issue)
  99. end
  100. def create_cross_reference_note(mentioned, noteable, author)
  101. unless can_cross_reference?(noteable)
  102. return "Events for #{noteable.model_name.plural.humanize(capitalize: false)} are disabled."
  103. end
  104. jira_issue = jira_request { client.Issue.find(mentioned.id) }
  105. return unless jira_issue.present?
  106. noteable_id = noteable.respond_to?(:iid) ? noteable.iid : noteable.id
  107. noteable_type = noteable_name(noteable)
  108. entity_url = build_entity_url(noteable_type, noteable_id)
  109. data = {
  110. user: {
  111. name: author.name,
  112. url: resource_url(user_path(author))
  113. },
  114. project: {
  115. name: project.full_path,
  116. url: resource_url(namespace_project_path(project.namespace, project)) # rubocop:disable Cop/ProjectPathHelper
  117. },
  118. entity: {
  119. name: noteable_type.humanize.downcase,
  120. url: entity_url,
  121. title: noteable.title
  122. }
  123. }
  124. add_comment(data, jira_issue)
  125. end
  126. # reason why service cannot be tested
  127. def disabled_title
  128. "Please fill in Password and Username."
  129. end
  130. def test(_)
  131. result = test_settings
  132. success = result.present?
  133. result = @error if @error && !success
  134. { success: success, result: result }
  135. end
  136. # JIRA does not need test data.
  137. # We are requesting the project that belongs to the project key.
  138. def test_data(user = nil, project = nil)
  139. nil
  140. end
  141. def test_settings
  142. return unless client_url.present?
  143. # Test settings by getting the project
  144. jira_request { client.ServerInfo.all.attrs }
  145. end
  146. private
  147. def can_cross_reference?(noteable)
  148. case noteable
  149. when Commit then commit_events
  150. when MergeRequest then merge_requests_events
  151. else true
  152. end
  153. end
  154. def transition_issue(issue)
  155. issue.transitions.build.save(transition: { id: jira_issue_transition_id })
  156. end
  157. def add_issue_solved_comment(issue, commit_id, commit_url)
  158. link_title = "GitLab: Solved by commit #{commit_id}."
  159. comment = "Issue solved with [#{commit_id}|#{commit_url}]."
  160. link_props = build_remote_link_props(url: commit_url, title: link_title, resolved: true)
  161. send_message(issue, comment, link_props)
  162. end
  163. def add_comment(data, issue)
  164. user_name = data[:user][:name]
  165. user_url = data[:user][:url]
  166. entity_name = data[:entity][:name]
  167. entity_url = data[:entity][:url]
  168. entity_title = data[:entity][:title]
  169. project_name = data[:project][:name]
  170. message = "[#{user_name}|#{user_url}] mentioned this issue in [a #{entity_name} of #{project_name}|#{entity_url}]:\n'#{entity_title.chomp}'"
  171. link_title = "GitLab: Mentioned on #{entity_name} - #{entity_title}"
  172. link_props = build_remote_link_props(url: entity_url, title: link_title)
  173. unless comment_exists?(issue, message)
  174. send_message(issue, message, link_props)
  175. end
  176. end
  177. def has_resolution?(issue)
  178. issue.respond_to?(:resolution) && issue.resolution.present?
  179. end
  180. def comment_exists?(issue, message)
  181. comments = jira_request { issue.comments }
  182. comments.present? && comments.any? { |comment| comment.body.include?(message) }
  183. end
  184. def send_message(issue, message, remote_link_props)
  185. return unless client_url.present?
  186. jira_request do
  187. remote_link = find_remote_link(issue, remote_link_props[:object][:url])
  188. if remote_link
  189. remote_link.save!(remote_link_props)
  190. elsif issue.comments.build.save!(body: message)
  191. new_remote_link = issue.remotelink.build
  192. new_remote_link.save!(remote_link_props)
  193. end
  194. result_message = "#{self.class.name} SUCCESS: Successfully posted to #{client_url}."
  195. Rails.logger.info(result_message)
  196. result_message
  197. end
  198. end
  199. def find_remote_link(issue, url)
  200. links = jira_request { issue.remotelink.all }
  201. links.find { |link| link.object["url"] == url }
  202. end
  203. def build_remote_link_props(url:, title:, resolved: false)
  204. status = {
  205. resolved: resolved
  206. }
  207. {
  208. GlobalID: 'GitLab',
  209. object: {
  210. url: url,
  211. title: title,
  212. status: status,
  213. icon: { title: 'GitLab', url16x16: 'https://gitlab.com/favicon.ico' }
  214. }
  215. }
  216. end
  217. def resource_url(resource)
  218. "#{Settings.gitlab.base_url.chomp("/")}#{resource}"
  219. end
  220. def build_entity_url(noteable_type, entity_id)
  221. polymorphic_url(
  222. [
  223. self.project.namespace.becomes(Namespace),
  224. self.project,
  225. noteable_type.to_sym
  226. ],
  227. id: entity_id,
  228. host: Settings.gitlab.base_url
  229. )
  230. end
  231. def noteable_name(noteable)
  232. name = noteable.model_name.singular
  233. # ProjectSnippet inherits from Snippet class so it causes
  234. # routing error building the URL.
  235. name == "project_snippet" ? "snippet" : name
  236. end
  237. # Handle errors when doing JIRA API calls
  238. def jira_request
  239. yield
  240. rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, Errno::ECONNREFUSED, URI::InvalidURIError, JIRA::HTTPError, OpenSSL::SSL::SSLError => e
  241. @error = e.message
  242. Rails.logger.info "#{self.class.name} Send message ERROR: #{client_url} - #{@error}"
  243. nil
  244. end
  245. def client_url
  246. api_url.present? ? api_url : url
  247. end
  248. def reset_password?
  249. # don't reset the password if a new one is provided
  250. return false if password_touched?
  251. return true if api_url_changed?
  252. return false if api_url.present?
  253. url_changed?
  254. end
  255. end