issue.go 38 KB

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