issue.go 38 KB

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