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

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