issue.go 38 KB

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