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

issue.go 41KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600
  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 err = issue.loadRepo(x); err != nil {
  326. log.Error(4, "loadRepo: %v", err)
  327. return
  328. }
  329. if err = issue.loadPoster(x); err != nil {
  330. log.Error(4, "loadPoster: %v", err)
  331. return
  332. }
  333. mode, _ := AccessLevel(issue.Poster.ID, issue.Repo)
  334. if issue.IsPull {
  335. if err = issue.loadPullRequest(x); err != nil {
  336. log.Error(4, "loadPullRequest: %v", err)
  337. return
  338. }
  339. if err = issue.PullRequest.LoadIssue(); err != nil {
  340. log.Error(4, "LoadIssue: %v", err)
  341. return
  342. }
  343. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  344. Action: api.HookIssueLabelUpdated,
  345. Index: issue.Index,
  346. PullRequest: issue.PullRequest.APIFormat(),
  347. Repository: issue.Repo.APIFormat(AccessModeNone),
  348. Sender: doer.APIFormat(),
  349. })
  350. } else {
  351. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  352. Action: api.HookIssueLabelUpdated,
  353. Index: issue.Index,
  354. Issue: issue.APIFormat(),
  355. Repository: issue.Repo.APIFormat(mode),
  356. Sender: doer.APIFormat(),
  357. })
  358. }
  359. if err != nil {
  360. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  361. } else {
  362. go HookQueue.Add(issue.RepoID)
  363. }
  364. }
  365. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  366. return newIssueLabel(e, issue, label, doer)
  367. }
  368. // AddLabel adds a new label to the issue.
  369. func (issue *Issue) AddLabel(doer *User, label *Label) error {
  370. if err := NewIssueLabel(issue, label, doer); err != nil {
  371. return err
  372. }
  373. issue.sendLabelUpdatedWebhook(doer)
  374. return nil
  375. }
  376. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  377. return newIssueLabels(e, issue, labels, doer)
  378. }
  379. // AddLabels adds a list of new labels to the issue.
  380. func (issue *Issue) AddLabels(doer *User, labels []*Label) error {
  381. if err := NewIssueLabels(issue, labels, doer); err != nil {
  382. return err
  383. }
  384. issue.sendLabelUpdatedWebhook(doer)
  385. return nil
  386. }
  387. func (issue *Issue) getLabels(e Engine) (err error) {
  388. if len(issue.Labels) > 0 {
  389. return nil
  390. }
  391. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  392. if err != nil {
  393. return fmt.Errorf("getLabelsByIssueID: %v", err)
  394. }
  395. return nil
  396. }
  397. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  398. return deleteIssueLabel(e, issue, label, doer)
  399. }
  400. // RemoveLabel removes a label from issue by given ID.
  401. func (issue *Issue) RemoveLabel(doer *User, label *Label) error {
  402. if err := issue.loadRepo(x); err != nil {
  403. return err
  404. }
  405. if has, err := HasAccess(doer.ID, issue.Repo, AccessModeWrite); err != nil {
  406. return err
  407. } else if !has {
  408. return ErrLabelNotExist{}
  409. }
  410. if err := DeleteIssueLabel(issue, label, doer); err != nil {
  411. return err
  412. }
  413. issue.sendLabelUpdatedWebhook(doer)
  414. return nil
  415. }
  416. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  417. if err = issue.getLabels(e); err != nil {
  418. return fmt.Errorf("getLabels: %v", err)
  419. }
  420. for i := range issue.Labels {
  421. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  422. return fmt.Errorf("removeLabel: %v", err)
  423. }
  424. }
  425. return nil
  426. }
  427. // ClearLabels removes all issue labels as the given user.
  428. // Triggers appropriate WebHooks, if any.
  429. func (issue *Issue) ClearLabels(doer *User) (err error) {
  430. sess := x.NewSession()
  431. defer sess.Close()
  432. if err = sess.Begin(); err != nil {
  433. return err
  434. }
  435. if err := issue.loadRepo(sess); err != nil {
  436. return err
  437. } else if err = issue.loadPullRequest(sess); err != nil {
  438. return err
  439. }
  440. if has, err := hasAccess(sess, doer.ID, issue.Repo, AccessModeWrite); err != nil {
  441. return err
  442. } else if !has {
  443. return ErrLabelNotExist{}
  444. }
  445. if err = issue.clearLabels(sess, doer); err != nil {
  446. return err
  447. }
  448. if err = sess.Commit(); err != nil {
  449. return fmt.Errorf("Commit: %v", err)
  450. }
  451. if err = issue.loadPoster(x); err != nil {
  452. return fmt.Errorf("loadPoster: %v", err)
  453. }
  454. mode, _ := AccessLevel(issue.Poster.ID, issue.Repo)
  455. if issue.IsPull {
  456. err = issue.PullRequest.LoadIssue()
  457. if err != nil {
  458. log.Error(4, "LoadIssue: %v", err)
  459. return
  460. }
  461. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  462. Action: api.HookIssueLabelCleared,
  463. Index: issue.Index,
  464. PullRequest: issue.PullRequest.APIFormat(),
  465. Repository: issue.Repo.APIFormat(mode),
  466. Sender: doer.APIFormat(),
  467. })
  468. } else {
  469. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  470. Action: api.HookIssueLabelCleared,
  471. Index: issue.Index,
  472. Issue: issue.APIFormat(),
  473. Repository: issue.Repo.APIFormat(mode),
  474. Sender: doer.APIFormat(),
  475. })
  476. }
  477. if err != nil {
  478. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  479. } else {
  480. go HookQueue.Add(issue.RepoID)
  481. }
  482. return nil
  483. }
  484. type labelSorter []*Label
  485. func (ts labelSorter) Len() int {
  486. return len([]*Label(ts))
  487. }
  488. func (ts labelSorter) Less(i, j int) bool {
  489. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  490. }
  491. func (ts labelSorter) Swap(i, j int) {
  492. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  493. }
  494. // ReplaceLabels removes all current labels and add new labels to the issue.
  495. // Triggers appropriate WebHooks, if any.
  496. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  497. sess := x.NewSession()
  498. defer sess.Close()
  499. if err = sess.Begin(); err != nil {
  500. return err
  501. }
  502. if err = issue.loadLabels(sess); err != nil {
  503. return err
  504. }
  505. sort.Sort(labelSorter(labels))
  506. sort.Sort(labelSorter(issue.Labels))
  507. var toAdd, toRemove []*Label
  508. addIndex, removeIndex := 0, 0
  509. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  510. addLabel := labels[addIndex]
  511. removeLabel := issue.Labels[removeIndex]
  512. if addLabel.ID == removeLabel.ID {
  513. addIndex++
  514. removeIndex++
  515. } else if addLabel.ID < removeLabel.ID {
  516. toAdd = append(toAdd, addLabel)
  517. addIndex++
  518. } else {
  519. toRemove = append(toRemove, removeLabel)
  520. removeIndex++
  521. }
  522. }
  523. toAdd = append(toAdd, labels[addIndex:]...)
  524. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  525. if len(toAdd) > 0 {
  526. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  527. return fmt.Errorf("addLabels: %v", err)
  528. }
  529. }
  530. for _, l := range toRemove {
  531. if err = issue.removeLabel(sess, doer, l); err != nil {
  532. return fmt.Errorf("removeLabel: %v", err)
  533. }
  534. }
  535. return sess.Commit()
  536. }
  537. // ReadBy sets issue to be read by given user.
  538. func (issue *Issue) ReadBy(userID int64) error {
  539. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  540. return err
  541. }
  542. return setNotificationStatusReadIfUnread(x, userID, issue.ID)
  543. }
  544. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  545. if _, err := e.ID(issue.ID).Cols(cols...).Update(issue); err != nil {
  546. return err
  547. }
  548. UpdateIssueIndexerCols(issue.ID, cols...)
  549. return nil
  550. }
  551. // UpdateIssueCols only updates values of specific columns for given issue.
  552. func UpdateIssueCols(issue *Issue, cols ...string) error {
  553. return updateIssueCols(x, issue, cols...)
  554. }
  555. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
  556. // Nothing should be performed if current status is same as target status
  557. if issue.IsClosed == isClosed {
  558. return nil
  559. }
  560. issue.IsClosed = isClosed
  561. if isClosed {
  562. issue.ClosedUnix = util.TimeStampNow()
  563. } else {
  564. issue.ClosedUnix = 0
  565. }
  566. if err = updateIssueCols(e, issue, "is_closed", "closed_unix"); err != nil {
  567. return err
  568. }
  569. // Update issue count of labels
  570. if err = issue.getLabels(e); err != nil {
  571. return err
  572. }
  573. for idx := range issue.Labels {
  574. if issue.IsClosed {
  575. issue.Labels[idx].NumClosedIssues++
  576. } else {
  577. issue.Labels[idx].NumClosedIssues--
  578. }
  579. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  580. return err
  581. }
  582. }
  583. // Update issue count of milestone
  584. if err = changeMilestoneIssueStats(e, issue); err != nil {
  585. return err
  586. }
  587. // New action comment
  588. if _, err = createStatusComment(e, doer, repo, issue); err != nil {
  589. return err
  590. }
  591. return nil
  592. }
  593. // ChangeStatus changes issue status to open or closed.
  594. func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (err error) {
  595. sess := x.NewSession()
  596. defer sess.Close()
  597. if err = sess.Begin(); err != nil {
  598. return err
  599. }
  600. if err = issue.changeStatus(sess, doer, repo, isClosed); err != nil {
  601. return err
  602. }
  603. if err = sess.Commit(); err != nil {
  604. return fmt.Errorf("Commit: %v", err)
  605. }
  606. mode, _ := AccessLevel(issue.Poster.ID, issue.Repo)
  607. if issue.IsPull {
  608. // Merge pull request calls issue.changeStatus so we need to handle separately.
  609. issue.PullRequest.Issue = issue
  610. apiPullRequest := &api.PullRequestPayload{
  611. Index: issue.Index,
  612. PullRequest: issue.PullRequest.APIFormat(),
  613. Repository: repo.APIFormat(mode),
  614. Sender: doer.APIFormat(),
  615. }
  616. if isClosed {
  617. apiPullRequest.Action = api.HookIssueClosed
  618. } else {
  619. apiPullRequest.Action = api.HookIssueReOpened
  620. }
  621. err = PrepareWebhooks(repo, HookEventPullRequest, apiPullRequest)
  622. } else {
  623. apiIssue := &api.IssuePayload{
  624. Index: issue.Index,
  625. Issue: issue.APIFormat(),
  626. Repository: repo.APIFormat(mode),
  627. Sender: doer.APIFormat(),
  628. }
  629. if isClosed {
  630. apiIssue.Action = api.HookIssueClosed
  631. } else {
  632. apiIssue.Action = api.HookIssueReOpened
  633. }
  634. err = PrepareWebhooks(repo, HookEventIssues, apiIssue)
  635. }
  636. if err != nil {
  637. log.Error(4, "PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  638. } else {
  639. go HookQueue.Add(repo.ID)
  640. }
  641. return nil
  642. }
  643. // ChangeTitle changes the title of this issue, as the given user.
  644. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
  645. oldTitle := issue.Title
  646. issue.Title = title
  647. sess := x.NewSession()
  648. defer sess.Close()
  649. if err = sess.Begin(); err != nil {
  650. return err
  651. }
  652. if err = updateIssueCols(sess, issue, "name"); err != nil {
  653. return fmt.Errorf("updateIssueCols: %v", err)
  654. }
  655. if _, err = createChangeTitleComment(sess, doer, issue.Repo, issue, oldTitle, title); err != nil {
  656. return fmt.Errorf("createChangeTitleComment: %v", err)
  657. }
  658. if err = sess.Commit(); err != nil {
  659. return err
  660. }
  661. mode, _ := AccessLevel(issue.Poster.ID, issue.Repo)
  662. if issue.IsPull {
  663. issue.PullRequest.Issue = issue
  664. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  665. Action: api.HookIssueEdited,
  666. Index: issue.Index,
  667. Changes: &api.ChangesPayload{
  668. Title: &api.ChangesFromPayload{
  669. From: oldTitle,
  670. },
  671. },
  672. PullRequest: issue.PullRequest.APIFormat(),
  673. Repository: issue.Repo.APIFormat(mode),
  674. Sender: doer.APIFormat(),
  675. })
  676. } else {
  677. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  678. Action: api.HookIssueEdited,
  679. Index: issue.Index,
  680. Changes: &api.ChangesPayload{
  681. Title: &api.ChangesFromPayload{
  682. From: oldTitle,
  683. },
  684. },
  685. Issue: issue.APIFormat(),
  686. Repository: issue.Repo.APIFormat(mode),
  687. Sender: issue.Poster.APIFormat(),
  688. })
  689. }
  690. if err != nil {
  691. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  692. } else {
  693. go HookQueue.Add(issue.RepoID)
  694. }
  695. return nil
  696. }
  697. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  698. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  699. issue, err := getIssueByID(x, issueID)
  700. if err != nil {
  701. return err
  702. }
  703. sess := x.NewSession()
  704. defer sess.Close()
  705. if err := sess.Begin(); err != nil {
  706. return err
  707. }
  708. if _, err := createDeleteBranchComment(sess, doer, repo, issue, branchName); err != nil {
  709. return err
  710. }
  711. return sess.Commit()
  712. }
  713. // ChangeContent changes issue content, as the given user.
  714. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  715. oldContent := issue.Content
  716. issue.Content = content
  717. if err = UpdateIssueCols(issue, "content"); err != nil {
  718. return fmt.Errorf("UpdateIssueCols: %v", err)
  719. }
  720. mode, _ := AccessLevel(issue.Poster.ID, issue.Repo)
  721. if issue.IsPull {
  722. issue.PullRequest.Issue = issue
  723. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  724. Action: api.HookIssueEdited,
  725. Index: issue.Index,
  726. Changes: &api.ChangesPayload{
  727. Body: &api.ChangesFromPayload{
  728. From: oldContent,
  729. },
  730. },
  731. PullRequest: issue.PullRequest.APIFormat(),
  732. Repository: issue.Repo.APIFormat(mode),
  733. Sender: doer.APIFormat(),
  734. })
  735. } else {
  736. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  737. Action: api.HookIssueEdited,
  738. Index: issue.Index,
  739. Changes: &api.ChangesPayload{
  740. Body: &api.ChangesFromPayload{
  741. From: oldContent,
  742. },
  743. },
  744. Issue: issue.APIFormat(),
  745. Repository: issue.Repo.APIFormat(mode),
  746. Sender: doer.APIFormat(),
  747. })
  748. }
  749. if err != nil {
  750. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  751. } else {
  752. go HookQueue.Add(issue.RepoID)
  753. }
  754. return nil
  755. }
  756. // GetTasks returns the amount of tasks in the issues content
  757. func (issue *Issue) GetTasks() int {
  758. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  759. }
  760. // GetTasksDone returns the amount of completed tasks in the issues content
  761. func (issue *Issue) GetTasksDone() int {
  762. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  763. }
  764. // NewIssueOptions represents the options of a new issue.
  765. type NewIssueOptions struct {
  766. Repo *Repository
  767. Issue *Issue
  768. LabelIDs []int64
  769. AssigneeIDs []int64
  770. Attachments []string // In UUID format.
  771. IsPull bool
  772. }
  773. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  774. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  775. opts.Issue.Index = opts.Repo.NextIssueIndex()
  776. if opts.Issue.MilestoneID > 0 {
  777. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  778. if err != nil && !IsErrMilestoneNotExist(err) {
  779. return fmt.Errorf("getMilestoneByID: %v", err)
  780. }
  781. // Assume milestone is invalid and drop silently.
  782. opts.Issue.MilestoneID = 0
  783. if milestone != nil {
  784. opts.Issue.MilestoneID = milestone.ID
  785. opts.Issue.Milestone = milestone
  786. }
  787. }
  788. // Keep the old assignee id thingy for compatibility reasons
  789. if opts.Issue.AssigneeID > 0 {
  790. isAdded := false
  791. // Check if the user has already been passed to issue.AssigneeIDs, if not, add it
  792. for _, aID := range opts.AssigneeIDs {
  793. if aID == opts.Issue.AssigneeID {
  794. isAdded = true
  795. break
  796. }
  797. }
  798. if !isAdded {
  799. opts.AssigneeIDs = append(opts.AssigneeIDs, opts.Issue.AssigneeID)
  800. }
  801. }
  802. // Check for and validate assignees
  803. if len(opts.AssigneeIDs) > 0 {
  804. for _, assigneeID := range opts.AssigneeIDs {
  805. valid, err := hasAccess(e, assigneeID, opts.Repo, AccessModeWrite)
  806. if err != nil {
  807. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  808. }
  809. if !valid {
  810. return ErrUserDoesNotHaveAccessToRepo{UserID: assigneeID, RepoName: opts.Repo.Name}
  811. }
  812. }
  813. }
  814. // Milestone and assignee validation should happen before insert actual object.
  815. if _, err = e.Insert(opts.Issue); err != nil {
  816. return err
  817. }
  818. if opts.Issue.MilestoneID > 0 {
  819. if err = changeMilestoneAssign(e, doer, opts.Issue, -1); err != nil {
  820. return err
  821. }
  822. }
  823. // Insert the assignees
  824. for _, assigneeID := range opts.AssigneeIDs {
  825. err = opts.Issue.changeAssignee(e, doer, assigneeID)
  826. if err != nil {
  827. return err
  828. }
  829. }
  830. if opts.IsPull {
  831. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  832. } else {
  833. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  834. }
  835. if err != nil {
  836. return err
  837. }
  838. if len(opts.LabelIDs) > 0 {
  839. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  840. // So we have to get all needed labels first.
  841. labels := make([]*Label, 0, len(opts.LabelIDs))
  842. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  843. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  844. }
  845. if err = opts.Issue.loadPoster(e); err != nil {
  846. return err
  847. }
  848. for _, label := range labels {
  849. // Silently drop invalid labels.
  850. if label.RepoID != opts.Repo.ID {
  851. continue
  852. }
  853. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  854. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  855. }
  856. }
  857. }
  858. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  859. return err
  860. }
  861. if len(opts.Attachments) > 0 {
  862. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  863. if err != nil {
  864. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  865. }
  866. for i := 0; i < len(attachments); i++ {
  867. attachments[i].IssueID = opts.Issue.ID
  868. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  869. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  870. }
  871. }
  872. }
  873. return opts.Issue.loadAttributes(e)
  874. }
  875. // NewIssue creates new issue with labels for repository.
  876. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, assigneeIDs []int64, uuids []string) (err error) {
  877. sess := x.NewSession()
  878. defer sess.Close()
  879. if err = sess.Begin(); err != nil {
  880. return err
  881. }
  882. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  883. Repo: repo,
  884. Issue: issue,
  885. LabelIDs: labelIDs,
  886. Attachments: uuids,
  887. AssigneeIDs: assigneeIDs,
  888. }); err != nil {
  889. if IsErrUserDoesNotHaveAccessToRepo(err) {
  890. return err
  891. }
  892. return fmt.Errorf("newIssue: %v", err)
  893. }
  894. if err = sess.Commit(); err != nil {
  895. return fmt.Errorf("Commit: %v", err)
  896. }
  897. UpdateIssueIndexer(issue.ID)
  898. if err = NotifyWatchers(&Action{
  899. ActUserID: issue.Poster.ID,
  900. ActUser: issue.Poster,
  901. OpType: ActionCreateIssue,
  902. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  903. RepoID: repo.ID,
  904. Repo: repo,
  905. IsPrivate: repo.IsPrivate,
  906. }); err != nil {
  907. log.Error(4, "NotifyWatchers: %v", err)
  908. }
  909. if err = issue.MailParticipants(); err != nil {
  910. log.Error(4, "MailParticipants: %v", err)
  911. }
  912. mode, _ := AccessLevel(issue.Poster.ID, issue.Repo)
  913. if err = PrepareWebhooks(repo, HookEventIssues, &api.IssuePayload{
  914. Action: api.HookIssueOpened,
  915. Index: issue.Index,
  916. Issue: issue.APIFormat(),
  917. Repository: repo.APIFormat(mode),
  918. Sender: issue.Poster.APIFormat(),
  919. }); err != nil {
  920. log.Error(4, "PrepareWebhooks: %v", err)
  921. } else {
  922. go HookQueue.Add(issue.RepoID)
  923. }
  924. return nil
  925. }
  926. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  927. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  928. issue := &Issue{
  929. RepoID: repoID,
  930. Index: index,
  931. }
  932. has, err := x.Get(issue)
  933. if err != nil {
  934. return nil, err
  935. } else if !has {
  936. return nil, ErrIssueNotExist{0, repoID, index}
  937. }
  938. return issue, nil
  939. }
  940. // GetIssueByIndex returns issue by index in a repository.
  941. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  942. issue, err := GetRawIssueByIndex(repoID, index)
  943. if err != nil {
  944. return nil, err
  945. }
  946. return issue, issue.LoadAttributes()
  947. }
  948. func getIssueByID(e Engine, id int64) (*Issue, error) {
  949. issue := new(Issue)
  950. has, err := e.ID(id).Get(issue)
  951. if err != nil {
  952. return nil, err
  953. } else if !has {
  954. return nil, ErrIssueNotExist{id, 0, 0}
  955. }
  956. return issue, issue.loadAttributes(e)
  957. }
  958. // GetIssueByID returns an issue by given ID.
  959. func GetIssueByID(id int64) (*Issue, error) {
  960. return getIssueByID(x, id)
  961. }
  962. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  963. issues := make([]*Issue, 0, 10)
  964. return issues, e.In("id", issueIDs).Find(&issues)
  965. }
  966. // GetIssuesByIDs return issues with the given IDs.
  967. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  968. return getIssuesByIDs(x, issueIDs)
  969. }
  970. // IssuesOptions represents options of an issue.
  971. type IssuesOptions struct {
  972. RepoIDs []int64 // include all repos if empty
  973. AssigneeID int64
  974. PosterID int64
  975. MentionedID int64
  976. MilestoneID int64
  977. Page int
  978. PageSize int
  979. IsClosed util.OptionalBool
  980. IsPull util.OptionalBool
  981. Labels string
  982. SortType string
  983. IssueIDs []int64
  984. }
  985. // sortIssuesSession sort an issues-related session based on the provided
  986. // sortType string
  987. func sortIssuesSession(sess *xorm.Session, sortType string) {
  988. switch sortType {
  989. case "oldest":
  990. sess.Asc("issue.created_unix")
  991. case "recentupdate":
  992. sess.Desc("issue.updated_unix")
  993. case "leastupdate":
  994. sess.Asc("issue.updated_unix")
  995. case "mostcomment":
  996. sess.Desc("issue.num_comments")
  997. case "leastcomment":
  998. sess.Asc("issue.num_comments")
  999. case "priority":
  1000. sess.Desc("issue.priority")
  1001. default:
  1002. sess.Desc("issue.created_unix")
  1003. }
  1004. }
  1005. func (opts *IssuesOptions) setupSession(sess *xorm.Session) error {
  1006. if opts.Page >= 0 && opts.PageSize > 0 {
  1007. var start int
  1008. if opts.Page == 0 {
  1009. start = 0
  1010. } else {
  1011. start = (opts.Page - 1) * opts.PageSize
  1012. }
  1013. sess.Limit(opts.PageSize, start)
  1014. }
  1015. if len(opts.IssueIDs) > 0 {
  1016. sess.In("issue.id", opts.IssueIDs)
  1017. }
  1018. if len(opts.RepoIDs) > 0 {
  1019. // In case repository IDs are provided but actually no repository has issue.
  1020. sess.In("issue.repo_id", opts.RepoIDs)
  1021. }
  1022. switch opts.IsClosed {
  1023. case util.OptionalBoolTrue:
  1024. sess.And("issue.is_closed=?", true)
  1025. case util.OptionalBoolFalse:
  1026. sess.And("issue.is_closed=?", false)
  1027. }
  1028. if opts.AssigneeID > 0 {
  1029. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1030. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1031. }
  1032. if opts.PosterID > 0 {
  1033. sess.And("issue.poster_id=?", opts.PosterID)
  1034. }
  1035. if opts.MentionedID > 0 {
  1036. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1037. And("issue_user.is_mentioned = ?", true).
  1038. And("issue_user.uid = ?", opts.MentionedID)
  1039. }
  1040. if opts.MilestoneID > 0 {
  1041. sess.And("issue.milestone_id=?", opts.MilestoneID)
  1042. }
  1043. switch opts.IsPull {
  1044. case util.OptionalBoolTrue:
  1045. sess.And("issue.is_pull=?", true)
  1046. case util.OptionalBoolFalse:
  1047. sess.And("issue.is_pull=?", false)
  1048. }
  1049. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1050. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1051. if err != nil {
  1052. return err
  1053. }
  1054. if len(labelIDs) > 0 {
  1055. sess.
  1056. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  1057. In("issue_label.label_id", labelIDs)
  1058. }
  1059. }
  1060. return nil
  1061. }
  1062. // CountIssuesByRepo map from repoID to number of issues matching the options
  1063. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1064. sess := x.NewSession()
  1065. defer sess.Close()
  1066. if err := opts.setupSession(sess); err != nil {
  1067. return nil, err
  1068. }
  1069. countsSlice := make([]*struct {
  1070. RepoID int64
  1071. Count int64
  1072. }, 0, 10)
  1073. if err := sess.GroupBy("issue.repo_id").
  1074. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1075. Table("issue").
  1076. Find(&countsSlice); err != nil {
  1077. return nil, err
  1078. }
  1079. countMap := make(map[int64]int64, len(countsSlice))
  1080. for _, c := range countsSlice {
  1081. countMap[c.RepoID] = c.Count
  1082. }
  1083. return countMap, nil
  1084. }
  1085. // Issues returns a list of issues by given conditions.
  1086. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1087. sess := x.NewSession()
  1088. defer sess.Close()
  1089. if err := opts.setupSession(sess); err != nil {
  1090. return nil, err
  1091. }
  1092. sortIssuesSession(sess, opts.SortType)
  1093. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1094. if err := sess.Find(&issues); err != nil {
  1095. return nil, fmt.Errorf("Find: %v", err)
  1096. }
  1097. if err := IssueList(issues).LoadAttributes(); err != nil {
  1098. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1099. }
  1100. return issues, nil
  1101. }
  1102. // GetParticipantsByIssueID returns all users who are participated in comments of an issue.
  1103. func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
  1104. return getParticipantsByIssueID(x, issueID)
  1105. }
  1106. func getParticipantsByIssueID(e Engine, issueID int64) ([]*User, error) {
  1107. userIDs := make([]int64, 0, 5)
  1108. if err := e.Table("comment").Cols("poster_id").
  1109. Where("`comment`.issue_id = ?", issueID).
  1110. And("`comment`.type = ?", CommentTypeComment).
  1111. And("`user`.is_active = ?", true).
  1112. And("`user`.prohibit_login = ?", false).
  1113. Join("INNER", "user", "`user`.id = `comment`.poster_id").
  1114. Distinct("poster_id").
  1115. Find(&userIDs); err != nil {
  1116. return nil, fmt.Errorf("get poster IDs: %v", err)
  1117. }
  1118. if len(userIDs) == 0 {
  1119. return nil, nil
  1120. }
  1121. users := make([]*User, 0, len(userIDs))
  1122. return users, e.In("id", userIDs).Find(&users)
  1123. }
  1124. // UpdateIssueMentions extracts mentioned people from content and
  1125. // updates issue-user relations for them.
  1126. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  1127. if len(mentions) == 0 {
  1128. return nil
  1129. }
  1130. for i := range mentions {
  1131. mentions[i] = strings.ToLower(mentions[i])
  1132. }
  1133. users := make([]*User, 0, len(mentions))
  1134. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  1135. return fmt.Errorf("find mentioned users: %v", err)
  1136. }
  1137. ids := make([]int64, 0, len(mentions))
  1138. for _, user := range users {
  1139. ids = append(ids, user.ID)
  1140. if !user.IsOrganization() || user.NumMembers == 0 {
  1141. continue
  1142. }
  1143. memberIDs := make([]int64, 0, user.NumMembers)
  1144. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  1145. if err != nil {
  1146. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  1147. }
  1148. for _, orgUser := range orgUsers {
  1149. memberIDs = append(memberIDs, orgUser.ID)
  1150. }
  1151. ids = append(ids, memberIDs...)
  1152. }
  1153. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  1154. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1155. }
  1156. return nil
  1157. }
  1158. // IssueStats represents issue statistic information.
  1159. type IssueStats struct {
  1160. OpenCount, ClosedCount int64
  1161. YourRepositoriesCount int64
  1162. AssignCount int64
  1163. CreateCount int64
  1164. MentionCount int64
  1165. }
  1166. // Filter modes.
  1167. const (
  1168. FilterModeAll = iota
  1169. FilterModeAssign
  1170. FilterModeCreate
  1171. FilterModeMention
  1172. )
  1173. func parseCountResult(results []map[string][]byte) int64 {
  1174. if len(results) == 0 {
  1175. return 0
  1176. }
  1177. for _, result := range results[0] {
  1178. return com.StrTo(string(result)).MustInt64()
  1179. }
  1180. return 0
  1181. }
  1182. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1183. type IssueStatsOptions struct {
  1184. RepoID int64
  1185. Labels string
  1186. MilestoneID int64
  1187. AssigneeID int64
  1188. MentionedID int64
  1189. PosterID int64
  1190. IsPull bool
  1191. IssueIDs []int64
  1192. }
  1193. // GetIssueStats returns issue statistic information by given conditions.
  1194. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1195. stats := &IssueStats{}
  1196. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1197. sess := x.
  1198. Where("issue.repo_id = ?", opts.RepoID).
  1199. And("issue.is_pull = ?", opts.IsPull)
  1200. if len(opts.IssueIDs) > 0 {
  1201. sess.In("issue.id", opts.IssueIDs)
  1202. }
  1203. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1204. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1205. if err != nil {
  1206. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1207. } else if len(labelIDs) > 0 {
  1208. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  1209. In("issue_label.label_id", labelIDs)
  1210. }
  1211. }
  1212. if opts.MilestoneID > 0 {
  1213. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1214. }
  1215. if opts.AssigneeID > 0 {
  1216. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1217. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1218. }
  1219. if opts.PosterID > 0 {
  1220. sess.And("issue.poster_id = ?", opts.PosterID)
  1221. }
  1222. if opts.MentionedID > 0 {
  1223. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1224. And("issue_user.uid = ?", opts.MentionedID).
  1225. And("issue_user.is_mentioned = ?", true)
  1226. }
  1227. return sess
  1228. }
  1229. var err error
  1230. stats.OpenCount, err = countSession(opts).
  1231. And("issue.is_closed = ?", false).
  1232. Count(new(Issue))
  1233. if err != nil {
  1234. return stats, err
  1235. }
  1236. stats.ClosedCount, err = countSession(opts).
  1237. And("issue.is_closed = ?", true).
  1238. Count(new(Issue))
  1239. return stats, err
  1240. }
  1241. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1242. type UserIssueStatsOptions struct {
  1243. UserID int64
  1244. RepoID int64
  1245. UserRepoIDs []int64
  1246. FilterMode int
  1247. IsPull bool
  1248. IsClosed bool
  1249. }
  1250. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1251. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1252. var err error
  1253. stats := &IssueStats{}
  1254. cond := builder.NewCond()
  1255. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1256. if opts.RepoID > 0 {
  1257. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  1258. }
  1259. switch opts.FilterMode {
  1260. case FilterModeAll:
  1261. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1262. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1263. Count(new(Issue))
  1264. if err != nil {
  1265. return nil, err
  1266. }
  1267. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1268. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1269. Count(new(Issue))
  1270. if err != nil {
  1271. return nil, err
  1272. }
  1273. case FilterModeAssign:
  1274. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1275. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1276. And("issue_assignees.assignee_id = ?", opts.UserID).
  1277. Count(new(Issue))
  1278. if err != nil {
  1279. return nil, err
  1280. }
  1281. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1282. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1283. And("issue_assignees.assignee_id = ?", opts.UserID).
  1284. Count(new(Issue))
  1285. if err != nil {
  1286. return nil, err
  1287. }
  1288. case FilterModeCreate:
  1289. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1290. And("poster_id = ?", opts.UserID).
  1291. Count(new(Issue))
  1292. if err != nil {
  1293. return nil, err
  1294. }
  1295. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1296. And("poster_id = ?", opts.UserID).
  1297. Count(new(Issue))
  1298. if err != nil {
  1299. return nil, err
  1300. }
  1301. }
  1302. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1303. stats.AssignCount, err = x.Where(cond).
  1304. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1305. And("issue_assignees.assignee_id = ?", opts.UserID).
  1306. Count(new(Issue))
  1307. if err != nil {
  1308. return nil, err
  1309. }
  1310. stats.CreateCount, err = x.Where(cond).
  1311. And("poster_id = ?", opts.UserID).
  1312. Count(new(Issue))
  1313. if err != nil {
  1314. return nil, err
  1315. }
  1316. stats.YourRepositoriesCount, err = x.Where(cond).
  1317. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1318. Count(new(Issue))
  1319. if err != nil {
  1320. return nil, err
  1321. }
  1322. return stats, nil
  1323. }
  1324. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1325. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1326. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1327. sess := x.
  1328. Where("is_closed = ?", isClosed).
  1329. And("is_pull = ?", isPull).
  1330. And("repo_id = ?", repoID)
  1331. return sess
  1332. }
  1333. openCountSession := countSession(false, isPull, repoID)
  1334. closedCountSession := countSession(true, isPull, repoID)
  1335. switch filterMode {
  1336. case FilterModeAssign:
  1337. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1338. And("issue_assignees.assignee_id = ?", uid)
  1339. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1340. And("issue_assignees.assignee_id = ?", uid)
  1341. case FilterModeCreate:
  1342. openCountSession.And("poster_id = ?", uid)
  1343. closedCountSession.And("poster_id = ?", uid)
  1344. }
  1345. openResult, _ := openCountSession.Count(new(Issue))
  1346. closedResult, _ := closedCountSession.Count(new(Issue))
  1347. return openResult, closedResult
  1348. }
  1349. func updateIssue(e Engine, issue *Issue) error {
  1350. _, err := e.ID(issue.ID).AllCols().Update(issue)
  1351. if err != nil {
  1352. return err
  1353. }
  1354. UpdateIssueIndexer(issue.ID)
  1355. return nil
  1356. }
  1357. // UpdateIssue updates all fields of given issue.
  1358. func UpdateIssue(issue *Issue) error {
  1359. return updateIssue(x, issue)
  1360. }
  1361. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1362. func UpdateIssueDeadline(issue *Issue, deadlineUnix util.TimeStamp, doer *User) (err error) {
  1363. // if the deadline hasn't changed do nothing
  1364. if issue.DeadlineUnix == deadlineUnix {
  1365. return nil
  1366. }
  1367. sess := x.NewSession()
  1368. defer sess.Close()
  1369. if err := sess.Begin(); err != nil {
  1370. return err
  1371. }
  1372. // Update the deadline
  1373. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1374. return err
  1375. }
  1376. // Make the comment
  1377. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1378. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1379. }
  1380. return sess.Commit()
  1381. }