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