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.

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