issue.go 38 KB

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