issue.go 38 KB

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