You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

issue.go 38 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "fmt"
  7. "path"
  8. "sort"
  9. "strings"
  10. "code.gitea.io/gitea/modules/base"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/setting"
  13. "code.gitea.io/gitea/modules/util"
  14. api "code.gitea.io/sdk/gitea"
  15. "github.com/Unknwon/com"
  16. "github.com/go-xorm/builder"
  17. "github.com/go-xorm/xorm"
  18. )
  19. // Issue represents an issue or pull request of repository.
  20. type Issue struct {
  21. ID int64 `xorm:"pk autoincr"`
  22. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  23. Repo *Repository `xorm:"-"`
  24. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  25. PosterID int64 `xorm:"INDEX"`
  26. Poster *User `xorm:"-"`
  27. Title string `xorm:"name"`
  28. Content string `xorm:"TEXT"`
  29. RenderedContent string `xorm:"-"`
  30. Labels []*Label `xorm:"-"`
  31. MilestoneID int64 `xorm:"INDEX"`
  32. Milestone *Milestone `xorm:"-"`
  33. Priority int
  34. AssigneeID int64 `xorm:"INDEX"`
  35. Assignee *User `xorm:"-"`
  36. IsClosed bool `xorm:"INDEX"`
  37. IsRead bool `xorm:"-"`
  38. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  39. PullRequest *PullRequest `xorm:"-"`
  40. NumComments int
  41. Ref string
  42. DeadlineUnix util.TimeStamp `xorm:"INDEX"`
  43. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  44. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  45. Attachments []*Attachment `xorm:"-"`
  46. Comments []*Comment `xorm:"-"`
  47. Reactions ReactionList `xorm:"-"`
  48. }
  49. func (issue *Issue) loadRepo(e Engine) (err error) {
  50. if issue.Repo == nil {
  51. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  52. if err != nil {
  53. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  54. }
  55. }
  56. return nil
  57. }
  58. // GetPullRequest returns the issue pull request
  59. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  60. if !issue.IsPull {
  61. return nil, fmt.Errorf("Issue is not a pull request")
  62. }
  63. pr, err = getPullRequestByIssueID(x, issue.ID)
  64. return
  65. }
  66. func (issue *Issue) loadLabels(e Engine) (err error) {
  67. if issue.Labels == nil {
  68. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  69. if err != nil {
  70. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  71. }
  72. }
  73. return nil
  74. }
  75. func (issue *Issue) loadPoster(e Engine) (err error) {
  76. if issue.Poster == nil {
  77. issue.Poster, err = getUserByID(e, issue.PosterID)
  78. if err != nil {
  79. issue.PosterID = -1
  80. issue.Poster = NewGhostUser()
  81. if !IsErrUserNotExist(err) {
  82. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  83. }
  84. err = nil
  85. return
  86. }
  87. }
  88. return
  89. }
  90. func (issue *Issue) loadAssignee(e Engine) (err error) {
  91. if issue.Assignee == nil && issue.AssigneeID > 0 {
  92. issue.Assignee, err = getUserByID(e, issue.AssigneeID)
  93. if err != nil {
  94. issue.AssigneeID = -1
  95. issue.Assignee = NewGhostUser()
  96. if !IsErrUserNotExist(err) {
  97. return fmt.Errorf("getUserByID.(assignee) [%d]: %v", issue.AssigneeID, err)
  98. }
  99. err = nil
  100. return
  101. }
  102. }
  103. return
  104. }
  105. func (issue *Issue) loadPullRequest(e Engine) (err error) {
  106. if issue.IsPull && issue.PullRequest == nil {
  107. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  108. if err != nil {
  109. if IsErrPullRequestNotExist(err) {
  110. return err
  111. }
  112. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  113. }
  114. }
  115. return nil
  116. }
  117. func (issue *Issue) loadComments(e Engine) (err error) {
  118. if issue.Comments != nil {
  119. return nil
  120. }
  121. issue.Comments, err = findComments(e, FindCommentsOptions{
  122. IssueID: issue.ID,
  123. Type: CommentTypeUnknown,
  124. })
  125. return err
  126. }
  127. func (issue *Issue) loadReactions(e Engine) (err error) {
  128. if issue.Reactions != nil {
  129. return nil
  130. }
  131. reactions, err := findReactions(e, FindReactionsOptions{
  132. IssueID: issue.ID,
  133. })
  134. if err != nil {
  135. return err
  136. }
  137. // Load reaction user data
  138. if _, err := ReactionList(reactions).LoadUsers(); err != nil {
  139. return err
  140. }
  141. // Cache comments to map
  142. comments := make(map[int64]*Comment)
  143. for _, comment := range issue.Comments {
  144. comments[comment.ID] = comment
  145. }
  146. // Add reactions either to issue or comment
  147. for _, react := range reactions {
  148. if react.CommentID == 0 {
  149. issue.Reactions = append(issue.Reactions, react)
  150. } else if comment, ok := comments[react.CommentID]; ok {
  151. comment.Reactions = append(comment.Reactions, react)
  152. }
  153. }
  154. return nil
  155. }
  156. func (issue *Issue) loadAttributes(e Engine) (err error) {
  157. if err = issue.loadRepo(e); err != nil {
  158. return
  159. }
  160. if err = issue.loadPoster(e); err != nil {
  161. return
  162. }
  163. if err = issue.loadLabels(e); err != nil {
  164. return
  165. }
  166. if issue.Milestone == nil && issue.MilestoneID > 0 {
  167. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  168. if err != nil && !IsErrMilestoneNotExist(err) {
  169. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  170. }
  171. }
  172. if err = issue.loadAssignee(e); err != nil {
  173. return
  174. }
  175. if err = issue.loadPullRequest(e); err != nil && !IsErrPullRequestNotExist(err) {
  176. // It is possible pull request is not yet created.
  177. return err
  178. }
  179. if issue.Attachments == nil {
  180. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  181. if err != nil {
  182. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  183. }
  184. }
  185. if err = issue.loadComments(e); err != nil {
  186. return err
  187. }
  188. return issue.loadReactions(e)
  189. }
  190. // LoadAttributes loads the attribute of this issue.
  191. func (issue *Issue) LoadAttributes() error {
  192. return issue.loadAttributes(x)
  193. }
  194. // GetIsRead load the `IsRead` field of the issue
  195. func (issue *Issue) GetIsRead(userID int64) error {
  196. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  197. if has, err := x.Get(issueUser); err != nil {
  198. return err
  199. } else if !has {
  200. issue.IsRead = false
  201. return nil
  202. }
  203. issue.IsRead = issueUser.IsRead
  204. return nil
  205. }
  206. // APIURL returns the absolute APIURL to this issue.
  207. func (issue *Issue) APIURL() string {
  208. return issue.Repo.APIURL() + "/" + path.Join("issues", fmt.Sprint(issue.ID))
  209. }
  210. // HTMLURL returns the absolute URL to this issue.
  211. func (issue *Issue) HTMLURL() string {
  212. var path string
  213. if issue.IsPull {
  214. path = "pulls"
  215. } else {
  216. path = "issues"
  217. }
  218. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  219. }
  220. // DiffURL returns the absolute URL to this diff
  221. func (issue *Issue) DiffURL() string {
  222. if issue.IsPull {
  223. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  224. }
  225. return ""
  226. }
  227. // PatchURL returns the absolute URL to this patch
  228. func (issue *Issue) PatchURL() string {
  229. if issue.IsPull {
  230. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  231. }
  232. return ""
  233. }
  234. // State returns string representation of issue status.
  235. func (issue *Issue) State() api.StateType {
  236. if issue.IsClosed {
  237. return api.StateClosed
  238. }
  239. return api.StateOpen
  240. }
  241. // APIFormat assumes some fields assigned with values:
  242. // Required - Poster, Labels,
  243. // Optional - Milestone, Assignee, PullRequest
  244. func (issue *Issue) APIFormat() *api.Issue {
  245. apiLabels := make([]*api.Label, len(issue.Labels))
  246. for i := range issue.Labels {
  247. apiLabels[i] = issue.Labels[i].APIFormat()
  248. }
  249. apiIssue := &api.Issue{
  250. ID: issue.ID,
  251. URL: issue.APIURL(),
  252. Index: issue.Index,
  253. Poster: issue.Poster.APIFormat(),
  254. Title: issue.Title,
  255. Body: issue.Content,
  256. Labels: apiLabels,
  257. State: issue.State(),
  258. Comments: issue.NumComments,
  259. Created: issue.CreatedUnix.AsTime(),
  260. Updated: issue.UpdatedUnix.AsTime(),
  261. }
  262. if issue.Milestone != nil {
  263. apiIssue.Milestone = issue.Milestone.APIFormat()
  264. }
  265. if issue.Assignee != nil {
  266. apiIssue.Assignee = issue.Assignee.APIFormat()
  267. }
  268. if issue.IsPull {
  269. apiIssue.PullRequest = &api.PullRequestMeta{
  270. HasMerged: issue.PullRequest.HasMerged,
  271. }
  272. if issue.PullRequest.HasMerged {
  273. apiIssue.PullRequest.Merged = issue.PullRequest.MergedUnix.AsTimePtr()
  274. }
  275. }
  276. return apiIssue
  277. }
  278. // HashTag returns unique hash tag for issue.
  279. func (issue *Issue) HashTag() string {
  280. return "issue-" + com.ToStr(issue.ID)
  281. }
  282. // IsPoster returns true if given user by ID is the poster.
  283. func (issue *Issue) IsPoster(uid int64) bool {
  284. return issue.PosterID == uid
  285. }
  286. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  287. return hasIssueLabel(e, issue.ID, labelID)
  288. }
  289. // HasLabel returns true if issue has been labeled by given ID.
  290. func (issue *Issue) HasLabel(labelID int64) bool {
  291. return issue.hasLabel(x, labelID)
  292. }
  293. func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
  294. var err error
  295. if issue.IsPull {
  296. if err = issue.loadRepo(x); err != nil {
  297. log.Error(4, "loadRepo: %v", err)
  298. return
  299. }
  300. if err = issue.loadPullRequest(x); err != nil {
  301. log.Error(4, "loadPullRequest: %v", err)
  302. return
  303. }
  304. if err = issue.PullRequest.LoadIssue(); err != nil {
  305. log.Error(4, "LoadIssue: %v", err)
  306. return
  307. }
  308. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  309. Action: api.HookIssueLabelUpdated,
  310. Index: issue.Index,
  311. PullRequest: issue.PullRequest.APIFormat(),
  312. Repository: issue.Repo.APIFormat(AccessModeNone),
  313. Sender: doer.APIFormat(),
  314. })
  315. }
  316. if err != nil {
  317. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  318. } else {
  319. go HookQueue.Add(issue.RepoID)
  320. }
  321. }
  322. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  323. return newIssueLabel(e, issue, label, doer)
  324. }
  325. // AddLabel adds a new label to the issue.
  326. func (issue *Issue) AddLabel(doer *User, label *Label) error {
  327. if err := NewIssueLabel(issue, label, doer); err != nil {
  328. return err
  329. }
  330. issue.sendLabelUpdatedWebhook(doer)
  331. return nil
  332. }
  333. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  334. return newIssueLabels(e, issue, labels, doer)
  335. }
  336. // AddLabels adds a list of new labels to the issue.
  337. func (issue *Issue) AddLabels(doer *User, labels []*Label) error {
  338. if err := NewIssueLabels(issue, labels, doer); err != nil {
  339. return err
  340. }
  341. issue.sendLabelUpdatedWebhook(doer)
  342. return nil
  343. }
  344. func (issue *Issue) getLabels(e Engine) (err error) {
  345. if len(issue.Labels) > 0 {
  346. return nil
  347. }
  348. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  349. if err != nil {
  350. return fmt.Errorf("getLabelsByIssueID: %v", err)
  351. }
  352. return nil
  353. }
  354. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  355. return deleteIssueLabel(e, issue, label, doer)
  356. }
  357. // RemoveLabel removes a label from issue by given ID.
  358. func (issue *Issue) RemoveLabel(doer *User, label *Label) error {
  359. if err := issue.loadRepo(x); err != nil {
  360. return err
  361. }
  362. if has, err := HasAccess(doer.ID, issue.Repo, AccessModeWrite); err != nil {
  363. return err
  364. } else if !has {
  365. return ErrLabelNotExist{}
  366. }
  367. if err := DeleteIssueLabel(issue, label, doer); err != nil {
  368. return err
  369. }
  370. issue.sendLabelUpdatedWebhook(doer)
  371. return nil
  372. }
  373. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  374. if err = issue.getLabels(e); err != nil {
  375. return fmt.Errorf("getLabels: %v", err)
  376. }
  377. for i := range issue.Labels {
  378. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  379. return fmt.Errorf("removeLabel: %v", err)
  380. }
  381. }
  382. return nil
  383. }
  384. // ClearLabels removes all issue labels as the given user.
  385. // Triggers appropriate WebHooks, if any.
  386. func (issue *Issue) ClearLabels(doer *User) (err error) {
  387. sess := x.NewSession()
  388. defer sess.Close()
  389. if err = sess.Begin(); err != nil {
  390. return err
  391. }
  392. if err := issue.loadRepo(sess); err != nil {
  393. return err
  394. } else if err = issue.loadPullRequest(sess); err != nil {
  395. return err
  396. }
  397. if has, err := hasAccess(sess, doer.ID, issue.Repo, AccessModeWrite); err != nil {
  398. return err
  399. } else if !has {
  400. return ErrLabelNotExist{}
  401. }
  402. if err = issue.clearLabels(sess, doer); err != nil {
  403. return err
  404. }
  405. if err = sess.Commit(); err != nil {
  406. return fmt.Errorf("Commit: %v", err)
  407. }
  408. if issue.IsPull {
  409. err = issue.PullRequest.LoadIssue()
  410. if err != nil {
  411. log.Error(4, "LoadIssue: %v", err)
  412. return
  413. }
  414. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  415. Action: api.HookIssueLabelCleared,
  416. Index: issue.Index,
  417. PullRequest: issue.PullRequest.APIFormat(),
  418. Repository: issue.Repo.APIFormat(AccessModeNone),
  419. Sender: doer.APIFormat(),
  420. })
  421. }
  422. if err != nil {
  423. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  424. } else {
  425. go HookQueue.Add(issue.RepoID)
  426. }
  427. return nil
  428. }
  429. type labelSorter []*Label
  430. func (ts labelSorter) Len() int {
  431. return len([]*Label(ts))
  432. }
  433. func (ts labelSorter) Less(i, j int) bool {
  434. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  435. }
  436. func (ts labelSorter) Swap(i, j int) {
  437. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  438. }
  439. // ReplaceLabels removes all current labels and add new labels to the issue.
  440. // Triggers appropriate WebHooks, if any.
  441. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  442. sess := x.NewSession()
  443. defer sess.Close()
  444. if err = sess.Begin(); err != nil {
  445. return err
  446. }
  447. if err = issue.loadLabels(sess); err != nil {
  448. return err
  449. }
  450. sort.Sort(labelSorter(labels))
  451. sort.Sort(labelSorter(issue.Labels))
  452. var toAdd, toRemove []*Label
  453. addIndex, removeIndex := 0, 0
  454. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  455. addLabel := labels[addIndex]
  456. removeLabel := issue.Labels[removeIndex]
  457. if addLabel.ID == removeLabel.ID {
  458. addIndex++
  459. removeIndex++
  460. } else if addLabel.ID < removeLabel.ID {
  461. toAdd = append(toAdd, addLabel)
  462. addIndex++
  463. } else {
  464. toRemove = append(toRemove, removeLabel)
  465. removeIndex++
  466. }
  467. }
  468. toAdd = append(toAdd, labels[addIndex:]...)
  469. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  470. if len(toAdd) > 0 {
  471. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  472. return fmt.Errorf("addLabels: %v", err)
  473. }
  474. }
  475. for _, l := range toRemove {
  476. if err = issue.removeLabel(sess, doer, l); err != nil {
  477. return fmt.Errorf("removeLabel: %v", err)
  478. }
  479. }
  480. return sess.Commit()
  481. }
  482. // GetAssignee sets the Assignee attribute of this issue.
  483. func (issue *Issue) GetAssignee() (err error) {
  484. if issue.AssigneeID == 0 || issue.Assignee != nil {
  485. return nil
  486. }
  487. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  488. if IsErrUserNotExist(err) {
  489. return nil
  490. }
  491. return err
  492. }
  493. // ReadBy sets issue to be read by given user.
  494. func (issue *Issue) ReadBy(userID int64) error {
  495. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  496. return err
  497. }
  498. return setNotificationStatusReadIfUnread(x, userID, issue.ID)
  499. }
  500. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  501. if _, err := e.ID(issue.ID).Cols(cols...).Update(issue); err != nil {
  502. return err
  503. }
  504. UpdateIssueIndexerCols(issue.ID, cols...)
  505. return nil
  506. }
  507. // UpdateIssueCols only updates values of specific columns for given issue.
  508. func UpdateIssueCols(issue *Issue, cols ...string) error {
  509. return updateIssueCols(x, issue, cols...)
  510. }
  511. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
  512. // Nothing should be performed if current status is same as target status
  513. if issue.IsClosed == isClosed {
  514. return nil
  515. }
  516. issue.IsClosed = isClosed
  517. if err = updateIssueCols(e, issue, "is_closed"); err != nil {
  518. return err
  519. }
  520. // Update issue count of labels
  521. if err = issue.getLabels(e); err != nil {
  522. return err
  523. }
  524. for idx := range issue.Labels {
  525. if issue.IsClosed {
  526. issue.Labels[idx].NumClosedIssues++
  527. } else {
  528. issue.Labels[idx].NumClosedIssues--
  529. }
  530. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  531. return err
  532. }
  533. }
  534. // Update issue count of milestone
  535. if err = changeMilestoneIssueStats(e, issue); err != nil {
  536. return err
  537. }
  538. // New action comment
  539. if _, err = createStatusComment(e, doer, repo, issue); err != nil {
  540. return err
  541. }
  542. return nil
  543. }
  544. // ChangeStatus changes issue status to open or closed.
  545. func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (err error) {
  546. sess := x.NewSession()
  547. defer sess.Close()
  548. if err = sess.Begin(); err != nil {
  549. return err
  550. }
  551. if err = issue.changeStatus(sess, doer, repo, isClosed); err != nil {
  552. return err
  553. }
  554. if err = sess.Commit(); err != nil {
  555. return fmt.Errorf("Commit: %v", err)
  556. }
  557. if issue.IsPull {
  558. // Merge pull request calls issue.changeStatus so we need to handle separately.
  559. issue.PullRequest.Issue = issue
  560. apiPullRequest := &api.PullRequestPayload{
  561. Index: issue.Index,
  562. PullRequest: issue.PullRequest.APIFormat(),
  563. Repository: repo.APIFormat(AccessModeNone),
  564. Sender: doer.APIFormat(),
  565. }
  566. if isClosed {
  567. apiPullRequest.Action = api.HookIssueClosed
  568. } else {
  569. apiPullRequest.Action = api.HookIssueReOpened
  570. }
  571. err = PrepareWebhooks(repo, HookEventPullRequest, apiPullRequest)
  572. }
  573. if err != nil {
  574. log.Error(4, "PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  575. } else {
  576. go HookQueue.Add(repo.ID)
  577. }
  578. return nil
  579. }
  580. // ChangeTitle changes the title of this issue, as the given user.
  581. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
  582. oldTitle := issue.Title
  583. issue.Title = title
  584. sess := x.NewSession()
  585. defer sess.Close()
  586. if err = sess.Begin(); err != nil {
  587. return err
  588. }
  589. if err = updateIssueCols(sess, issue, "name"); err != nil {
  590. return fmt.Errorf("updateIssueCols: %v", err)
  591. }
  592. if _, err = createChangeTitleComment(sess, doer, issue.Repo, issue, oldTitle, title); err != nil {
  593. return fmt.Errorf("createChangeTitleComment: %v", err)
  594. }
  595. if err = sess.Commit(); err != nil {
  596. return err
  597. }
  598. if issue.IsPull {
  599. issue.PullRequest.Issue = issue
  600. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  601. Action: api.HookIssueEdited,
  602. Index: issue.Index,
  603. Changes: &api.ChangesPayload{
  604. Title: &api.ChangesFromPayload{
  605. From: oldTitle,
  606. },
  607. },
  608. PullRequest: issue.PullRequest.APIFormat(),
  609. Repository: issue.Repo.APIFormat(AccessModeNone),
  610. Sender: doer.APIFormat(),
  611. })
  612. }
  613. if err != nil {
  614. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  615. } else {
  616. go HookQueue.Add(issue.RepoID)
  617. }
  618. return nil
  619. }
  620. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  621. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  622. issue, err := getIssueByID(x, issueID)
  623. if err != nil {
  624. return err
  625. }
  626. sess := x.NewSession()
  627. defer sess.Close()
  628. if err := sess.Begin(); err != nil {
  629. return err
  630. }
  631. if _, err := createDeleteBranchComment(sess, doer, repo, issue, branchName); err != nil {
  632. return err
  633. }
  634. return sess.Commit()
  635. }
  636. // ChangeContent changes issue content, as the given user.
  637. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  638. oldContent := issue.Content
  639. issue.Content = content
  640. if err = UpdateIssueCols(issue, "content"); err != nil {
  641. return fmt.Errorf("UpdateIssueCols: %v", err)
  642. }
  643. if issue.IsPull {
  644. issue.PullRequest.Issue = issue
  645. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  646. Action: api.HookIssueEdited,
  647. Index: issue.Index,
  648. Changes: &api.ChangesPayload{
  649. Body: &api.ChangesFromPayload{
  650. From: oldContent,
  651. },
  652. },
  653. PullRequest: issue.PullRequest.APIFormat(),
  654. Repository: issue.Repo.APIFormat(AccessModeNone),
  655. Sender: doer.APIFormat(),
  656. })
  657. }
  658. if err != nil {
  659. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  660. } else {
  661. go HookQueue.Add(issue.RepoID)
  662. }
  663. return nil
  664. }
  665. // ChangeAssignee changes the Assignee field of this issue.
  666. func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
  667. var oldAssigneeID = issue.AssigneeID
  668. issue.AssigneeID = assigneeID
  669. if err = UpdateIssueUserByAssignee(issue); err != nil {
  670. return fmt.Errorf("UpdateIssueUserByAssignee: %v", err)
  671. }
  672. sess := x.NewSession()
  673. defer sess.Close()
  674. if err = issue.loadRepo(sess); err != nil {
  675. return fmt.Errorf("loadRepo: %v", err)
  676. }
  677. if _, err = createAssigneeComment(sess, doer, issue.Repo, issue, oldAssigneeID, assigneeID); err != nil {
  678. return fmt.Errorf("createAssigneeComment: %v", err)
  679. }
  680. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  681. if err != nil && !IsErrUserNotExist(err) {
  682. log.Error(4, "GetUserByID [assignee_id: %v]: %v", issue.AssigneeID, err)
  683. return nil
  684. }
  685. // Error not nil here means user does not exist, which is remove assignee.
  686. isRemoveAssignee := err != nil
  687. if issue.IsPull {
  688. issue.PullRequest.Issue = issue
  689. apiPullRequest := &api.PullRequestPayload{
  690. Index: issue.Index,
  691. PullRequest: issue.PullRequest.APIFormat(),
  692. Repository: issue.Repo.APIFormat(AccessModeNone),
  693. Sender: doer.APIFormat(),
  694. }
  695. if isRemoveAssignee {
  696. apiPullRequest.Action = api.HookIssueUnassigned
  697. } else {
  698. apiPullRequest.Action = api.HookIssueAssigned
  699. }
  700. if err := PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest); err != nil {
  701. log.Error(4, "PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err)
  702. return nil
  703. }
  704. }
  705. go HookQueue.Add(issue.RepoID)
  706. return nil
  707. }
  708. // NewIssueOptions represents the options of a new issue.
  709. type NewIssueOptions struct {
  710. Repo *Repository
  711. Issue *Issue
  712. LabelIDs []int64
  713. Attachments []string // In UUID format.
  714. IsPull bool
  715. }
  716. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  717. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  718. opts.Issue.Index = opts.Repo.NextIssueIndex()
  719. if opts.Issue.MilestoneID > 0 {
  720. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  721. if err != nil && !IsErrMilestoneNotExist(err) {
  722. return fmt.Errorf("getMilestoneByID: %v", err)
  723. }
  724. // Assume milestone is invalid and drop silently.
  725. opts.Issue.MilestoneID = 0
  726. if milestone != nil {
  727. opts.Issue.MilestoneID = milestone.ID
  728. opts.Issue.Milestone = milestone
  729. }
  730. }
  731. if assigneeID := opts.Issue.AssigneeID; assigneeID > 0 {
  732. valid, err := hasAccess(e, assigneeID, opts.Repo, AccessModeWrite)
  733. if err != nil {
  734. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  735. }
  736. if !valid {
  737. opts.Issue.AssigneeID = 0
  738. opts.Issue.Assignee = nil
  739. }
  740. }
  741. // Milestone and assignee validation should happen before insert actual object.
  742. if _, err = e.Insert(opts.Issue); err != nil {
  743. return err
  744. }
  745. if opts.Issue.MilestoneID > 0 {
  746. if err = changeMilestoneAssign(e, doer, opts.Issue, -1); err != nil {
  747. return err
  748. }
  749. }
  750. if opts.Issue.AssigneeID > 0 {
  751. if err = opts.Issue.loadRepo(e); err != nil {
  752. return err
  753. }
  754. if _, err = createAssigneeComment(e, doer, opts.Issue.Repo, opts.Issue, -1, opts.Issue.AssigneeID); err != nil {
  755. return err
  756. }
  757. }
  758. if opts.IsPull {
  759. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  760. } else {
  761. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  762. }
  763. if err != nil {
  764. return err
  765. }
  766. if len(opts.LabelIDs) > 0 {
  767. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  768. // So we have to get all needed labels first.
  769. labels := make([]*Label, 0, len(opts.LabelIDs))
  770. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  771. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  772. }
  773. if err = opts.Issue.loadPoster(e); err != nil {
  774. return err
  775. }
  776. for _, label := range labels {
  777. // Silently drop invalid labels.
  778. if label.RepoID != opts.Repo.ID {
  779. continue
  780. }
  781. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  782. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  783. }
  784. }
  785. }
  786. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  787. return err
  788. }
  789. if len(opts.Attachments) > 0 {
  790. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  791. if err != nil {
  792. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  793. }
  794. for i := 0; i < len(attachments); i++ {
  795. attachments[i].IssueID = opts.Issue.ID
  796. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  797. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  798. }
  799. }
  800. }
  801. return opts.Issue.loadAttributes(e)
  802. }
  803. // NewIssue creates new issue with labels for repository.
  804. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  805. sess := x.NewSession()
  806. defer sess.Close()
  807. if err = sess.Begin(); err != nil {
  808. return err
  809. }
  810. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  811. Repo: repo,
  812. Issue: issue,
  813. LabelIDs: labelIDs,
  814. Attachments: uuids,
  815. }); err != nil {
  816. return fmt.Errorf("newIssue: %v", err)
  817. }
  818. if err = sess.Commit(); err != nil {
  819. return fmt.Errorf("Commit: %v", err)
  820. }
  821. UpdateIssueIndexer(issue.ID)
  822. if err = NotifyWatchers(&Action{
  823. ActUserID: issue.Poster.ID,
  824. ActUser: issue.Poster,
  825. OpType: ActionCreateIssue,
  826. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  827. RepoID: repo.ID,
  828. Repo: repo,
  829. IsPrivate: repo.IsPrivate,
  830. }); err != nil {
  831. log.Error(4, "NotifyWatchers: %v", err)
  832. }
  833. if err = issue.MailParticipants(); err != nil {
  834. log.Error(4, "MailParticipants: %v", err)
  835. }
  836. return nil
  837. }
  838. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  839. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  840. issue := &Issue{
  841. RepoID: repoID,
  842. Index: index,
  843. }
  844. has, err := x.Get(issue)
  845. if err != nil {
  846. return nil, err
  847. } else if !has {
  848. return nil, ErrIssueNotExist{0, repoID, index}
  849. }
  850. return issue, nil
  851. }
  852. // GetIssueByIndex returns issue by index in a repository.
  853. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  854. issue, err := GetRawIssueByIndex(repoID, index)
  855. if err != nil {
  856. return nil, err
  857. }
  858. return issue, issue.LoadAttributes()
  859. }
  860. func getIssueByID(e Engine, id int64) (*Issue, error) {
  861. issue := new(Issue)
  862. has, err := e.ID(id).Get(issue)
  863. if err != nil {
  864. return nil, err
  865. } else if !has {
  866. return nil, ErrIssueNotExist{id, 0, 0}
  867. }
  868. return issue, issue.loadAttributes(e)
  869. }
  870. // GetIssueByID returns an issue by given ID.
  871. func GetIssueByID(id int64) (*Issue, error) {
  872. return getIssueByID(x, id)
  873. }
  874. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  875. issues := make([]*Issue, 0, 10)
  876. return issues, e.In("id", issueIDs).Find(&issues)
  877. }
  878. // GetIssuesByIDs return issues with the given IDs.
  879. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  880. return getIssuesByIDs(x, issueIDs)
  881. }
  882. // IssuesOptions represents options of an issue.
  883. type IssuesOptions struct {
  884. RepoIDs []int64 // include all repos if empty
  885. AssigneeID int64
  886. PosterID int64
  887. MentionedID int64
  888. MilestoneID int64
  889. Page int
  890. PageSize int
  891. IsClosed util.OptionalBool
  892. IsPull util.OptionalBool
  893. Labels string
  894. SortType string
  895. IssueIDs []int64
  896. }
  897. // sortIssuesSession sort an issues-related session based on the provided
  898. // sortType string
  899. func sortIssuesSession(sess *xorm.Session, sortType string) {
  900. switch sortType {
  901. case "oldest":
  902. sess.Asc("issue.created_unix")
  903. case "recentupdate":
  904. sess.Desc("issue.updated_unix")
  905. case "leastupdate":
  906. sess.Asc("issue.updated_unix")
  907. case "mostcomment":
  908. sess.Desc("issue.num_comments")
  909. case "leastcomment":
  910. sess.Asc("issue.num_comments")
  911. case "priority":
  912. sess.Desc("issue.priority")
  913. default:
  914. sess.Desc("issue.created_unix")
  915. }
  916. }
  917. func (opts *IssuesOptions) setupSession(sess *xorm.Session) error {
  918. if opts.Page >= 0 && opts.PageSize > 0 {
  919. var start int
  920. if opts.Page == 0 {
  921. start = 0
  922. } else {
  923. start = (opts.Page - 1) * opts.PageSize
  924. }
  925. sess.Limit(opts.PageSize, start)
  926. }
  927. if len(opts.IssueIDs) > 0 {
  928. sess.In("issue.id", opts.IssueIDs)
  929. }
  930. if len(opts.RepoIDs) > 0 {
  931. // In case repository IDs are provided but actually no repository has issue.
  932. sess.In("issue.repo_id", opts.RepoIDs)
  933. }
  934. switch opts.IsClosed {
  935. case util.OptionalBoolTrue:
  936. sess.And("issue.is_closed=?", true)
  937. case util.OptionalBoolFalse:
  938. sess.And("issue.is_closed=?", false)
  939. }
  940. if opts.AssigneeID > 0 {
  941. sess.And("issue.assignee_id=?", opts.AssigneeID)
  942. }
  943. if opts.PosterID > 0 {
  944. sess.And("issue.poster_id=?", opts.PosterID)
  945. }
  946. if opts.MentionedID > 0 {
  947. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  948. And("issue_user.is_mentioned = ?", true).
  949. And("issue_user.uid = ?", opts.MentionedID)
  950. }
  951. if opts.MilestoneID > 0 {
  952. sess.And("issue.milestone_id=?", opts.MilestoneID)
  953. }
  954. switch opts.IsPull {
  955. case util.OptionalBoolTrue:
  956. sess.And("issue.is_pull=?", true)
  957. case util.OptionalBoolFalse:
  958. sess.And("issue.is_pull=?", false)
  959. }
  960. if len(opts.Labels) > 0 && opts.Labels != "0" {
  961. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  962. if err != nil {
  963. return err
  964. }
  965. if len(labelIDs) > 0 {
  966. sess.
  967. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  968. In("issue_label.label_id", labelIDs)
  969. }
  970. }
  971. return nil
  972. }
  973. // CountIssuesByRepo map from repoID to number of issues matching the options
  974. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  975. sess := x.NewSession()
  976. defer sess.Close()
  977. if err := opts.setupSession(sess); err != nil {
  978. return nil, err
  979. }
  980. countsSlice := make([]*struct {
  981. RepoID int64
  982. Count int64
  983. }, 0, 10)
  984. if err := sess.GroupBy("issue.repo_id").
  985. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  986. Table("issue").
  987. Find(&countsSlice); err != nil {
  988. return nil, err
  989. }
  990. countMap := make(map[int64]int64, len(countsSlice))
  991. for _, c := range countsSlice {
  992. countMap[c.RepoID] = c.Count
  993. }
  994. return countMap, nil
  995. }
  996. // Issues returns a list of issues by given conditions.
  997. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  998. sess := x.NewSession()
  999. defer sess.Close()
  1000. if err := opts.setupSession(sess); err != nil {
  1001. return nil, err
  1002. }
  1003. sortIssuesSession(sess, opts.SortType)
  1004. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1005. if err := sess.Find(&issues); err != nil {
  1006. return nil, fmt.Errorf("Find: %v", err)
  1007. }
  1008. if err := IssueList(issues).LoadAttributes(); err != nil {
  1009. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1010. }
  1011. return issues, nil
  1012. }
  1013. // GetParticipantsByIssueID returns all users who are participated in comments of an issue.
  1014. func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
  1015. return getParticipantsByIssueID(x, issueID)
  1016. }
  1017. func getParticipantsByIssueID(e Engine, issueID int64) ([]*User, error) {
  1018. userIDs := make([]int64, 0, 5)
  1019. if err := e.Table("comment").Cols("poster_id").
  1020. Where("`comment`.issue_id = ?", issueID).
  1021. And("`comment`.type = ?", CommentTypeComment).
  1022. And("`user`.is_active = ?", true).
  1023. And("`user`.prohibit_login = ?", false).
  1024. Join("INNER", "user", "`user`.id = `comment`.poster_id").
  1025. Distinct("poster_id").
  1026. Find(&userIDs); err != nil {
  1027. return nil, fmt.Errorf("get poster IDs: %v", err)
  1028. }
  1029. if len(userIDs) == 0 {
  1030. return nil, nil
  1031. }
  1032. users := make([]*User, 0, len(userIDs))
  1033. return users, e.In("id", userIDs).Find(&users)
  1034. }
  1035. // UpdateIssueMentions extracts mentioned people from content and
  1036. // updates issue-user relations for them.
  1037. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  1038. if len(mentions) == 0 {
  1039. return nil
  1040. }
  1041. for i := range mentions {
  1042. mentions[i] = strings.ToLower(mentions[i])
  1043. }
  1044. users := make([]*User, 0, len(mentions))
  1045. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  1046. return fmt.Errorf("find mentioned users: %v", err)
  1047. }
  1048. ids := make([]int64, 0, len(mentions))
  1049. for _, user := range users {
  1050. ids = append(ids, user.ID)
  1051. if !user.IsOrganization() || user.NumMembers == 0 {
  1052. continue
  1053. }
  1054. memberIDs := make([]int64, 0, user.NumMembers)
  1055. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  1056. if err != nil {
  1057. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  1058. }
  1059. for _, orgUser := range orgUsers {
  1060. memberIDs = append(memberIDs, orgUser.ID)
  1061. }
  1062. ids = append(ids, memberIDs...)
  1063. }
  1064. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  1065. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1066. }
  1067. return nil
  1068. }
  1069. // IssueStats represents issue statistic information.
  1070. type IssueStats struct {
  1071. OpenCount, ClosedCount int64
  1072. YourRepositoriesCount int64
  1073. AssignCount int64
  1074. CreateCount int64
  1075. MentionCount int64
  1076. }
  1077. // Filter modes.
  1078. const (
  1079. FilterModeAll = iota
  1080. FilterModeAssign
  1081. FilterModeCreate
  1082. FilterModeMention
  1083. )
  1084. func parseCountResult(results []map[string][]byte) int64 {
  1085. if len(results) == 0 {
  1086. return 0
  1087. }
  1088. for _, result := range results[0] {
  1089. return com.StrTo(string(result)).MustInt64()
  1090. }
  1091. return 0
  1092. }
  1093. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1094. type IssueStatsOptions struct {
  1095. RepoID int64
  1096. Labels string
  1097. MilestoneID int64
  1098. AssigneeID int64
  1099. MentionedID int64
  1100. PosterID int64
  1101. IsPull bool
  1102. IssueIDs []int64
  1103. }
  1104. // GetIssueStats returns issue statistic information by given conditions.
  1105. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1106. stats := &IssueStats{}
  1107. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1108. sess := x.
  1109. Where("issue.repo_id = ?", opts.RepoID).
  1110. And("issue.is_pull = ?", opts.IsPull)
  1111. if len(opts.IssueIDs) > 0 {
  1112. sess.In("issue.id", opts.IssueIDs)
  1113. }
  1114. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1115. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1116. if err != nil {
  1117. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1118. } else if len(labelIDs) > 0 {
  1119. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  1120. In("issue_label.label_id", labelIDs)
  1121. }
  1122. }
  1123. if opts.MilestoneID > 0 {
  1124. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1125. }
  1126. if opts.AssigneeID > 0 {
  1127. sess.And("issue.assignee_id = ?", opts.AssigneeID)
  1128. }
  1129. if opts.PosterID > 0 {
  1130. sess.And("issue.poster_id = ?", opts.PosterID)
  1131. }
  1132. if opts.MentionedID > 0 {
  1133. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1134. And("issue_user.uid = ?", opts.MentionedID).
  1135. And("issue_user.is_mentioned = ?", true)
  1136. }
  1137. return sess
  1138. }
  1139. var err error
  1140. stats.OpenCount, err = countSession(opts).
  1141. And("issue.is_closed = ?", false).
  1142. Count(new(Issue))
  1143. if err != nil {
  1144. return stats, err
  1145. }
  1146. stats.ClosedCount, err = countSession(opts).
  1147. And("issue.is_closed = ?", true).
  1148. Count(new(Issue))
  1149. return stats, err
  1150. }
  1151. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1152. type UserIssueStatsOptions struct {
  1153. UserID int64
  1154. RepoID int64
  1155. UserRepoIDs []int64
  1156. FilterMode int
  1157. IsPull bool
  1158. IsClosed bool
  1159. }
  1160. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1161. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1162. var err error
  1163. stats := &IssueStats{}
  1164. cond := builder.NewCond()
  1165. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1166. if opts.RepoID > 0 {
  1167. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  1168. }
  1169. switch opts.FilterMode {
  1170. case FilterModeAll:
  1171. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1172. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1173. Count(new(Issue))
  1174. if err != nil {
  1175. return nil, err
  1176. }
  1177. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1178. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1179. Count(new(Issue))
  1180. if err != nil {
  1181. return nil, err
  1182. }
  1183. case FilterModeAssign:
  1184. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1185. And("assignee_id = ?", opts.UserID).
  1186. Count(new(Issue))
  1187. if err != nil {
  1188. return nil, err
  1189. }
  1190. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1191. And("assignee_id = ?", opts.UserID).
  1192. Count(new(Issue))
  1193. if err != nil {
  1194. return nil, err
  1195. }
  1196. case FilterModeCreate:
  1197. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1198. And("poster_id = ?", opts.UserID).
  1199. Count(new(Issue))
  1200. if err != nil {
  1201. return nil, err
  1202. }
  1203. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1204. And("poster_id = ?", opts.UserID).
  1205. Count(new(Issue))
  1206. if err != nil {
  1207. return nil, err
  1208. }
  1209. }
  1210. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1211. stats.AssignCount, err = x.Where(cond).
  1212. And("assignee_id = ?", opts.UserID).
  1213. Count(new(Issue))
  1214. if err != nil {
  1215. return nil, err
  1216. }
  1217. stats.CreateCount, err = x.Where(cond).
  1218. And("poster_id = ?", opts.UserID).
  1219. Count(new(Issue))
  1220. if err != nil {
  1221. return nil, err
  1222. }
  1223. stats.YourRepositoriesCount, err = x.Where(cond).
  1224. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1225. Count(new(Issue))
  1226. if err != nil {
  1227. return nil, err
  1228. }
  1229. return stats, nil
  1230. }
  1231. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1232. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1233. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1234. sess := x.
  1235. Where("is_closed = ?", isClosed).
  1236. And("is_pull = ?", isPull).
  1237. And("repo_id = ?", repoID)
  1238. return sess
  1239. }
  1240. openCountSession := countSession(false, isPull, repoID)
  1241. closedCountSession := countSession(true, isPull, repoID)
  1242. switch filterMode {
  1243. case FilterModeAssign:
  1244. openCountSession.And("assignee_id = ?", uid)
  1245. closedCountSession.And("assignee_id = ?", uid)
  1246. case FilterModeCreate:
  1247. openCountSession.And("poster_id = ?", uid)
  1248. closedCountSession.And("poster_id = ?", uid)
  1249. }
  1250. openResult, _ := openCountSession.Count(new(Issue))
  1251. closedResult, _ := closedCountSession.Count(new(Issue))
  1252. return openResult, closedResult
  1253. }
  1254. func updateIssue(e Engine, issue *Issue) error {
  1255. _, err := e.ID(issue.ID).AllCols().Update(issue)
  1256. if err != nil {
  1257. return err
  1258. }
  1259. UpdateIssueIndexer(issue.ID)
  1260. return nil
  1261. }
  1262. // UpdateIssue updates all fields of given issue.
  1263. func UpdateIssue(issue *Issue) error {
  1264. return updateIssue(x, issue)
  1265. }