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