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.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  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 = findComments(e, FindCommentsOptions{
  154. IssueID: issue.ID,
  155. Type: CommentTypeUnknown,
  156. })
  157. if err != nil {
  158. return fmt.Errorf("getCommentsByIssueID [%d]: %v", issue.ID, err)
  159. }
  160. }
  161. return nil
  162. }
  163. // LoadAttributes loads the attribute of this issue.
  164. func (issue *Issue) LoadAttributes() error {
  165. return issue.loadAttributes(x)
  166. }
  167. // GetIsRead load the `IsRead` field of the issue
  168. func (issue *Issue) GetIsRead(userID int64) error {
  169. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  170. if has, err := x.Get(issueUser); err != nil {
  171. return err
  172. } else if !has {
  173. issue.IsRead = false
  174. return nil
  175. }
  176. issue.IsRead = issueUser.IsRead
  177. return nil
  178. }
  179. // APIURL returns the absolute APIURL to this issue.
  180. func (issue *Issue) APIURL() string {
  181. return issue.Repo.APIURL() + "/" + path.Join("issues", fmt.Sprint(issue.ID))
  182. }
  183. // HTMLURL returns the absolute URL to this issue.
  184. func (issue *Issue) HTMLURL() string {
  185. var path string
  186. if issue.IsPull {
  187. path = "pulls"
  188. } else {
  189. path = "issues"
  190. }
  191. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  192. }
  193. // DiffURL returns the absolute URL to this diff
  194. func (issue *Issue) DiffURL() string {
  195. if issue.IsPull {
  196. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  197. }
  198. return ""
  199. }
  200. // PatchURL returns the absolute URL to this patch
  201. func (issue *Issue) PatchURL() string {
  202. if issue.IsPull {
  203. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  204. }
  205. return ""
  206. }
  207. // State returns string representation of issue status.
  208. func (issue *Issue) State() api.StateType {
  209. if issue.IsClosed {
  210. return api.StateClosed
  211. }
  212. return api.StateOpen
  213. }
  214. // APIFormat assumes some fields assigned with values:
  215. // Required - Poster, Labels,
  216. // Optional - Milestone, Assignee, PullRequest
  217. func (issue *Issue) APIFormat() *api.Issue {
  218. apiLabels := make([]*api.Label, len(issue.Labels))
  219. for i := range issue.Labels {
  220. apiLabels[i] = issue.Labels[i].APIFormat()
  221. }
  222. apiIssue := &api.Issue{
  223. ID: issue.ID,
  224. URL: issue.APIURL(),
  225. Index: issue.Index,
  226. Poster: issue.Poster.APIFormat(),
  227. Title: issue.Title,
  228. Body: issue.Content,
  229. Labels: apiLabels,
  230. State: issue.State(),
  231. Comments: issue.NumComments,
  232. Created: issue.Created,
  233. Updated: issue.Updated,
  234. }
  235. if issue.Milestone != nil {
  236. apiIssue.Milestone = issue.Milestone.APIFormat()
  237. }
  238. if issue.Assignee != nil {
  239. apiIssue.Assignee = issue.Assignee.APIFormat()
  240. }
  241. if issue.IsPull {
  242. apiIssue.PullRequest = &api.PullRequestMeta{
  243. HasMerged: issue.PullRequest.HasMerged,
  244. }
  245. if issue.PullRequest.HasMerged {
  246. apiIssue.PullRequest.Merged = &issue.PullRequest.Merged
  247. }
  248. }
  249. return apiIssue
  250. }
  251. // HashTag returns unique hash tag for issue.
  252. func (issue *Issue) HashTag() string {
  253. return "issue-" + com.ToStr(issue.ID)
  254. }
  255. // IsPoster returns true if given user by ID is the poster.
  256. func (issue *Issue) IsPoster(uid int64) bool {
  257. return issue.PosterID == uid
  258. }
  259. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  260. return hasIssueLabel(e, issue.ID, labelID)
  261. }
  262. // HasLabel returns true if issue has been labeled by given ID.
  263. func (issue *Issue) HasLabel(labelID int64) bool {
  264. return issue.hasLabel(x, labelID)
  265. }
  266. func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
  267. var err error
  268. if issue.IsPull {
  269. err = issue.PullRequest.LoadIssue()
  270. if err != nil {
  271. log.Error(4, "LoadIssue: %v", err)
  272. return
  273. }
  274. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  275. Action: api.HookIssueLabelUpdated,
  276. Index: issue.Index,
  277. PullRequest: issue.PullRequest.APIFormat(),
  278. Repository: issue.Repo.APIFormat(AccessModeNone),
  279. Sender: doer.APIFormat(),
  280. })
  281. }
  282. if err != nil {
  283. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  284. } else {
  285. go HookQueue.Add(issue.RepoID)
  286. }
  287. }
  288. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  289. return newIssueLabel(e, issue, label, doer)
  290. }
  291. // AddLabel adds a new label to the issue.
  292. func (issue *Issue) AddLabel(doer *User, label *Label) error {
  293. if err := NewIssueLabel(issue, label, doer); err != nil {
  294. return err
  295. }
  296. issue.sendLabelUpdatedWebhook(doer)
  297. return nil
  298. }
  299. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  300. return newIssueLabels(e, issue, labels, doer)
  301. }
  302. // AddLabels adds a list of new labels to the issue.
  303. func (issue *Issue) AddLabels(doer *User, labels []*Label) error {
  304. if err := NewIssueLabels(issue, labels, doer); err != nil {
  305. return err
  306. }
  307. issue.sendLabelUpdatedWebhook(doer)
  308. return nil
  309. }
  310. func (issue *Issue) getLabels(e Engine) (err error) {
  311. if len(issue.Labels) > 0 {
  312. return nil
  313. }
  314. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  315. if err != nil {
  316. return fmt.Errorf("getLabelsByIssueID: %v", err)
  317. }
  318. return nil
  319. }
  320. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  321. return deleteIssueLabel(e, issue, label, doer)
  322. }
  323. // RemoveLabel removes a label from issue by given ID.
  324. func (issue *Issue) RemoveLabel(doer *User, label *Label) error {
  325. if err := issue.loadRepo(x); err != nil {
  326. return err
  327. }
  328. if has, err := HasAccess(doer.ID, issue.Repo, AccessModeWrite); err != nil {
  329. return err
  330. } else if !has {
  331. return ErrLabelNotExist{}
  332. }
  333. if err := DeleteIssueLabel(issue, label, doer); err != nil {
  334. return err
  335. }
  336. issue.sendLabelUpdatedWebhook(doer)
  337. return nil
  338. }
  339. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  340. if err = issue.getLabels(e); err != nil {
  341. return fmt.Errorf("getLabels: %v", err)
  342. }
  343. for i := range issue.Labels {
  344. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  345. return fmt.Errorf("removeLabel: %v", err)
  346. }
  347. }
  348. return nil
  349. }
  350. // ClearLabels removes all issue labels as the given user.
  351. // Triggers appropriate WebHooks, if any.
  352. func (issue *Issue) ClearLabels(doer *User) (err error) {
  353. sess := x.NewSession()
  354. defer sess.Close()
  355. if err = sess.Begin(); err != nil {
  356. return err
  357. }
  358. if err := issue.loadRepo(sess); err != nil {
  359. return err
  360. }
  361. if has, err := hasAccess(sess, doer.ID, issue.Repo, AccessModeWrite); err != nil {
  362. return err
  363. } else if !has {
  364. return ErrLabelNotExist{}
  365. }
  366. if err = issue.clearLabels(sess, doer); err != nil {
  367. return err
  368. }
  369. if err = sess.Commit(); err != nil {
  370. return fmt.Errorf("Commit: %v", err)
  371. }
  372. if issue.IsPull {
  373. err = issue.PullRequest.LoadIssue()
  374. if err != nil {
  375. log.Error(4, "LoadIssue: %v", err)
  376. return
  377. }
  378. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  379. Action: api.HookIssueLabelCleared,
  380. Index: issue.Index,
  381. PullRequest: issue.PullRequest.APIFormat(),
  382. Repository: issue.Repo.APIFormat(AccessModeNone),
  383. Sender: doer.APIFormat(),
  384. })
  385. }
  386. if err != nil {
  387. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  388. } else {
  389. go HookQueue.Add(issue.RepoID)
  390. }
  391. return nil
  392. }
  393. type labelSorter []*Label
  394. func (ts labelSorter) Len() int {
  395. return len([]*Label(ts))
  396. }
  397. func (ts labelSorter) Less(i, j int) bool {
  398. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  399. }
  400. func (ts labelSorter) Swap(i, j int) {
  401. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  402. }
  403. // ReplaceLabels removes all current labels and add new labels to the issue.
  404. // Triggers appropriate WebHooks, if any.
  405. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  406. sess := x.NewSession()
  407. defer sess.Close()
  408. if err = sess.Begin(); err != nil {
  409. return err
  410. }
  411. if err = issue.loadLabels(sess); err != nil {
  412. return err
  413. }
  414. sort.Sort(labelSorter(labels))
  415. sort.Sort(labelSorter(issue.Labels))
  416. var toAdd, toRemove []*Label
  417. addIndex, removeIndex := 0, 0
  418. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  419. addLabel := labels[addIndex]
  420. removeLabel := issue.Labels[removeIndex]
  421. if addLabel.ID == removeLabel.ID {
  422. addIndex++
  423. removeIndex++
  424. } else if addLabel.ID < removeLabel.ID {
  425. toAdd = append(toAdd, addLabel)
  426. addIndex++
  427. } else {
  428. toRemove = append(toRemove, removeLabel)
  429. removeIndex++
  430. }
  431. }
  432. toAdd = append(toAdd, labels[addIndex:]...)
  433. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  434. if len(toAdd) > 0 {
  435. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  436. return fmt.Errorf("addLabels: %v", err)
  437. }
  438. }
  439. for _, l := range toRemove {
  440. if err = issue.removeLabel(sess, doer, l); err != nil {
  441. return fmt.Errorf("removeLabel: %v", err)
  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 sess.Close()
  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 Assignee 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. LabelIDs []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 assigneeID := opts.Issue.AssigneeID; assigneeID > 0 {
  699. valid, err := hasAccess(e, assigneeID, opts.Repo, AccessModeWrite)
  700. if err != nil {
  701. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  702. }
  703. if !valid {
  704. opts.Issue.AssigneeID = 0
  705. opts.Issue.Assignee = nil
  706. }
  707. }
  708. // Milestone and assignee validation should happen before insert actual object.
  709. if _, err = e.Insert(opts.Issue); err != nil {
  710. return err
  711. }
  712. if opts.Issue.MilestoneID > 0 {
  713. if err = changeMilestoneAssign(e, doer, opts.Issue, -1); err != nil {
  714. return err
  715. }
  716. }
  717. if opts.Issue.AssigneeID > 0 {
  718. if err = opts.Issue.loadRepo(e); err != nil {
  719. return err
  720. }
  721. if _, err = createAssigneeComment(e, doer, opts.Issue.Repo, opts.Issue, -1, opts.Issue.AssigneeID); err != nil {
  722. return err
  723. }
  724. }
  725. if opts.IsPull {
  726. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  727. } else {
  728. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  729. }
  730. if err != nil {
  731. return err
  732. }
  733. if len(opts.LabelIDs) > 0 {
  734. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  735. // So we have to get all needed labels first.
  736. labels := make([]*Label, 0, len(opts.LabelIDs))
  737. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  738. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  739. }
  740. if err = opts.Issue.loadPoster(e); err != nil {
  741. return err
  742. }
  743. for _, label := range labels {
  744. // Silently drop invalid labels.
  745. if label.RepoID != opts.Repo.ID {
  746. continue
  747. }
  748. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  749. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  750. }
  751. }
  752. }
  753. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  754. return err
  755. }
  756. UpdateIssueIndexer(opts.Issue)
  757. if len(opts.Attachments) > 0 {
  758. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  759. if err != nil {
  760. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  761. }
  762. for i := 0; i < len(attachments); i++ {
  763. attachments[i].IssueID = opts.Issue.ID
  764. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  765. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  766. }
  767. }
  768. }
  769. return opts.Issue.loadAttributes(e)
  770. }
  771. // NewIssue creates new issue with labels for repository.
  772. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  773. sess := x.NewSession()
  774. defer sess.Close()
  775. if err = sess.Begin(); err != nil {
  776. return err
  777. }
  778. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  779. Repo: repo,
  780. Issue: issue,
  781. LabelIDs: labelIDs,
  782. Attachments: uuids,
  783. }); err != nil {
  784. return fmt.Errorf("newIssue: %v", err)
  785. }
  786. if err = sess.Commit(); err != nil {
  787. return fmt.Errorf("Commit: %v", err)
  788. }
  789. if err = NotifyWatchers(&Action{
  790. ActUserID: issue.Poster.ID,
  791. ActUser: issue.Poster,
  792. OpType: ActionCreateIssue,
  793. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  794. RepoID: repo.ID,
  795. Repo: repo,
  796. IsPrivate: repo.IsPrivate,
  797. }); err != nil {
  798. log.Error(4, "NotifyWatchers: %v", err)
  799. }
  800. if err = issue.MailParticipants(); err != nil {
  801. log.Error(4, "MailParticipants: %v", err)
  802. }
  803. return nil
  804. }
  805. // GetIssueByRef returns an Issue specified by a GFM reference.
  806. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  807. func GetIssueByRef(ref string) (*Issue, error) {
  808. n := strings.IndexByte(ref, byte('#'))
  809. if n == -1 {
  810. return nil, errMissingIssueNumber
  811. }
  812. index, err := com.StrTo(ref[n+1:]).Int64()
  813. if err != nil {
  814. return nil, err
  815. }
  816. repo, err := GetRepositoryByRef(ref[:n])
  817. if err != nil {
  818. return nil, err
  819. }
  820. issue, err := GetIssueByIndex(repo.ID, index)
  821. if err != nil {
  822. return nil, err
  823. }
  824. return issue, issue.LoadAttributes()
  825. }
  826. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  827. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  828. issue := &Issue{
  829. RepoID: repoID,
  830. Index: index,
  831. }
  832. has, err := x.Get(issue)
  833. if err != nil {
  834. return nil, err
  835. } else if !has {
  836. return nil, ErrIssueNotExist{0, repoID, index}
  837. }
  838. return issue, nil
  839. }
  840. // GetIssueByIndex returns issue by index in a repository.
  841. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  842. issue, err := GetRawIssueByIndex(repoID, index)
  843. if err != nil {
  844. return nil, err
  845. }
  846. return issue, issue.LoadAttributes()
  847. }
  848. func getIssueByID(e Engine, id int64) (*Issue, error) {
  849. issue := new(Issue)
  850. has, err := e.Id(id).Get(issue)
  851. if err != nil {
  852. return nil, err
  853. } else if !has {
  854. return nil, ErrIssueNotExist{id, 0, 0}
  855. }
  856. return issue, issue.loadAttributes(e)
  857. }
  858. // GetIssueByID returns an issue by given ID.
  859. func GetIssueByID(id int64) (*Issue, error) {
  860. return getIssueByID(x, id)
  861. }
  862. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  863. issues := make([]*Issue, 0, 10)
  864. return issues, e.In("id", issueIDs).Find(&issues)
  865. }
  866. // GetIssuesByIDs return issues with the given IDs.
  867. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  868. return getIssuesByIDs(x, issueIDs)
  869. }
  870. // IssuesOptions represents options of an issue.
  871. type IssuesOptions struct {
  872. RepoID int64
  873. AssigneeID int64
  874. PosterID int64
  875. MentionedID int64
  876. MilestoneID int64
  877. RepoIDs []int64
  878. Page int
  879. IsClosed util.OptionalBool
  880. IsPull util.OptionalBool
  881. Labels string
  882. SortType string
  883. IssueIDs []int64
  884. }
  885. // sortIssuesSession sort an issues-related session based on the provided
  886. // sortType string
  887. func sortIssuesSession(sess *xorm.Session, sortType string) {
  888. switch sortType {
  889. case "oldest":
  890. sess.Asc("issue.created_unix")
  891. case "recentupdate":
  892. sess.Desc("issue.updated_unix")
  893. case "leastupdate":
  894. sess.Asc("issue.updated_unix")
  895. case "mostcomment":
  896. sess.Desc("issue.num_comments")
  897. case "leastcomment":
  898. sess.Asc("issue.num_comments")
  899. case "priority":
  900. sess.Desc("issue.priority")
  901. default:
  902. sess.Desc("issue.created_unix")
  903. }
  904. }
  905. // Issues returns a list of issues by given conditions.
  906. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  907. var sess *xorm.Session
  908. if opts.Page >= 0 {
  909. var start int
  910. if opts.Page == 0 {
  911. start = 0
  912. } else {
  913. start = (opts.Page - 1) * setting.UI.IssuePagingNum
  914. }
  915. sess = x.Limit(setting.UI.IssuePagingNum, start)
  916. } else {
  917. sess = x.NewSession()
  918. defer sess.Close()
  919. }
  920. if len(opts.IssueIDs) > 0 {
  921. sess.In("issue.id", opts.IssueIDs)
  922. }
  923. if opts.RepoID > 0 {
  924. sess.And("issue.repo_id=?", opts.RepoID)
  925. } else if len(opts.RepoIDs) > 0 {
  926. // In case repository IDs are provided but actually no repository has issue.
  927. sess.In("issue.repo_id", opts.RepoIDs)
  928. }
  929. switch opts.IsClosed {
  930. case util.OptionalBoolTrue:
  931. sess.And("issue.is_closed=?", true)
  932. case util.OptionalBoolFalse:
  933. sess.And("issue.is_closed=?", false)
  934. }
  935. if opts.AssigneeID > 0 {
  936. sess.And("issue.assignee_id=?", opts.AssigneeID)
  937. }
  938. if opts.PosterID > 0 {
  939. sess.And("issue.poster_id=?", opts.PosterID)
  940. }
  941. if opts.MentionedID > 0 {
  942. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  943. And("issue_user.is_mentioned = ?", true).
  944. And("issue_user.uid = ?", opts.MentionedID)
  945. }
  946. if opts.MilestoneID > 0 {
  947. sess.And("issue.milestone_id=?", opts.MilestoneID)
  948. }
  949. switch opts.IsPull {
  950. case util.OptionalBoolTrue:
  951. sess.And("issue.is_pull=?", true)
  952. case util.OptionalBoolFalse:
  953. sess.And("issue.is_pull=?", false)
  954. }
  955. sortIssuesSession(sess, opts.SortType)
  956. if len(opts.Labels) > 0 && opts.Labels != "0" {
  957. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  958. if err != nil {
  959. return nil, err
  960. }
  961. if len(labelIDs) > 0 {
  962. sess.
  963. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  964. In("issue_label.label_id", labelIDs)
  965. }
  966. }
  967. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  968. if err := sess.Find(&issues); err != nil {
  969. return nil, fmt.Errorf("Find: %v", err)
  970. }
  971. if err := IssueList(issues).LoadAttributes(); err != nil {
  972. return nil, fmt.Errorf("LoadAttributes: %v", err)
  973. }
  974. return issues, nil
  975. }
  976. // GetParticipantsByIssueID returns all users who are participated in comments of an issue.
  977. func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
  978. userIDs := make([]int64, 0, 5)
  979. if err := x.Table("comment").Cols("poster_id").
  980. Where("issue_id = ?", issueID).
  981. And("type = ?", CommentTypeComment).
  982. Distinct("poster_id").
  983. Find(&userIDs); err != nil {
  984. return nil, fmt.Errorf("get poster IDs: %v", err)
  985. }
  986. if len(userIDs) == 0 {
  987. return nil, nil
  988. }
  989. users := make([]*User, 0, len(userIDs))
  990. return users, x.In("id", userIDs).Find(&users)
  991. }
  992. // UpdateIssueMentions extracts mentioned people from content and
  993. // updates issue-user relations for them.
  994. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  995. if len(mentions) == 0 {
  996. return nil
  997. }
  998. for i := range mentions {
  999. mentions[i] = strings.ToLower(mentions[i])
  1000. }
  1001. users := make([]*User, 0, len(mentions))
  1002. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  1003. return fmt.Errorf("find mentioned users: %v", err)
  1004. }
  1005. ids := make([]int64, 0, len(mentions))
  1006. for _, user := range users {
  1007. ids = append(ids, user.ID)
  1008. if !user.IsOrganization() || user.NumMembers == 0 {
  1009. continue
  1010. }
  1011. memberIDs := make([]int64, 0, user.NumMembers)
  1012. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  1013. if err != nil {
  1014. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  1015. }
  1016. for _, orgUser := range orgUsers {
  1017. memberIDs = append(memberIDs, orgUser.ID)
  1018. }
  1019. ids = append(ids, memberIDs...)
  1020. }
  1021. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  1022. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1023. }
  1024. return nil
  1025. }
  1026. // IssueStats represents issue statistic information.
  1027. type IssueStats struct {
  1028. OpenCount, ClosedCount int64
  1029. YourRepositoriesCount int64
  1030. AssignCount int64
  1031. CreateCount int64
  1032. MentionCount int64
  1033. }
  1034. // Filter modes.
  1035. const (
  1036. FilterModeAll = iota
  1037. FilterModeAssign
  1038. FilterModeCreate
  1039. FilterModeMention
  1040. )
  1041. func parseCountResult(results []map[string][]byte) int64 {
  1042. if len(results) == 0 {
  1043. return 0
  1044. }
  1045. for _, result := range results[0] {
  1046. return com.StrTo(string(result)).MustInt64()
  1047. }
  1048. return 0
  1049. }
  1050. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1051. type IssueStatsOptions struct {
  1052. RepoID int64
  1053. Labels string
  1054. MilestoneID int64
  1055. AssigneeID int64
  1056. MentionedID int64
  1057. PosterID int64
  1058. IsPull bool
  1059. IssueIDs []int64
  1060. }
  1061. // GetIssueStats returns issue statistic information by given conditions.
  1062. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1063. stats := &IssueStats{}
  1064. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1065. sess := x.
  1066. Where("issue.repo_id = ?", opts.RepoID).
  1067. And("issue.is_pull = ?", opts.IsPull)
  1068. if len(opts.IssueIDs) > 0 {
  1069. sess.In("issue.id", opts.IssueIDs)
  1070. }
  1071. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1072. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1073. if err != nil {
  1074. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1075. } else if len(labelIDs) > 0 {
  1076. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  1077. In("issue_label.label_id", labelIDs)
  1078. }
  1079. }
  1080. if opts.MilestoneID > 0 {
  1081. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1082. }
  1083. if opts.AssigneeID > 0 {
  1084. sess.And("issue.assignee_id = ?", opts.AssigneeID)
  1085. }
  1086. if opts.PosterID > 0 {
  1087. sess.And("issue.poster_id = ?", opts.PosterID)
  1088. }
  1089. if opts.MentionedID > 0 {
  1090. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1091. And("issue_user.uid = ?", opts.MentionedID).
  1092. And("issue_user.is_mentioned = ?", true)
  1093. }
  1094. return sess
  1095. }
  1096. var err error
  1097. stats.OpenCount, err = countSession(opts).
  1098. And("issue.is_closed = ?", false).
  1099. Count(new(Issue))
  1100. if err != nil {
  1101. return stats, err
  1102. }
  1103. stats.ClosedCount, err = countSession(opts).
  1104. And("issue.is_closed = ?", true).
  1105. Count(new(Issue))
  1106. return stats, err
  1107. }
  1108. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1109. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  1110. stats := &IssueStats{}
  1111. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1112. sess := x.
  1113. Where("issue.is_closed = ?", isClosed).
  1114. And("issue.is_pull = ?", isPull)
  1115. if repoID > 0 {
  1116. sess.And("repo_id = ?", repoID)
  1117. } else if len(repoIDs) > 0 {
  1118. sess.In("repo_id", repoIDs)
  1119. }
  1120. return sess
  1121. }
  1122. stats.AssignCount, _ = countSession(false, isPull, repoID, nil).
  1123. And("assignee_id = ?", uid).
  1124. Count(new(Issue))
  1125. stats.CreateCount, _ = countSession(false, isPull, repoID, nil).
  1126. And("poster_id = ?", uid).
  1127. Count(new(Issue))
  1128. stats.YourRepositoriesCount, _ = countSession(false, isPull, repoID, repoIDs).
  1129. Count(new(Issue))
  1130. switch filterMode {
  1131. case FilterModeAll:
  1132. stats.OpenCount, _ = countSession(false, isPull, repoID, repoIDs).
  1133. Count(new(Issue))
  1134. stats.ClosedCount, _ = countSession(true, isPull, repoID, repoIDs).
  1135. Count(new(Issue))
  1136. case FilterModeAssign:
  1137. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1138. And("assignee_id = ?", uid).
  1139. Count(new(Issue))
  1140. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1141. And("assignee_id = ?", uid).
  1142. Count(new(Issue))
  1143. case FilterModeCreate:
  1144. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1145. And("poster_id = ?", uid).
  1146. Count(new(Issue))
  1147. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1148. And("poster_id = ?", uid).
  1149. Count(new(Issue))
  1150. }
  1151. return stats
  1152. }
  1153. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1154. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1155. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1156. sess := x.
  1157. Where("is_closed = ?", isClosed).
  1158. And("is_pull = ?", isPull).
  1159. And("repo_id = ?", repoID)
  1160. return sess
  1161. }
  1162. openCountSession := countSession(false, isPull, repoID)
  1163. closedCountSession := countSession(true, isPull, repoID)
  1164. switch filterMode {
  1165. case FilterModeAssign:
  1166. openCountSession.And("assignee_id = ?", uid)
  1167. closedCountSession.And("assignee_id = ?", uid)
  1168. case FilterModeCreate:
  1169. openCountSession.And("poster_id = ?", uid)
  1170. closedCountSession.And("poster_id = ?", uid)
  1171. }
  1172. openResult, _ := openCountSession.Count(new(Issue))
  1173. closedResult, _ := closedCountSession.Count(new(Issue))
  1174. return openResult, closedResult
  1175. }
  1176. func updateIssue(e Engine, issue *Issue) error {
  1177. _, err := e.Id(issue.ID).AllCols().Update(issue)
  1178. if err != nil {
  1179. return err
  1180. }
  1181. UpdateIssueIndexer(issue)
  1182. return nil
  1183. }
  1184. // UpdateIssue updates all fields of given issue.
  1185. func UpdateIssue(issue *Issue) error {
  1186. return updateIssue(x, issue)
  1187. }