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 44 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
9 years ago
8 years ago
8 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663
  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. "regexp"
  9. "sort"
  10. "strings"
  11. "code.gitea.io/gitea/modules/base"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. "code.gitea.io/gitea/modules/util"
  15. api "code.gitea.io/sdk/gitea"
  16. "github.com/Unknwon/com"
  17. "github.com/go-xorm/builder"
  18. "github.com/go-xorm/xorm"
  19. )
  20. // Issue represents an issue or pull request of repository.
  21. type Issue struct {
  22. ID int64 `xorm:"pk autoincr"`
  23. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  24. Repo *Repository `xorm:"-"`
  25. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  26. PosterID int64 `xorm:"INDEX"`
  27. Poster *User `xorm:"-"`
  28. Title string `xorm:"name"`
  29. Content string `xorm:"TEXT"`
  30. RenderedContent string `xorm:"-"`
  31. Labels []*Label `xorm:"-"`
  32. MilestoneID int64 `xorm:"INDEX"`
  33. Milestone *Milestone `xorm:"-"`
  34. Priority int
  35. AssigneeID int64 `xorm:"-"`
  36. Assignee *User `xorm:"-"`
  37. IsClosed bool `xorm:"INDEX"`
  38. IsRead bool `xorm:"-"`
  39. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  40. PullRequest *PullRequest `xorm:"-"`
  41. NumComments int
  42. Ref string
  43. DeadlineUnix util.TimeStamp `xorm:"INDEX"`
  44. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  45. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  46. ClosedUnix util.TimeStamp `xorm:"INDEX"`
  47. Attachments []*Attachment `xorm:"-"`
  48. Comments []*Comment `xorm:"-"`
  49. Reactions ReactionList `xorm:"-"`
  50. TotalTrackedTime int64 `xorm:"-"`
  51. Assignees []*User `xorm:"-"`
  52. }
  53. var (
  54. issueTasksPat *regexp.Regexp
  55. issueTasksDonePat *regexp.Regexp
  56. )
  57. const issueTasksRegexpStr = `(^\s*[-*]\s\[[\sx]\]\s.)|(\n\s*[-*]\s\[[\sx]\]\s.)`
  58. const issueTasksDoneRegexpStr = `(^\s*[-*]\s\[[x]\]\s.)|(\n\s*[-*]\s\[[x]\]\s.)`
  59. func init() {
  60. issueTasksPat = regexp.MustCompile(issueTasksRegexpStr)
  61. issueTasksDonePat = regexp.MustCompile(issueTasksDoneRegexpStr)
  62. }
  63. func (issue *Issue) loadTotalTimes(e Engine) (err error) {
  64. opts := FindTrackedTimesOptions{IssueID: issue.ID}
  65. issue.TotalTrackedTime, err = opts.ToSession(e).SumInt(&TrackedTime{}, "time")
  66. if err != nil {
  67. return err
  68. }
  69. return nil
  70. }
  71. // IsOverdue checks if the issue is overdue
  72. func (issue *Issue) IsOverdue() bool {
  73. return util.TimeStampNow() >= issue.DeadlineUnix
  74. }
  75. func (issue *Issue) loadRepo(e Engine) (err error) {
  76. if issue.Repo == nil {
  77. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  78. if err != nil {
  79. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  80. }
  81. }
  82. return nil
  83. }
  84. // IsTimetrackerEnabled returns true if the repo enables timetracking
  85. func (issue *Issue) IsTimetrackerEnabled() bool {
  86. if err := issue.loadRepo(x); err != nil {
  87. log.Error(4, fmt.Sprintf("loadRepo: %v", err))
  88. return false
  89. }
  90. return issue.Repo.IsTimetrackerEnabled()
  91. }
  92. // GetPullRequest returns the issue pull request
  93. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  94. if !issue.IsPull {
  95. return nil, fmt.Errorf("Issue is not a pull request")
  96. }
  97. pr, err = getPullRequestByIssueID(x, issue.ID)
  98. if err != nil {
  99. return nil, err
  100. }
  101. pr.Issue = issue
  102. return
  103. }
  104. func (issue *Issue) loadLabels(e Engine) (err error) {
  105. if issue.Labels == nil {
  106. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  107. if err != nil {
  108. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  109. }
  110. }
  111. return nil
  112. }
  113. func (issue *Issue) loadPoster(e Engine) (err error) {
  114. if issue.Poster == nil {
  115. issue.Poster, err = getUserByID(e, issue.PosterID)
  116. if err != nil {
  117. issue.PosterID = -1
  118. issue.Poster = NewGhostUser()
  119. if !IsErrUserNotExist(err) {
  120. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  121. }
  122. err = nil
  123. return
  124. }
  125. }
  126. return
  127. }
  128. func (issue *Issue) loadPullRequest(e Engine) (err error) {
  129. if issue.IsPull && issue.PullRequest == nil {
  130. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  131. if err != nil {
  132. if IsErrPullRequestNotExist(err) {
  133. return err
  134. }
  135. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  136. }
  137. }
  138. return nil
  139. }
  140. func (issue *Issue) loadComments(e Engine) (err error) {
  141. if issue.Comments != nil {
  142. return nil
  143. }
  144. issue.Comments, err = findComments(e, FindCommentsOptions{
  145. IssueID: issue.ID,
  146. Type: CommentTypeUnknown,
  147. })
  148. return err
  149. }
  150. func (issue *Issue) loadReactions(e Engine) (err error) {
  151. if issue.Reactions != nil {
  152. return nil
  153. }
  154. reactions, err := findReactions(e, FindReactionsOptions{
  155. IssueID: issue.ID,
  156. })
  157. if err != nil {
  158. return err
  159. }
  160. // Load reaction user data
  161. if _, err := ReactionList(reactions).LoadUsers(); err != nil {
  162. return err
  163. }
  164. // Cache comments to map
  165. comments := make(map[int64]*Comment)
  166. for _, comment := range issue.Comments {
  167. comments[comment.ID] = comment
  168. }
  169. // Add reactions either to issue or comment
  170. for _, react := range reactions {
  171. if react.CommentID == 0 {
  172. issue.Reactions = append(issue.Reactions, react)
  173. } else if comment, ok := comments[react.CommentID]; ok {
  174. comment.Reactions = append(comment.Reactions, react)
  175. }
  176. }
  177. return nil
  178. }
  179. func (issue *Issue) loadAttributes(e Engine) (err error) {
  180. if err = issue.loadRepo(e); err != nil {
  181. return
  182. }
  183. if err = issue.loadPoster(e); err != nil {
  184. return
  185. }
  186. if err = issue.loadLabels(e); err != nil {
  187. return
  188. }
  189. if issue.Milestone == nil && issue.MilestoneID > 0 {
  190. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  191. if err != nil && !IsErrMilestoneNotExist(err) {
  192. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  193. }
  194. }
  195. if err = issue.loadAssignees(e); err != nil {
  196. return
  197. }
  198. if err = issue.loadPullRequest(e); err != nil && !IsErrPullRequestNotExist(err) {
  199. // It is possible pull request is not yet created.
  200. return err
  201. }
  202. if issue.Attachments == nil {
  203. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  204. if err != nil {
  205. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  206. }
  207. }
  208. if err = issue.loadComments(e); err != nil {
  209. return err
  210. }
  211. if issue.IsTimetrackerEnabled() {
  212. if err = issue.loadTotalTimes(e); err != nil {
  213. return err
  214. }
  215. }
  216. return issue.loadReactions(e)
  217. }
  218. // LoadAttributes loads the attribute of this issue.
  219. func (issue *Issue) LoadAttributes() error {
  220. return issue.loadAttributes(x)
  221. }
  222. // GetIsRead load the `IsRead` field of the issue
  223. func (issue *Issue) GetIsRead(userID int64) error {
  224. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  225. if has, err := x.Get(issueUser); err != nil {
  226. return err
  227. } else if !has {
  228. issue.IsRead = false
  229. return nil
  230. }
  231. issue.IsRead = issueUser.IsRead
  232. return nil
  233. }
  234. // APIURL returns the absolute APIURL to this issue.
  235. func (issue *Issue) APIURL() string {
  236. return issue.Repo.APIURL() + "/" + path.Join("issues", fmt.Sprint(issue.Index))
  237. }
  238. // HTMLURL returns the absolute URL to this issue.
  239. func (issue *Issue) HTMLURL() string {
  240. var path string
  241. if issue.IsPull {
  242. path = "pulls"
  243. } else {
  244. path = "issues"
  245. }
  246. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  247. }
  248. // DiffURL returns the absolute URL to this diff
  249. func (issue *Issue) DiffURL() string {
  250. if issue.IsPull {
  251. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  252. }
  253. return ""
  254. }
  255. // PatchURL returns the absolute URL to this patch
  256. func (issue *Issue) PatchURL() string {
  257. if issue.IsPull {
  258. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  259. }
  260. return ""
  261. }
  262. // State returns string representation of issue status.
  263. func (issue *Issue) State() api.StateType {
  264. if issue.IsClosed {
  265. return api.StateClosed
  266. }
  267. return api.StateOpen
  268. }
  269. // APIFormat assumes some fields assigned with values:
  270. // Required - Poster, Labels,
  271. // Optional - Milestone, Assignee, PullRequest
  272. func (issue *Issue) APIFormat() *api.Issue {
  273. apiLabels := make([]*api.Label, len(issue.Labels))
  274. for i := range issue.Labels {
  275. apiLabels[i] = issue.Labels[i].APIFormat()
  276. }
  277. apiIssue := &api.Issue{
  278. ID: issue.ID,
  279. URL: issue.APIURL(),
  280. Index: issue.Index,
  281. Poster: issue.Poster.APIFormat(),
  282. Title: issue.Title,
  283. Body: issue.Content,
  284. Labels: apiLabels,
  285. State: issue.State(),
  286. Comments: issue.NumComments,
  287. Created: issue.CreatedUnix.AsTime(),
  288. Updated: issue.UpdatedUnix.AsTime(),
  289. }
  290. if issue.Milestone != nil {
  291. apiIssue.Milestone = issue.Milestone.APIFormat()
  292. }
  293. if len(issue.Assignees) > 0 {
  294. for _, assignee := range issue.Assignees {
  295. apiIssue.Assignees = append(apiIssue.Assignees, assignee.APIFormat())
  296. }
  297. apiIssue.Assignee = issue.Assignees[0].APIFormat() // For compatibility, we're keeping the first assignee as `apiIssue.Assignee`
  298. }
  299. if issue.IsPull {
  300. apiIssue.PullRequest = &api.PullRequestMeta{
  301. HasMerged: issue.PullRequest.HasMerged,
  302. }
  303. if issue.PullRequest.HasMerged {
  304. apiIssue.PullRequest.Merged = issue.PullRequest.MergedUnix.AsTimePtr()
  305. }
  306. }
  307. if issue.DeadlineUnix != 0 {
  308. apiIssue.Deadline = issue.DeadlineUnix.AsTimePtr()
  309. }
  310. return apiIssue
  311. }
  312. // HashTag returns unique hash tag for issue.
  313. func (issue *Issue) HashTag() string {
  314. return "issue-" + com.ToStr(issue.ID)
  315. }
  316. // IsPoster returns true if given user by ID is the poster.
  317. func (issue *Issue) IsPoster(uid int64) bool {
  318. return issue.PosterID == uid
  319. }
  320. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  321. return hasIssueLabel(e, issue.ID, labelID)
  322. }
  323. // HasLabel returns true if issue has been labeled by given ID.
  324. func (issue *Issue) HasLabel(labelID int64) bool {
  325. return issue.hasLabel(x, labelID)
  326. }
  327. func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
  328. var err error
  329. if err = issue.loadRepo(x); err != nil {
  330. log.Error(4, "loadRepo: %v", err)
  331. return
  332. }
  333. if err = issue.loadPoster(x); err != nil {
  334. log.Error(4, "loadPoster: %v", err)
  335. return
  336. }
  337. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  338. if issue.IsPull {
  339. if err = issue.loadPullRequest(x); err != nil {
  340. log.Error(4, "loadPullRequest: %v", err)
  341. return
  342. }
  343. if err = issue.PullRequest.LoadIssue(); err != nil {
  344. log.Error(4, "LoadIssue: %v", err)
  345. return
  346. }
  347. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  348. Action: api.HookIssueLabelUpdated,
  349. Index: issue.Index,
  350. PullRequest: issue.PullRequest.APIFormat(),
  351. Repository: issue.Repo.APIFormat(AccessModeNone),
  352. Sender: doer.APIFormat(),
  353. })
  354. } else {
  355. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  356. Action: api.HookIssueLabelUpdated,
  357. Index: issue.Index,
  358. Issue: issue.APIFormat(),
  359. Repository: issue.Repo.APIFormat(mode),
  360. Sender: doer.APIFormat(),
  361. })
  362. }
  363. if err != nil {
  364. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  365. } else {
  366. go HookQueue.Add(issue.RepoID)
  367. }
  368. }
  369. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  370. return newIssueLabel(e, issue, label, doer)
  371. }
  372. // AddLabel adds a new label to the issue.
  373. func (issue *Issue) AddLabel(doer *User, label *Label) error {
  374. if err := NewIssueLabel(issue, label, doer); err != nil {
  375. return err
  376. }
  377. issue.sendLabelUpdatedWebhook(doer)
  378. return nil
  379. }
  380. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  381. return newIssueLabels(e, issue, labels, doer)
  382. }
  383. // AddLabels adds a list of new labels to the issue.
  384. func (issue *Issue) AddLabels(doer *User, labels []*Label) error {
  385. if err := NewIssueLabels(issue, labels, doer); err != nil {
  386. return err
  387. }
  388. issue.sendLabelUpdatedWebhook(doer)
  389. return nil
  390. }
  391. func (issue *Issue) getLabels(e Engine) (err error) {
  392. if len(issue.Labels) > 0 {
  393. return nil
  394. }
  395. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  396. if err != nil {
  397. return fmt.Errorf("getLabelsByIssueID: %v", err)
  398. }
  399. return nil
  400. }
  401. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  402. return deleteIssueLabel(e, issue, label, doer)
  403. }
  404. // RemoveLabel removes a label from issue by given ID.
  405. func (issue *Issue) RemoveLabel(doer *User, label *Label) error {
  406. if err := issue.loadRepo(x); err != nil {
  407. return err
  408. }
  409. perm, err := GetUserRepoPermission(issue.Repo, doer)
  410. if err != nil {
  411. return err
  412. }
  413. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  414. return ErrLabelNotExist{}
  415. }
  416. if err := DeleteIssueLabel(issue, label, doer); err != nil {
  417. return err
  418. }
  419. issue.sendLabelUpdatedWebhook(doer)
  420. return nil
  421. }
  422. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  423. if err = issue.getLabels(e); err != nil {
  424. return fmt.Errorf("getLabels: %v", err)
  425. }
  426. for i := range issue.Labels {
  427. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  428. return fmt.Errorf("removeLabel: %v", err)
  429. }
  430. }
  431. return nil
  432. }
  433. // ClearLabels removes all issue labels as the given user.
  434. // Triggers appropriate WebHooks, if any.
  435. func (issue *Issue) ClearLabels(doer *User) (err error) {
  436. sess := x.NewSession()
  437. defer sess.Close()
  438. if err = sess.Begin(); err != nil {
  439. return err
  440. }
  441. if err := issue.loadRepo(sess); err != nil {
  442. return err
  443. } else if err = issue.loadPullRequest(sess); err != nil {
  444. return err
  445. }
  446. perm, err := getUserRepoPermission(sess, issue.Repo, doer)
  447. if err != nil {
  448. return err
  449. }
  450. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  451. return ErrLabelNotExist{}
  452. }
  453. if err = issue.clearLabels(sess, doer); err != nil {
  454. return err
  455. }
  456. if err = sess.Commit(); err != nil {
  457. return fmt.Errorf("Commit: %v", err)
  458. }
  459. if err = issue.loadPoster(x); err != nil {
  460. return fmt.Errorf("loadPoster: %v", err)
  461. }
  462. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  463. if issue.IsPull {
  464. err = issue.PullRequest.LoadIssue()
  465. if err != nil {
  466. log.Error(4, "LoadIssue: %v", err)
  467. return
  468. }
  469. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  470. Action: api.HookIssueLabelCleared,
  471. Index: issue.Index,
  472. PullRequest: issue.PullRequest.APIFormat(),
  473. Repository: issue.Repo.APIFormat(mode),
  474. Sender: doer.APIFormat(),
  475. })
  476. } else {
  477. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  478. Action: api.HookIssueLabelCleared,
  479. Index: issue.Index,
  480. Issue: issue.APIFormat(),
  481. Repository: issue.Repo.APIFormat(mode),
  482. Sender: doer.APIFormat(),
  483. })
  484. }
  485. if err != nil {
  486. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  487. } else {
  488. go HookQueue.Add(issue.RepoID)
  489. }
  490. return nil
  491. }
  492. type labelSorter []*Label
  493. func (ts labelSorter) Len() int {
  494. return len([]*Label(ts))
  495. }
  496. func (ts labelSorter) Less(i, j int) bool {
  497. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  498. }
  499. func (ts labelSorter) Swap(i, j int) {
  500. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  501. }
  502. // ReplaceLabels removes all current labels and add new labels to the issue.
  503. // Triggers appropriate WebHooks, if any.
  504. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  505. sess := x.NewSession()
  506. defer sess.Close()
  507. if err = sess.Begin(); err != nil {
  508. return err
  509. }
  510. if err = issue.loadLabels(sess); err != nil {
  511. return err
  512. }
  513. sort.Sort(labelSorter(labels))
  514. sort.Sort(labelSorter(issue.Labels))
  515. var toAdd, toRemove []*Label
  516. addIndex, removeIndex := 0, 0
  517. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  518. addLabel := labels[addIndex]
  519. removeLabel := issue.Labels[removeIndex]
  520. if addLabel.ID == removeLabel.ID {
  521. addIndex++
  522. removeIndex++
  523. } else if addLabel.ID < removeLabel.ID {
  524. toAdd = append(toAdd, addLabel)
  525. addIndex++
  526. } else {
  527. toRemove = append(toRemove, removeLabel)
  528. removeIndex++
  529. }
  530. }
  531. toAdd = append(toAdd, labels[addIndex:]...)
  532. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  533. if len(toAdd) > 0 {
  534. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  535. return fmt.Errorf("addLabels: %v", err)
  536. }
  537. }
  538. for _, l := range toRemove {
  539. if err = issue.removeLabel(sess, doer, l); err != nil {
  540. return fmt.Errorf("removeLabel: %v", err)
  541. }
  542. }
  543. return sess.Commit()
  544. }
  545. // ReadBy sets issue to be read by given user.
  546. func (issue *Issue) ReadBy(userID int64) error {
  547. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  548. return err
  549. }
  550. return setNotificationStatusReadIfUnread(x, userID, issue.ID)
  551. }
  552. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  553. if _, err := e.ID(issue.ID).Cols(cols...).Update(issue); err != nil {
  554. return err
  555. }
  556. UpdateIssueIndexerCols(issue.ID, cols...)
  557. return nil
  558. }
  559. // UpdateIssueCols only updates values of specific columns for given issue.
  560. func UpdateIssueCols(issue *Issue, cols ...string) error {
  561. return updateIssueCols(x, issue, cols...)
  562. }
  563. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
  564. // Nothing should be performed if current status is same as target status
  565. if issue.IsClosed == isClosed {
  566. return nil
  567. }
  568. // Check for open dependencies
  569. if isClosed && issue.Repo.isDependenciesEnabled(e) {
  570. // only check if dependencies are enabled and we're about to close an issue, otherwise reopening an issue would fail when there are unsatisfied dependencies
  571. noDeps, err := issueNoDependenciesLeft(e, issue)
  572. if err != nil {
  573. return err
  574. }
  575. if !noDeps {
  576. return ErrDependenciesLeft{issue.ID}
  577. }
  578. }
  579. issue.IsClosed = isClosed
  580. if isClosed {
  581. issue.ClosedUnix = util.TimeStampNow()
  582. } else {
  583. issue.ClosedUnix = 0
  584. }
  585. if err = updateIssueCols(e, issue, "is_closed", "closed_unix"); err != nil {
  586. return err
  587. }
  588. // Update issue count of labels
  589. if err = issue.getLabels(e); err != nil {
  590. return err
  591. }
  592. for idx := range issue.Labels {
  593. if issue.IsClosed {
  594. issue.Labels[idx].NumClosedIssues++
  595. } else {
  596. issue.Labels[idx].NumClosedIssues--
  597. }
  598. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  599. return err
  600. }
  601. }
  602. // Update issue count of milestone
  603. if err = changeMilestoneIssueStats(e, issue); err != nil {
  604. return err
  605. }
  606. // New action comment
  607. if _, err = createStatusComment(e, doer, repo, issue); err != nil {
  608. return err
  609. }
  610. return nil
  611. }
  612. // ChangeStatus changes issue status to open or closed.
  613. func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (err error) {
  614. sess := x.NewSession()
  615. defer sess.Close()
  616. if err = sess.Begin(); err != nil {
  617. return err
  618. }
  619. if err = issue.changeStatus(sess, doer, repo, isClosed); err != nil {
  620. return err
  621. }
  622. if err = sess.Commit(); err != nil {
  623. return fmt.Errorf("Commit: %v", err)
  624. }
  625. sess.Close()
  626. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  627. if issue.IsPull {
  628. // Merge pull request calls issue.changeStatus so we need to handle separately.
  629. issue.PullRequest.Issue = issue
  630. apiPullRequest := &api.PullRequestPayload{
  631. Index: issue.Index,
  632. PullRequest: issue.PullRequest.APIFormat(),
  633. Repository: repo.APIFormat(mode),
  634. Sender: doer.APIFormat(),
  635. }
  636. if isClosed {
  637. apiPullRequest.Action = api.HookIssueClosed
  638. } else {
  639. apiPullRequest.Action = api.HookIssueReOpened
  640. }
  641. err = PrepareWebhooks(repo, HookEventPullRequest, apiPullRequest)
  642. } else {
  643. apiIssue := &api.IssuePayload{
  644. Index: issue.Index,
  645. Issue: issue.APIFormat(),
  646. Repository: repo.APIFormat(mode),
  647. Sender: doer.APIFormat(),
  648. }
  649. if isClosed {
  650. apiIssue.Action = api.HookIssueClosed
  651. } else {
  652. apiIssue.Action = api.HookIssueReOpened
  653. }
  654. err = PrepareWebhooks(repo, HookEventIssues, apiIssue)
  655. }
  656. if err != nil {
  657. log.Error(4, "PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  658. } else {
  659. go HookQueue.Add(repo.ID)
  660. }
  661. return nil
  662. }
  663. // ChangeTitle changes the title of this issue, as the given user.
  664. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
  665. oldTitle := issue.Title
  666. issue.Title = title
  667. sess := x.NewSession()
  668. defer sess.Close()
  669. if err = sess.Begin(); err != nil {
  670. return err
  671. }
  672. if err = updateIssueCols(sess, issue, "name"); err != nil {
  673. return fmt.Errorf("updateIssueCols: %v", err)
  674. }
  675. if _, err = createChangeTitleComment(sess, doer, issue.Repo, issue, oldTitle, title); err != nil {
  676. return fmt.Errorf("createChangeTitleComment: %v", err)
  677. }
  678. if err = sess.Commit(); err != nil {
  679. return err
  680. }
  681. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  682. if issue.IsPull {
  683. issue.PullRequest.Issue = issue
  684. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  685. Action: api.HookIssueEdited,
  686. Index: issue.Index,
  687. Changes: &api.ChangesPayload{
  688. Title: &api.ChangesFromPayload{
  689. From: oldTitle,
  690. },
  691. },
  692. PullRequest: issue.PullRequest.APIFormat(),
  693. Repository: issue.Repo.APIFormat(mode),
  694. Sender: doer.APIFormat(),
  695. })
  696. } else {
  697. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  698. Action: api.HookIssueEdited,
  699. Index: issue.Index,
  700. Changes: &api.ChangesPayload{
  701. Title: &api.ChangesFromPayload{
  702. From: oldTitle,
  703. },
  704. },
  705. Issue: issue.APIFormat(),
  706. Repository: issue.Repo.APIFormat(mode),
  707. Sender: issue.Poster.APIFormat(),
  708. })
  709. }
  710. if err != nil {
  711. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  712. } else {
  713. go HookQueue.Add(issue.RepoID)
  714. }
  715. return nil
  716. }
  717. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  718. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  719. issue, err := getIssueByID(x, issueID)
  720. if err != nil {
  721. return err
  722. }
  723. sess := x.NewSession()
  724. defer sess.Close()
  725. if err := sess.Begin(); err != nil {
  726. return err
  727. }
  728. if _, err := createDeleteBranchComment(sess, doer, repo, issue, branchName); err != nil {
  729. return err
  730. }
  731. return sess.Commit()
  732. }
  733. // ChangeContent changes issue content, as the given user.
  734. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  735. oldContent := issue.Content
  736. issue.Content = content
  737. if err = UpdateIssueCols(issue, "content"); err != nil {
  738. return fmt.Errorf("UpdateIssueCols: %v", err)
  739. }
  740. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  741. if issue.IsPull {
  742. issue.PullRequest.Issue = issue
  743. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  744. Action: api.HookIssueEdited,
  745. Index: issue.Index,
  746. Changes: &api.ChangesPayload{
  747. Body: &api.ChangesFromPayload{
  748. From: oldContent,
  749. },
  750. },
  751. PullRequest: issue.PullRequest.APIFormat(),
  752. Repository: issue.Repo.APIFormat(mode),
  753. Sender: doer.APIFormat(),
  754. })
  755. } else {
  756. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  757. Action: api.HookIssueEdited,
  758. Index: issue.Index,
  759. Changes: &api.ChangesPayload{
  760. Body: &api.ChangesFromPayload{
  761. From: oldContent,
  762. },
  763. },
  764. Issue: issue.APIFormat(),
  765. Repository: issue.Repo.APIFormat(mode),
  766. Sender: doer.APIFormat(),
  767. })
  768. }
  769. if err != nil {
  770. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  771. } else {
  772. go HookQueue.Add(issue.RepoID)
  773. }
  774. return nil
  775. }
  776. // GetTasks returns the amount of tasks in the issues content
  777. func (issue *Issue) GetTasks() int {
  778. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  779. }
  780. // GetTasksDone returns the amount of completed tasks in the issues content
  781. func (issue *Issue) GetTasksDone() int {
  782. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  783. }
  784. // NewIssueOptions represents the options of a new issue.
  785. type NewIssueOptions struct {
  786. Repo *Repository
  787. Issue *Issue
  788. LabelIDs []int64
  789. AssigneeIDs []int64
  790. Attachments []string // In UUID format.
  791. IsPull bool
  792. }
  793. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  794. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  795. opts.Issue.Index = opts.Repo.NextIssueIndex()
  796. if opts.Issue.MilestoneID > 0 {
  797. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  798. if err != nil && !IsErrMilestoneNotExist(err) {
  799. return fmt.Errorf("getMilestoneByID: %v", err)
  800. }
  801. // Assume milestone is invalid and drop silently.
  802. opts.Issue.MilestoneID = 0
  803. if milestone != nil {
  804. opts.Issue.MilestoneID = milestone.ID
  805. opts.Issue.Milestone = milestone
  806. }
  807. }
  808. // Keep the old assignee id thingy for compatibility reasons
  809. if opts.Issue.AssigneeID > 0 {
  810. isAdded := false
  811. // Check if the user has already been passed to issue.AssigneeIDs, if not, add it
  812. for _, aID := range opts.AssigneeIDs {
  813. if aID == opts.Issue.AssigneeID {
  814. isAdded = true
  815. break
  816. }
  817. }
  818. if !isAdded {
  819. opts.AssigneeIDs = append(opts.AssigneeIDs, opts.Issue.AssigneeID)
  820. }
  821. }
  822. // Check for and validate assignees
  823. if len(opts.AssigneeIDs) > 0 {
  824. for _, assigneeID := range opts.AssigneeIDs {
  825. user, err := getUserByID(e, assigneeID)
  826. if err != nil {
  827. return fmt.Errorf("getUserByID [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  828. }
  829. valid, err := canBeAssigned(e, user, opts.Repo)
  830. if err != nil {
  831. return fmt.Errorf("canBeAssigned [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  832. }
  833. if !valid {
  834. return ErrUserDoesNotHaveAccessToRepo{UserID: assigneeID, RepoName: opts.Repo.Name}
  835. }
  836. }
  837. }
  838. // Milestone and assignee validation should happen before insert actual object.
  839. if _, err = e.Insert(opts.Issue); err != nil {
  840. return err
  841. }
  842. if opts.Issue.MilestoneID > 0 {
  843. if err = changeMilestoneAssign(e, doer, opts.Issue, -1); err != nil {
  844. return err
  845. }
  846. }
  847. // Insert the assignees
  848. for _, assigneeID := range opts.AssigneeIDs {
  849. err = opts.Issue.changeAssignee(e, doer, assigneeID, true)
  850. if err != nil {
  851. return err
  852. }
  853. }
  854. if opts.IsPull {
  855. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  856. } else {
  857. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  858. }
  859. if err != nil {
  860. return err
  861. }
  862. if len(opts.LabelIDs) > 0 {
  863. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  864. // So we have to get all needed labels first.
  865. labels := make([]*Label, 0, len(opts.LabelIDs))
  866. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  867. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  868. }
  869. if err = opts.Issue.loadPoster(e); err != nil {
  870. return err
  871. }
  872. for _, label := range labels {
  873. // Silently drop invalid labels.
  874. if label.RepoID != opts.Repo.ID {
  875. continue
  876. }
  877. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  878. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  879. }
  880. }
  881. }
  882. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  883. return err
  884. }
  885. if len(opts.Attachments) > 0 {
  886. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  887. if err != nil {
  888. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  889. }
  890. for i := 0; i < len(attachments); i++ {
  891. attachments[i].IssueID = opts.Issue.ID
  892. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  893. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  894. }
  895. }
  896. }
  897. return opts.Issue.loadAttributes(e)
  898. }
  899. // NewIssue creates new issue with labels for repository.
  900. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, assigneeIDs []int64, uuids []string) (err error) {
  901. sess := x.NewSession()
  902. defer sess.Close()
  903. if err = sess.Begin(); err != nil {
  904. return err
  905. }
  906. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  907. Repo: repo,
  908. Issue: issue,
  909. LabelIDs: labelIDs,
  910. Attachments: uuids,
  911. AssigneeIDs: assigneeIDs,
  912. }); err != nil {
  913. if IsErrUserDoesNotHaveAccessToRepo(err) {
  914. return err
  915. }
  916. return fmt.Errorf("newIssue: %v", err)
  917. }
  918. if err = sess.Commit(); err != nil {
  919. return fmt.Errorf("Commit: %v", err)
  920. }
  921. UpdateIssueIndexer(issue.ID)
  922. if err = NotifyWatchers(&Action{
  923. ActUserID: issue.Poster.ID,
  924. ActUser: issue.Poster,
  925. OpType: ActionCreateIssue,
  926. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  927. RepoID: repo.ID,
  928. Repo: repo,
  929. IsPrivate: repo.IsPrivate,
  930. }); err != nil {
  931. log.Error(4, "NotifyWatchers: %v", err)
  932. }
  933. if err = issue.MailParticipants(); err != nil {
  934. log.Error(4, "MailParticipants: %v", err)
  935. }
  936. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  937. if err = PrepareWebhooks(repo, HookEventIssues, &api.IssuePayload{
  938. Action: api.HookIssueOpened,
  939. Index: issue.Index,
  940. Issue: issue.APIFormat(),
  941. Repository: repo.APIFormat(mode),
  942. Sender: issue.Poster.APIFormat(),
  943. }); err != nil {
  944. log.Error(4, "PrepareWebhooks: %v", err)
  945. } else {
  946. go HookQueue.Add(issue.RepoID)
  947. }
  948. return nil
  949. }
  950. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  951. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  952. issue := &Issue{
  953. RepoID: repoID,
  954. Index: index,
  955. }
  956. has, err := x.Get(issue)
  957. if err != nil {
  958. return nil, err
  959. } else if !has {
  960. return nil, ErrIssueNotExist{0, repoID, index}
  961. }
  962. return issue, nil
  963. }
  964. // GetIssueByIndex returns issue by index in a repository.
  965. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  966. issue, err := GetRawIssueByIndex(repoID, index)
  967. if err != nil {
  968. return nil, err
  969. }
  970. return issue, issue.LoadAttributes()
  971. }
  972. func getIssueByID(e Engine, id int64) (*Issue, error) {
  973. issue := new(Issue)
  974. has, err := e.ID(id).Get(issue)
  975. if err != nil {
  976. return nil, err
  977. } else if !has {
  978. return nil, ErrIssueNotExist{id, 0, 0}
  979. }
  980. return issue, issue.loadAttributes(e)
  981. }
  982. // GetIssueByID returns an issue by given ID.
  983. func GetIssueByID(id int64) (*Issue, error) {
  984. return getIssueByID(x, id)
  985. }
  986. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  987. issues := make([]*Issue, 0, 10)
  988. return issues, e.In("id", issueIDs).Find(&issues)
  989. }
  990. // GetIssuesByIDs return issues with the given IDs.
  991. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  992. return getIssuesByIDs(x, issueIDs)
  993. }
  994. // IssuesOptions represents options of an issue.
  995. type IssuesOptions struct {
  996. RepoIDs []int64 // include all repos if empty
  997. AssigneeID int64
  998. PosterID int64
  999. MentionedID int64
  1000. MilestoneID int64
  1001. Page int
  1002. PageSize int
  1003. IsClosed util.OptionalBool
  1004. IsPull util.OptionalBool
  1005. Labels string
  1006. SortType string
  1007. IssueIDs []int64
  1008. }
  1009. // sortIssuesSession sort an issues-related session based on the provided
  1010. // sortType string
  1011. func sortIssuesSession(sess *xorm.Session, sortType string) {
  1012. switch sortType {
  1013. case "oldest":
  1014. sess.Asc("issue.created_unix")
  1015. case "recentupdate":
  1016. sess.Desc("issue.updated_unix")
  1017. case "leastupdate":
  1018. sess.Asc("issue.updated_unix")
  1019. case "mostcomment":
  1020. sess.Desc("issue.num_comments")
  1021. case "leastcomment":
  1022. sess.Asc("issue.num_comments")
  1023. case "priority":
  1024. sess.Desc("issue.priority")
  1025. default:
  1026. sess.Desc("issue.created_unix")
  1027. }
  1028. }
  1029. func (opts *IssuesOptions) setupSession(sess *xorm.Session) error {
  1030. if opts.Page >= 0 && opts.PageSize > 0 {
  1031. var start int
  1032. if opts.Page == 0 {
  1033. start = 0
  1034. } else {
  1035. start = (opts.Page - 1) * opts.PageSize
  1036. }
  1037. sess.Limit(opts.PageSize, start)
  1038. }
  1039. if len(opts.IssueIDs) > 0 {
  1040. sess.In("issue.id", opts.IssueIDs)
  1041. }
  1042. if len(opts.RepoIDs) > 0 {
  1043. // In case repository IDs are provided but actually no repository has issue.
  1044. sess.In("issue.repo_id", opts.RepoIDs)
  1045. }
  1046. switch opts.IsClosed {
  1047. case util.OptionalBoolTrue:
  1048. sess.And("issue.is_closed=?", true)
  1049. case util.OptionalBoolFalse:
  1050. sess.And("issue.is_closed=?", false)
  1051. }
  1052. if opts.AssigneeID > 0 {
  1053. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1054. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1055. }
  1056. if opts.PosterID > 0 {
  1057. sess.And("issue.poster_id=?", opts.PosterID)
  1058. }
  1059. if opts.MentionedID > 0 {
  1060. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1061. And("issue_user.is_mentioned = ?", true).
  1062. And("issue_user.uid = ?", opts.MentionedID)
  1063. }
  1064. if opts.MilestoneID > 0 {
  1065. sess.And("issue.milestone_id=?", opts.MilestoneID)
  1066. }
  1067. switch opts.IsPull {
  1068. case util.OptionalBoolTrue:
  1069. sess.And("issue.is_pull=?", true)
  1070. case util.OptionalBoolFalse:
  1071. sess.And("issue.is_pull=?", false)
  1072. }
  1073. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1074. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1075. if err != nil {
  1076. return err
  1077. }
  1078. if len(labelIDs) > 0 {
  1079. sess.
  1080. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  1081. In("issue_label.label_id", labelIDs)
  1082. }
  1083. }
  1084. return nil
  1085. }
  1086. // CountIssuesByRepo map from repoID to number of issues matching the options
  1087. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1088. sess := x.NewSession()
  1089. defer sess.Close()
  1090. if err := opts.setupSession(sess); err != nil {
  1091. return nil, err
  1092. }
  1093. countsSlice := make([]*struct {
  1094. RepoID int64
  1095. Count int64
  1096. }, 0, 10)
  1097. if err := sess.GroupBy("issue.repo_id").
  1098. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1099. Table("issue").
  1100. Find(&countsSlice); err != nil {
  1101. return nil, err
  1102. }
  1103. countMap := make(map[int64]int64, len(countsSlice))
  1104. for _, c := range countsSlice {
  1105. countMap[c.RepoID] = c.Count
  1106. }
  1107. return countMap, nil
  1108. }
  1109. // Issues returns a list of issues by given conditions.
  1110. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1111. sess := x.NewSession()
  1112. defer sess.Close()
  1113. if err := opts.setupSession(sess); err != nil {
  1114. return nil, err
  1115. }
  1116. sortIssuesSession(sess, opts.SortType)
  1117. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1118. if err := sess.Find(&issues); err != nil {
  1119. return nil, fmt.Errorf("Find: %v", err)
  1120. }
  1121. if err := IssueList(issues).LoadAttributes(); err != nil {
  1122. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1123. }
  1124. return issues, nil
  1125. }
  1126. // GetParticipantsByIssueID returns all users who are participated in comments of an issue.
  1127. func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
  1128. return getParticipantsByIssueID(x, issueID)
  1129. }
  1130. func getParticipantsByIssueID(e Engine, issueID int64) ([]*User, error) {
  1131. userIDs := make([]int64, 0, 5)
  1132. if err := e.Table("comment").Cols("poster_id").
  1133. Where("`comment`.issue_id = ?", issueID).
  1134. And("`comment`.type = ?", CommentTypeComment).
  1135. And("`user`.is_active = ?", true).
  1136. And("`user`.prohibit_login = ?", false).
  1137. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1138. Distinct("poster_id").
  1139. Find(&userIDs); err != nil {
  1140. return nil, fmt.Errorf("get poster IDs: %v", err)
  1141. }
  1142. if len(userIDs) == 0 {
  1143. return nil, nil
  1144. }
  1145. users := make([]*User, 0, len(userIDs))
  1146. return users, e.In("id", userIDs).Find(&users)
  1147. }
  1148. // UpdateIssueMentions extracts mentioned people from content and
  1149. // updates issue-user relations for them.
  1150. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  1151. if len(mentions) == 0 {
  1152. return nil
  1153. }
  1154. for i := range mentions {
  1155. mentions[i] = strings.ToLower(mentions[i])
  1156. }
  1157. users := make([]*User, 0, len(mentions))
  1158. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  1159. return fmt.Errorf("find mentioned users: %v", err)
  1160. }
  1161. ids := make([]int64, 0, len(mentions))
  1162. for _, user := range users {
  1163. ids = append(ids, user.ID)
  1164. if !user.IsOrganization() || user.NumMembers == 0 {
  1165. continue
  1166. }
  1167. memberIDs := make([]int64, 0, user.NumMembers)
  1168. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  1169. if err != nil {
  1170. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  1171. }
  1172. for _, orgUser := range orgUsers {
  1173. memberIDs = append(memberIDs, orgUser.ID)
  1174. }
  1175. ids = append(ids, memberIDs...)
  1176. }
  1177. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  1178. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1179. }
  1180. return nil
  1181. }
  1182. // IssueStats represents issue statistic information.
  1183. type IssueStats struct {
  1184. OpenCount, ClosedCount int64
  1185. YourRepositoriesCount int64
  1186. AssignCount int64
  1187. CreateCount int64
  1188. MentionCount int64
  1189. }
  1190. // Filter modes.
  1191. const (
  1192. FilterModeAll = iota
  1193. FilterModeAssign
  1194. FilterModeCreate
  1195. FilterModeMention
  1196. )
  1197. func parseCountResult(results []map[string][]byte) int64 {
  1198. if len(results) == 0 {
  1199. return 0
  1200. }
  1201. for _, result := range results[0] {
  1202. return com.StrTo(string(result)).MustInt64()
  1203. }
  1204. return 0
  1205. }
  1206. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1207. type IssueStatsOptions struct {
  1208. RepoID int64
  1209. Labels string
  1210. MilestoneID int64
  1211. AssigneeID int64
  1212. MentionedID int64
  1213. PosterID int64
  1214. IsPull util.OptionalBool
  1215. IssueIDs []int64
  1216. }
  1217. // GetIssueStats returns issue statistic information by given conditions.
  1218. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1219. stats := &IssueStats{}
  1220. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1221. sess := x.
  1222. Where("issue.repo_id = ?", opts.RepoID)
  1223. if len(opts.IssueIDs) > 0 {
  1224. sess.In("issue.id", opts.IssueIDs)
  1225. }
  1226. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1227. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1228. if err != nil {
  1229. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1230. } else if len(labelIDs) > 0 {
  1231. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  1232. In("issue_label.label_id", labelIDs)
  1233. }
  1234. }
  1235. if opts.MilestoneID > 0 {
  1236. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1237. }
  1238. if opts.AssigneeID > 0 {
  1239. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1240. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1241. }
  1242. if opts.PosterID > 0 {
  1243. sess.And("issue.poster_id = ?", opts.PosterID)
  1244. }
  1245. if opts.MentionedID > 0 {
  1246. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1247. And("issue_user.uid = ?", opts.MentionedID).
  1248. And("issue_user.is_mentioned = ?", true)
  1249. }
  1250. switch opts.IsPull {
  1251. case util.OptionalBoolTrue:
  1252. sess.And("issue.is_pull=?", true)
  1253. case util.OptionalBoolFalse:
  1254. sess.And("issue.is_pull=?", false)
  1255. }
  1256. return sess
  1257. }
  1258. var err error
  1259. stats.OpenCount, err = countSession(opts).
  1260. And("issue.is_closed = ?", false).
  1261. Count(new(Issue))
  1262. if err != nil {
  1263. return stats, err
  1264. }
  1265. stats.ClosedCount, err = countSession(opts).
  1266. And("issue.is_closed = ?", true).
  1267. Count(new(Issue))
  1268. return stats, err
  1269. }
  1270. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1271. type UserIssueStatsOptions struct {
  1272. UserID int64
  1273. RepoID int64
  1274. UserRepoIDs []int64
  1275. FilterMode int
  1276. IsPull bool
  1277. IsClosed bool
  1278. }
  1279. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1280. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1281. var err error
  1282. stats := &IssueStats{}
  1283. cond := builder.NewCond()
  1284. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1285. if opts.RepoID > 0 {
  1286. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  1287. }
  1288. switch opts.FilterMode {
  1289. case FilterModeAll:
  1290. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1291. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1292. Count(new(Issue))
  1293. if err != nil {
  1294. return nil, err
  1295. }
  1296. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1297. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1298. Count(new(Issue))
  1299. if err != nil {
  1300. return nil, err
  1301. }
  1302. case FilterModeAssign:
  1303. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1304. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1305. And("issue_assignees.assignee_id = ?", opts.UserID).
  1306. Count(new(Issue))
  1307. if err != nil {
  1308. return nil, err
  1309. }
  1310. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1311. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1312. And("issue_assignees.assignee_id = ?", opts.UserID).
  1313. Count(new(Issue))
  1314. if err != nil {
  1315. return nil, err
  1316. }
  1317. case FilterModeCreate:
  1318. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1319. And("poster_id = ?", opts.UserID).
  1320. Count(new(Issue))
  1321. if err != nil {
  1322. return nil, err
  1323. }
  1324. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1325. And("poster_id = ?", opts.UserID).
  1326. Count(new(Issue))
  1327. if err != nil {
  1328. return nil, err
  1329. }
  1330. }
  1331. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1332. stats.AssignCount, err = x.Where(cond).
  1333. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1334. And("issue_assignees.assignee_id = ?", opts.UserID).
  1335. Count(new(Issue))
  1336. if err != nil {
  1337. return nil, err
  1338. }
  1339. stats.CreateCount, err = x.Where(cond).
  1340. And("poster_id = ?", opts.UserID).
  1341. Count(new(Issue))
  1342. if err != nil {
  1343. return nil, err
  1344. }
  1345. stats.YourRepositoriesCount, err = x.Where(cond).
  1346. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1347. Count(new(Issue))
  1348. if err != nil {
  1349. return nil, err
  1350. }
  1351. return stats, nil
  1352. }
  1353. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1354. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1355. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1356. sess := x.
  1357. Where("is_closed = ?", isClosed).
  1358. And("is_pull = ?", isPull).
  1359. And("repo_id = ?", repoID)
  1360. return sess
  1361. }
  1362. openCountSession := countSession(false, isPull, repoID)
  1363. closedCountSession := countSession(true, isPull, repoID)
  1364. switch filterMode {
  1365. case FilterModeAssign:
  1366. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1367. And("issue_assignees.assignee_id = ?", uid)
  1368. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1369. And("issue_assignees.assignee_id = ?", uid)
  1370. case FilterModeCreate:
  1371. openCountSession.And("poster_id = ?", uid)
  1372. closedCountSession.And("poster_id = ?", uid)
  1373. }
  1374. openResult, _ := openCountSession.Count(new(Issue))
  1375. closedResult, _ := closedCountSession.Count(new(Issue))
  1376. return openResult, closedResult
  1377. }
  1378. func updateIssue(e Engine, issue *Issue) error {
  1379. _, err := e.ID(issue.ID).AllCols().Update(issue)
  1380. if err != nil {
  1381. return err
  1382. }
  1383. UpdateIssueIndexer(issue.ID)
  1384. return nil
  1385. }
  1386. // UpdateIssue updates all fields of given issue.
  1387. func UpdateIssue(issue *Issue) error {
  1388. return updateIssue(x, issue)
  1389. }
  1390. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1391. func UpdateIssueDeadline(issue *Issue, deadlineUnix util.TimeStamp, doer *User) (err error) {
  1392. // if the deadline hasn't changed do nothing
  1393. if issue.DeadlineUnix == deadlineUnix {
  1394. return nil
  1395. }
  1396. sess := x.NewSession()
  1397. defer sess.Close()
  1398. if err := sess.Begin(); err != nil {
  1399. return err
  1400. }
  1401. // Update the deadline
  1402. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1403. return err
  1404. }
  1405. // Make the comment
  1406. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1407. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1408. }
  1409. return sess.Commit()
  1410. }
  1411. // Get Blocked By Dependencies, aka all issues this issue is blocked by.
  1412. func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*Issue, err error) {
  1413. return issueDeps, e.
  1414. Table("issue_dependency").
  1415. Select("issue.*").
  1416. Join("INNER", "issue", "issue.id = issue_dependency.dependency_id").
  1417. Where("issue_id = ?", issue.ID).
  1418. Find(&issueDeps)
  1419. }
  1420. // Get Blocking Dependencies, aka all issues this issue blocks.
  1421. func (issue *Issue) getBlockingDependencies(e Engine) (issueDeps []*Issue, err error) {
  1422. return issueDeps, e.
  1423. Table("issue_dependency").
  1424. Select("issue.*").
  1425. Join("INNER", "issue", "issue.id = issue_dependency.issue_id").
  1426. Where("dependency_id = ?", issue.ID).
  1427. Find(&issueDeps)
  1428. }
  1429. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1430. func (issue *Issue) BlockedByDependencies() ([]*Issue, error) {
  1431. return issue.getBlockedByDependencies(x)
  1432. }
  1433. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
  1434. func (issue *Issue) BlockingDependencies() ([]*Issue, error) {
  1435. return issue.getBlockingDependencies(x)
  1436. }