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 37KB

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