issue.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459
  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 (
  19. ErrMissingIssueNumber = errors.New("No issue number specified")
  20. )
  21. // Issue represents an issue or pull request of repository.
  22. type Issue struct {
  23. ID int64
  24. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  25. Repo *Repository `xorm:"-" json:"-"`
  26. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  27. PosterID int64
  28. Poster *User `xorm:"-" json:"-"`
  29. Title string `xorm:"name"`
  30. Content string `xorm:"TEXT"`
  31. RenderedContent string `xorm:"-" json:"-"`
  32. Labels []*Label `xorm:"-" json:"-"`
  33. MilestoneID int64
  34. Milestone *Milestone `xorm:"-" json:"-"`
  35. Priority int
  36. AssigneeID int64
  37. Assignee *User `xorm:"-" json:"-"`
  38. IsClosed bool
  39. IsRead bool `xorm:"-" json:"-"`
  40. IsPull bool // Indicates whether is a pull request or not.
  41. PullRequest *PullRequest `xorm:"-" json:"-"`
  42. NumComments int
  43. Deadline time.Time `xorm:"-" json:"-"`
  44. DeadlineUnix int64
  45. Created time.Time `xorm:"-" json:"-"`
  46. CreatedUnix int64
  47. Updated time.Time `xorm:"-" json:"-"`
  48. UpdatedUnix int64
  49. Attachments []*Attachment `xorm:"-" json:"-"`
  50. Comments []*Comment `xorm:"-" json:"-"`
  51. }
  52. func (issue *Issue) BeforeInsert() {
  53. issue.CreatedUnix = time.Now().Unix()
  54. issue.UpdatedUnix = issue.CreatedUnix
  55. }
  56. func (issue *Issue) BeforeUpdate() {
  57. issue.UpdatedUnix = time.Now().Unix()
  58. issue.DeadlineUnix = issue.Deadline.Unix()
  59. }
  60. func (issue *Issue) AfterSet(colName string, _ xorm.Cell) {
  61. switch colName {
  62. case "deadline_unix":
  63. issue.Deadline = time.Unix(issue.DeadlineUnix, 0).Local()
  64. case "created_unix":
  65. issue.Created = time.Unix(issue.CreatedUnix, 0).Local()
  66. case "updated_unix":
  67. issue.Updated = time.Unix(issue.UpdatedUnix, 0).Local()
  68. }
  69. }
  70. func (issue *Issue) loadAttributes(e Engine) (err error) {
  71. if issue.Repo == nil {
  72. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  73. if err != nil {
  74. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  75. }
  76. }
  77. if issue.Poster == nil {
  78. issue.Poster, err = getUserByID(e, issue.PosterID)
  79. if err != nil {
  80. if IsErrUserNotExist(err) {
  81. issue.PosterID = -1
  82. issue.Poster = NewGhostUser()
  83. } else {
  84. return fmt.Errorf("getUserByID.(Poster) [%d]: %v", issue.PosterID, err)
  85. }
  86. }
  87. }
  88. if issue.Labels == nil {
  89. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  90. if err != nil {
  91. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  92. }
  93. }
  94. if issue.Milestone == nil && issue.MilestoneID > 0 {
  95. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  96. if err != nil {
  97. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  98. }
  99. }
  100. if issue.Assignee == nil && issue.AssigneeID > 0 {
  101. issue.Assignee, err = getUserByID(e, issue.AssigneeID)
  102. if err != nil {
  103. return fmt.Errorf("getUserByID.(assignee) [%d]: %v", issue.AssigneeID, err)
  104. }
  105. }
  106. if issue.IsPull && issue.PullRequest == nil {
  107. // It is possible pull request is not yet created.
  108. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  109. if err != nil && !IsErrPullRequestNotExist(err) {
  110. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  111. }
  112. }
  113. if issue.Attachments == nil {
  114. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  115. if err != nil {
  116. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  117. }
  118. }
  119. if issue.Comments == nil {
  120. issue.Comments, err = getCommentsByIssueID(e, issue.ID)
  121. if err != nil {
  122. return fmt.Errorf("getCommentsByIssueID [%d]: %v", issue.ID, err)
  123. }
  124. }
  125. return nil
  126. }
  127. func (issue *Issue) LoadAttributes() error {
  128. return issue.loadAttributes(x)
  129. }
  130. func (issue *Issue) HTMLURL() string {
  131. var path string
  132. if issue.IsPull {
  133. path = "pulls"
  134. } else {
  135. path = "issues"
  136. }
  137. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  138. }
  139. // State returns string representation of issue status.
  140. func (issue *Issue) State() api.StateType {
  141. if issue.IsClosed {
  142. return api.STATE_CLOSED
  143. }
  144. return api.STATE_OPEN
  145. }
  146. // This method assumes some fields assigned with values:
  147. // Required - Poster, Labels,
  148. // Optional - Milestone, Assignee, PullRequest
  149. func (issue *Issue) APIFormat() *api.Issue {
  150. apiLabels := make([]*api.Label, len(issue.Labels))
  151. for i := range issue.Labels {
  152. apiLabels[i] = issue.Labels[i].APIFormat()
  153. }
  154. apiIssue := &api.Issue{
  155. ID: issue.ID,
  156. Index: issue.Index,
  157. Poster: issue.Poster.APIFormat(),
  158. Title: issue.Title,
  159. Body: issue.Content,
  160. Labels: apiLabels,
  161. State: issue.State(),
  162. Comments: issue.NumComments,
  163. Created: issue.Created,
  164. Updated: issue.Updated,
  165. }
  166. if issue.Milestone != nil {
  167. apiIssue.Milestone = issue.Milestone.APIFormat()
  168. }
  169. if issue.Assignee != nil {
  170. apiIssue.Assignee = issue.Assignee.APIFormat()
  171. }
  172. if issue.IsPull {
  173. apiIssue.PullRequest = &api.PullRequestMeta{
  174. HasMerged: issue.PullRequest.HasMerged,
  175. }
  176. if issue.PullRequest.HasMerged {
  177. apiIssue.PullRequest.Merged = &issue.PullRequest.Merged
  178. }
  179. }
  180. return apiIssue
  181. }
  182. // HashTag returns unique hash tag for issue.
  183. func (issue *Issue) HashTag() string {
  184. return "issue-" + com.ToStr(issue.ID)
  185. }
  186. // IsPoster returns true if given user by ID is the poster.
  187. func (issue *Issue) IsPoster(uid int64) bool {
  188. return issue.PosterID == uid
  189. }
  190. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  191. return hasIssueLabel(e, issue.ID, labelID)
  192. }
  193. // HasLabel returns true if issue has been labeled by given ID.
  194. func (issue *Issue) HasLabel(labelID int64) bool {
  195. return issue.hasLabel(x, labelID)
  196. }
  197. func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
  198. var err error
  199. if issue.IsPull {
  200. err = issue.PullRequest.LoadIssue()
  201. if err != nil {
  202. log.Error("LoadIssue: %v", err)
  203. return
  204. }
  205. err = PrepareWebhooks(issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  206. Action: api.HOOK_ISSUE_LABEL_UPDATED,
  207. Index: issue.Index,
  208. PullRequest: issue.PullRequest.APIFormat(),
  209. Repository: issue.Repo.APIFormat(nil),
  210. Sender: doer.APIFormat(),
  211. })
  212. } else {
  213. err = PrepareWebhooks(issue.Repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{
  214. Action: api.HOOK_ISSUE_LABEL_UPDATED,
  215. Index: issue.Index,
  216. Issue: issue.APIFormat(),
  217. Repository: issue.Repo.APIFormat(nil),
  218. Sender: doer.APIFormat(),
  219. })
  220. }
  221. if err != nil {
  222. log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  223. }
  224. }
  225. func (issue *Issue) addLabel(e *xorm.Session, label *Label) error {
  226. return newIssueLabel(e, issue, label)
  227. }
  228. // AddLabel adds a new label to the issue.
  229. func (issue *Issue) AddLabel(doer *User, label *Label) error {
  230. if err := NewIssueLabel(issue, label); err != nil {
  231. return err
  232. }
  233. issue.sendLabelUpdatedWebhook(doer)
  234. return nil
  235. }
  236. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label) error {
  237. return newIssueLabels(e, issue, labels)
  238. }
  239. // AddLabels adds a list of new labels to the issue.
  240. func (issue *Issue) AddLabels(doer *User, labels []*Label) error {
  241. if err := NewIssueLabels(issue, labels); err != nil {
  242. return err
  243. }
  244. issue.sendLabelUpdatedWebhook(doer)
  245. return nil
  246. }
  247. func (issue *Issue) getLabels(e Engine) (err error) {
  248. if len(issue.Labels) > 0 {
  249. return nil
  250. }
  251. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  252. if err != nil {
  253. return fmt.Errorf("getLabelsByIssueID: %v", err)
  254. }
  255. return nil
  256. }
  257. func (issue *Issue) removeLabel(e *xorm.Session, label *Label) error {
  258. return deleteIssueLabel(e, issue, label)
  259. }
  260. // RemoveLabel removes a label from issue by given ID.
  261. func (issue *Issue) RemoveLabel(doer *User, label *Label) error {
  262. if err := DeleteIssueLabel(issue, label); err != nil {
  263. return err
  264. }
  265. issue.sendLabelUpdatedWebhook(doer)
  266. return nil
  267. }
  268. func (issue *Issue) clearLabels(e *xorm.Session) (err error) {
  269. if err = issue.getLabels(e); err != nil {
  270. return fmt.Errorf("getLabels: %v", err)
  271. }
  272. // NOTE: issue.removeLabel slices issue.Labels, so we need to create another slice to be unaffected.
  273. labels := make([]*Label, len(issue.Labels))
  274. copy(labels, issue.Labels)
  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. // Assume assignee is invalid and drop silently.
  594. opts.Issue.AssigneeID = 0
  595. if assignee != nil {
  596. valid, err := hasAccess(e, assignee.ID, opts.Repo, AccessModeRead)
  597. if err != nil {
  598. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assignee.ID, opts.Repo.ID, err)
  599. }
  600. if valid {
  601. opts.Issue.AssigneeID = assignee.ID
  602. opts.Issue.Assignee = assignee
  603. }
  604. }
  605. }
  606. // Milestone and assignee validation should happen before insert actual object.
  607. if _, err = e.Insert(opts.Issue); err != nil {
  608. return err
  609. }
  610. if opts.IsPull {
  611. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  612. } else {
  613. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  614. }
  615. if err != nil {
  616. return err
  617. }
  618. if len(opts.LableIDs) > 0 {
  619. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  620. // So we have to get all needed labels first.
  621. labels := make([]*Label, 0, len(opts.LableIDs))
  622. if err = e.In("id", opts.LableIDs).Find(&labels); err != nil {
  623. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LableIDs, err)
  624. }
  625. for _, label := range labels {
  626. // Silently drop invalid labels.
  627. if label.RepoID != opts.Repo.ID {
  628. continue
  629. }
  630. if err = opts.Issue.addLabel(e, label); err != nil {
  631. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  632. }
  633. }
  634. }
  635. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  636. return err
  637. }
  638. if len(opts.Attachments) > 0 {
  639. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  640. if err != nil {
  641. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  642. }
  643. for i := 0; i < len(attachments); i++ {
  644. attachments[i].IssueID = opts.Issue.ID
  645. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  646. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  647. }
  648. }
  649. }
  650. return opts.Issue.loadAttributes(e)
  651. }
  652. // NewIssue creates new issue with labels and attachments for repository.
  653. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  654. sess := x.NewSession()
  655. defer sess.Close()
  656. if err = sess.Begin(); err != nil {
  657. return err
  658. }
  659. if err = newIssue(sess, NewIssueOptions{
  660. Repo: repo,
  661. Issue: issue,
  662. LableIDs: labelIDs,
  663. Attachments: uuids,
  664. }); err != nil {
  665. return fmt.Errorf("newIssue: %v", err)
  666. }
  667. if err = sess.Commit(); err != nil {
  668. return fmt.Errorf("Commit: %v", err)
  669. }
  670. if err = NotifyWatchers(&Action{
  671. ActUserID: issue.Poster.ID,
  672. ActUserName: issue.Poster.Name,
  673. OpType: ACTION_CREATE_ISSUE,
  674. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  675. RepoID: repo.ID,
  676. RepoUserName: repo.Owner.Name,
  677. RepoName: repo.Name,
  678. IsPrivate: repo.IsPrivate,
  679. }); err != nil {
  680. log.Error("NotifyWatchers: %v", err)
  681. }
  682. if err = issue.MailParticipants(); err != nil {
  683. log.Error("MailParticipants: %v", err)
  684. }
  685. if err = PrepareWebhooks(repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{
  686. Action: api.HOOK_ISSUE_OPENED,
  687. Index: issue.Index,
  688. Issue: issue.APIFormat(),
  689. Repository: repo.APIFormat(nil),
  690. Sender: issue.Poster.APIFormat(),
  691. }); err != nil {
  692. log.Error("PrepareWebhooks: %v", err)
  693. }
  694. return nil
  695. }
  696. var _ errutil.NotFound = (*ErrIssueNotExist)(nil)
  697. type ErrIssueNotExist struct {
  698. args map[string]interface{}
  699. }
  700. func IsErrIssueNotExist(err error) bool {
  701. _, ok := err.(ErrIssueNotExist)
  702. return ok
  703. }
  704. func (err ErrIssueNotExist) Error() string {
  705. return fmt.Sprintf("issue does not exist: %v", err.args)
  706. }
  707. func (ErrIssueNotExist) NotFound() bool {
  708. return true
  709. }
  710. // GetIssueByRef returns an Issue specified by a GFM reference, e.g. owner/repo#123.
  711. func GetIssueByRef(ref string) (*Issue, error) {
  712. n := strings.IndexByte(ref, byte('#'))
  713. if n == -1 {
  714. return nil, ErrIssueNotExist{args: map[string]interface{}{"ref": ref}}
  715. }
  716. index := com.StrTo(ref[n+1:]).MustInt64()
  717. if index == 0 {
  718. return nil, ErrIssueNotExist{args: map[string]interface{}{"ref": ref}}
  719. }
  720. repo, err := GetRepositoryByRef(ref[:n])
  721. if err != nil {
  722. return nil, err
  723. }
  724. issue, err := GetIssueByIndex(repo.ID, index)
  725. if err != nil {
  726. return nil, err
  727. }
  728. return issue, issue.LoadAttributes()
  729. }
  730. // GetIssueByIndex returns raw issue without loading attributes by index in a repository.
  731. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  732. issue := &Issue{
  733. RepoID: repoID,
  734. Index: index,
  735. }
  736. has, err := x.Get(issue)
  737. if err != nil {
  738. return nil, err
  739. } else if !has {
  740. return nil, ErrIssueNotExist{args: map[string]interface{}{"repoID": repoID, "index": index}}
  741. }
  742. return issue, nil
  743. }
  744. // GetIssueByIndex returns issue by index in a repository.
  745. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  746. issue, err := GetRawIssueByIndex(repoID, index)
  747. if err != nil {
  748. return nil, err
  749. }
  750. return issue, issue.LoadAttributes()
  751. }
  752. func getRawIssueByID(e Engine, id int64) (*Issue, error) {
  753. issue := new(Issue)
  754. has, err := e.ID(id).Get(issue)
  755. if err != nil {
  756. return nil, err
  757. } else if !has {
  758. return nil, ErrIssueNotExist{args: map[string]interface{}{"issueID": id}}
  759. }
  760. return issue, nil
  761. }
  762. func getIssueByID(e Engine, id int64) (*Issue, error) {
  763. issue, err := getRawIssueByID(e, id)
  764. if err != nil {
  765. return nil, err
  766. }
  767. return issue, issue.loadAttributes(e)
  768. }
  769. // GetIssueByID returns an issue by given ID.
  770. func GetIssueByID(id int64) (*Issue, error) {
  771. return getIssueByID(x, id)
  772. }
  773. type IssuesOptions struct {
  774. UserID int64
  775. AssigneeID int64
  776. RepoID int64
  777. PosterID int64
  778. MilestoneID int64
  779. RepoIDs []int64
  780. Page int
  781. IsClosed bool
  782. IsMention bool
  783. IsPull bool
  784. Labels string
  785. SortType string
  786. }
  787. // buildIssuesQuery returns nil if it foresees there won't be any value returned.
  788. func buildIssuesQuery(opts *IssuesOptions) *xorm.Session {
  789. sess := x.NewSession()
  790. if opts.Page <= 0 {
  791. opts.Page = 1
  792. }
  793. if opts.RepoID > 0 {
  794. sess.Where("issue.repo_id=?", opts.RepoID).And("issue.is_closed=?", opts.IsClosed)
  795. } else if opts.RepoIDs != nil {
  796. // In case repository IDs are provided but actually no repository has issue.
  797. if len(opts.RepoIDs) == 0 {
  798. return nil
  799. }
  800. sess.In("issue.repo_id", opts.RepoIDs).And("issue.is_closed=?", opts.IsClosed)
  801. } else {
  802. sess.Where("issue.is_closed=?", opts.IsClosed)
  803. }
  804. if opts.AssigneeID > 0 {
  805. sess.And("issue.assignee_id=?", opts.AssigneeID)
  806. } else if opts.PosterID > 0 {
  807. sess.And("issue.poster_id=?", opts.PosterID)
  808. }
  809. if opts.MilestoneID > 0 {
  810. sess.And("issue.milestone_id=?", opts.MilestoneID)
  811. }
  812. sess.And("issue.is_pull=?", opts.IsPull)
  813. switch opts.SortType {
  814. case "oldest":
  815. sess.Asc("issue.created_unix")
  816. case "recentupdate":
  817. sess.Desc("issue.updated_unix")
  818. case "leastupdate":
  819. sess.Asc("issue.updated_unix")
  820. case "mostcomment":
  821. sess.Desc("issue.num_comments")
  822. case "leastcomment":
  823. sess.Asc("issue.num_comments")
  824. case "priority":
  825. sess.Desc("issue.priority")
  826. default:
  827. sess.Desc("issue.created_unix")
  828. }
  829. if len(opts.Labels) > 0 && opts.Labels != "0" {
  830. labelIDs := strings.Split(opts.Labels, ",")
  831. if len(labelIDs) > 0 {
  832. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").In("issue_label.label_id", labelIDs)
  833. }
  834. }
  835. if opts.IsMention {
  836. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").And("issue_user.is_mentioned = ?", true)
  837. if opts.UserID > 0 {
  838. sess.And("issue_user.uid = ?", opts.UserID)
  839. }
  840. }
  841. return sess
  842. }
  843. // IssuesCount returns the number of issues by given conditions.
  844. func IssuesCount(opts *IssuesOptions) (int64, error) {
  845. sess := buildIssuesQuery(opts)
  846. if sess == nil {
  847. return 0, nil
  848. }
  849. return sess.Count(&Issue{})
  850. }
  851. // Issues returns a list of issues by given conditions.
  852. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  853. sess := buildIssuesQuery(opts)
  854. if sess == nil {
  855. return make([]*Issue, 0), nil
  856. }
  857. sess.Limit(conf.UI.IssuePagingNum, (opts.Page-1)*conf.UI.IssuePagingNum)
  858. issues := make([]*Issue, 0, conf.UI.IssuePagingNum)
  859. if err := sess.Find(&issues); err != nil {
  860. return nil, fmt.Errorf("Find: %v", err)
  861. }
  862. // FIXME: use IssueList to improve performance.
  863. for i := range issues {
  864. if err := issues[i].LoadAttributes(); err != nil {
  865. return nil, fmt.Errorf("LoadAttributes [%d]: %v", issues[i].ID, err)
  866. }
  867. }
  868. return issues, nil
  869. }
  870. // GetParticipantsByIssueID returns all users who are participated in comments of an issue.
  871. func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
  872. userIDs := make([]int64, 0, 5)
  873. if err := x.Table("comment").Cols("poster_id").
  874. Where("issue_id = ?", issueID).
  875. Distinct("poster_id").
  876. Find(&userIDs); err != nil {
  877. return nil, fmt.Errorf("get poster IDs: %v", err)
  878. }
  879. if len(userIDs) == 0 {
  880. return nil, nil
  881. }
  882. users := make([]*User, 0, len(userIDs))
  883. return users, x.In("id", userIDs).Find(&users)
  884. }
  885. // .___ ____ ___
  886. // | | ______ ________ __ ____ | | \______ ___________
  887. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  888. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  889. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  890. // \/ \/ \/ \/ \/
  891. // IssueUser represents an issue-user relation.
  892. type IssueUser struct {
  893. ID int64
  894. UID int64 `xorm:"INDEX"` // User ID.
  895. IssueID int64
  896. RepoID int64 `xorm:"INDEX"`
  897. MilestoneID int64
  898. IsRead bool
  899. IsAssigned bool
  900. IsMentioned bool
  901. IsPoster bool
  902. IsClosed bool
  903. }
  904. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  905. assignees, err := repo.getAssignees(e)
  906. if err != nil {
  907. return fmt.Errorf("getAssignees: %v", err)
  908. }
  909. // Poster can be anyone, append later if not one of assignees.
  910. isPosterAssignee := false
  911. // Leave a seat for poster itself to append later, but if poster is one of assignee
  912. // and just waste 1 unit is cheaper than re-allocate memory once.
  913. issueUsers := make([]*IssueUser, 0, len(assignees)+1)
  914. for _, assignee := range assignees {
  915. isPoster := assignee.ID == issue.PosterID
  916. issueUsers = append(issueUsers, &IssueUser{
  917. IssueID: issue.ID,
  918. RepoID: repo.ID,
  919. UID: assignee.ID,
  920. IsPoster: isPoster,
  921. IsAssigned: assignee.ID == issue.AssigneeID,
  922. })
  923. if !isPosterAssignee && isPoster {
  924. isPosterAssignee = true
  925. }
  926. }
  927. if !isPosterAssignee {
  928. issueUsers = append(issueUsers, &IssueUser{
  929. IssueID: issue.ID,
  930. RepoID: repo.ID,
  931. UID: issue.PosterID,
  932. IsPoster: true,
  933. })
  934. }
  935. if _, err = e.Insert(issueUsers); err != nil {
  936. return err
  937. }
  938. return nil
  939. }
  940. // NewIssueUsers adds new issue-user relations for new issue of repository.
  941. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  942. sess := x.NewSession()
  943. defer sess.Close()
  944. if err = sess.Begin(); err != nil {
  945. return err
  946. }
  947. if err = newIssueUsers(sess, repo, issue); err != nil {
  948. return err
  949. }
  950. return sess.Commit()
  951. }
  952. // PairsContains returns true when pairs list contains given issue.
  953. func PairsContains(ius []*IssueUser, issueId, uid int64) int {
  954. for i := range ius {
  955. if ius[i].IssueID == issueId &&
  956. ius[i].UID == uid {
  957. return i
  958. }
  959. }
  960. return -1
  961. }
  962. // GetIssueUsers returns issue-user pairs by given repository and user.
  963. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  964. ius := make([]*IssueUser, 0, 10)
  965. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  966. return ius, err
  967. }
  968. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  969. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  970. if len(rids) == 0 {
  971. return []*IssueUser{}, nil
  972. }
  973. ius := make([]*IssueUser, 0, 10)
  974. sess := x.Limit(20, (page-1)*20).Where("is_closed=?", isClosed).In("repo_id", rids)
  975. err := sess.Find(&ius)
  976. return ius, err
  977. }
  978. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  979. func GetIssueUserPairsByMode(userID, repoID int64, filterMode FilterMode, isClosed bool, page int) ([]*IssueUser, error) {
  980. ius := make([]*IssueUser, 0, 10)
  981. sess := x.Limit(20, (page-1)*20).Where("uid=?", userID).And("is_closed=?", isClosed)
  982. if repoID > 0 {
  983. sess.And("repo_id=?", repoID)
  984. }
  985. switch filterMode {
  986. case FILTER_MODE_ASSIGN:
  987. sess.And("is_assigned=?", true)
  988. case FILTER_MODE_CREATE:
  989. sess.And("is_poster=?", true)
  990. default:
  991. return ius, nil
  992. }
  993. err := sess.Find(&ius)
  994. return ius, err
  995. }
  996. // updateIssueMentions extracts mentioned people from content and
  997. // updates issue-user relations for them.
  998. func updateIssueMentions(e Engine, issueID int64, mentions []string) error {
  999. if len(mentions) == 0 {
  1000. return nil
  1001. }
  1002. for i := range mentions {
  1003. mentions[i] = strings.ToLower(mentions[i])
  1004. }
  1005. users := make([]*User, 0, len(mentions))
  1006. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  1007. return fmt.Errorf("find mentioned users: %v", err)
  1008. }
  1009. ids := make([]int64, 0, len(mentions))
  1010. for _, user := range users {
  1011. ids = append(ids, user.ID)
  1012. if !user.IsOrganization() || user.NumMembers == 0 {
  1013. continue
  1014. }
  1015. memberIDs := make([]int64, 0, user.NumMembers)
  1016. orgUsers, err := getOrgUsersByOrgID(e, user.ID, 0)
  1017. if err != nil {
  1018. return fmt.Errorf("getOrgUsersByOrgID [%d]: %v", user.ID, err)
  1019. }
  1020. for _, orgUser := range orgUsers {
  1021. memberIDs = append(memberIDs, orgUser.ID)
  1022. }
  1023. ids = append(ids, memberIDs...)
  1024. }
  1025. if err := updateIssueUsersByMentions(e, issueID, ids); err != nil {
  1026. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1027. }
  1028. return nil
  1029. }
  1030. // IssueStats represents issue statistic information.
  1031. type IssueStats struct {
  1032. OpenCount, ClosedCount int64
  1033. YourReposCount int64
  1034. AssignCount int64
  1035. CreateCount int64
  1036. MentionCount int64
  1037. }
  1038. type FilterMode string
  1039. const (
  1040. FILTER_MODE_YOUR_REPOS FilterMode = "your_repositories"
  1041. FILTER_MODE_ASSIGN FilterMode = "assigned"
  1042. FILTER_MODE_CREATE FilterMode = "created_by"
  1043. FILTER_MODE_MENTION FilterMode = "mentioned"
  1044. )
  1045. func parseCountResult(results []map[string][]byte) int64 {
  1046. if len(results) == 0 {
  1047. return 0
  1048. }
  1049. for _, result := range results[0] {
  1050. return com.StrTo(string(result)).MustInt64()
  1051. }
  1052. return 0
  1053. }
  1054. type IssueStatsOptions struct {
  1055. RepoID int64
  1056. UserID int64
  1057. Labels string
  1058. MilestoneID int64
  1059. AssigneeID int64
  1060. FilterMode FilterMode
  1061. IsPull bool
  1062. }
  1063. // GetIssueStats returns issue statistic information by given conditions.
  1064. func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
  1065. stats := &IssueStats{}
  1066. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1067. sess := x.Where("issue.repo_id = ?", opts.RepoID).And("is_pull = ?", opts.IsPull)
  1068. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1069. labelIDs := tool.StringsToInt64s(strings.Split(opts.Labels, ","))
  1070. if len(labelIDs) > 0 {
  1071. sess.Join("INNER", "issue_label", "issue.id = issue_id").In("label_id", labelIDs)
  1072. }
  1073. }
  1074. if opts.MilestoneID > 0 {
  1075. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1076. }
  1077. if opts.AssigneeID > 0 {
  1078. sess.And("assignee_id = ?", opts.AssigneeID)
  1079. }
  1080. return sess
  1081. }
  1082. switch opts.FilterMode {
  1083. case FILTER_MODE_YOUR_REPOS, FILTER_MODE_ASSIGN:
  1084. stats.OpenCount, _ = countSession(opts).
  1085. And("is_closed = ?", false).
  1086. Count(new(Issue))
  1087. stats.ClosedCount, _ = countSession(opts).
  1088. And("is_closed = ?", true).
  1089. Count(new(Issue))
  1090. case FILTER_MODE_CREATE:
  1091. stats.OpenCount, _ = countSession(opts).
  1092. And("poster_id = ?", opts.UserID).
  1093. And("is_closed = ?", false).
  1094. Count(new(Issue))
  1095. stats.ClosedCount, _ = countSession(opts).
  1096. And("poster_id = ?", opts.UserID).
  1097. And("is_closed = ?", true).
  1098. Count(new(Issue))
  1099. case FILTER_MODE_MENTION:
  1100. stats.OpenCount, _ = countSession(opts).
  1101. Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1102. And("issue_user.uid = ?", opts.UserID).
  1103. And("issue_user.is_mentioned = ?", true).
  1104. And("issue.is_closed = ?", false).
  1105. Count(new(Issue))
  1106. stats.ClosedCount, _ = countSession(opts).
  1107. Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1108. And("issue_user.uid = ?", opts.UserID).
  1109. And("issue_user.is_mentioned = ?", true).
  1110. And("issue.is_closed = ?", true).
  1111. Count(new(Issue))
  1112. }
  1113. return stats
  1114. }
  1115. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1116. func GetUserIssueStats(repoID, userID int64, repoIDs []int64, filterMode FilterMode, isPull bool) *IssueStats {
  1117. stats := &IssueStats{}
  1118. hasAnyRepo := repoID > 0 || len(repoIDs) > 0
  1119. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1120. sess := x.Where("issue.is_closed = ?", isClosed).And("issue.is_pull = ?", isPull)
  1121. if repoID > 0 {
  1122. sess.And("repo_id = ?", repoID)
  1123. } else if len(repoIDs) > 0 {
  1124. sess.In("repo_id", repoIDs)
  1125. }
  1126. return sess
  1127. }
  1128. stats.AssignCount, _ = countSession(false, isPull, repoID, nil).
  1129. And("assignee_id = ?", userID).
  1130. Count(new(Issue))
  1131. stats.CreateCount, _ = countSession(false, isPull, repoID, nil).
  1132. And("poster_id = ?", userID).
  1133. Count(new(Issue))
  1134. if hasAnyRepo {
  1135. stats.YourReposCount, _ = countSession(false, isPull, repoID, repoIDs).
  1136. Count(new(Issue))
  1137. }
  1138. switch filterMode {
  1139. case FILTER_MODE_YOUR_REPOS:
  1140. if !hasAnyRepo {
  1141. break
  1142. }
  1143. stats.OpenCount, _ = countSession(false, isPull, repoID, repoIDs).
  1144. Count(new(Issue))
  1145. stats.ClosedCount, _ = countSession(true, isPull, repoID, repoIDs).
  1146. Count(new(Issue))
  1147. case FILTER_MODE_ASSIGN:
  1148. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1149. And("assignee_id = ?", userID).
  1150. Count(new(Issue))
  1151. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1152. And("assignee_id = ?", userID).
  1153. Count(new(Issue))
  1154. case FILTER_MODE_CREATE:
  1155. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1156. And("poster_id = ?", userID).
  1157. Count(new(Issue))
  1158. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1159. And("poster_id = ?", userID).
  1160. Count(new(Issue))
  1161. }
  1162. return stats
  1163. }
  1164. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1165. func GetRepoIssueStats(repoID, userID int64, filterMode FilterMode, isPull bool) (numOpen int64, numClosed int64) {
  1166. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1167. sess := x.Where("issue.repo_id = ?", isClosed).
  1168. And("is_pull = ?", isPull).
  1169. And("repo_id = ?", repoID)
  1170. return sess
  1171. }
  1172. openCountSession := countSession(false, isPull, repoID)
  1173. closedCountSession := countSession(true, isPull, repoID)
  1174. switch filterMode {
  1175. case FILTER_MODE_ASSIGN:
  1176. openCountSession.And("assignee_id = ?", userID)
  1177. closedCountSession.And("assignee_id = ?", userID)
  1178. case FILTER_MODE_CREATE:
  1179. openCountSession.And("poster_id = ?", userID)
  1180. closedCountSession.And("poster_id = ?", userID)
  1181. }
  1182. openResult, _ := openCountSession.Count(new(Issue))
  1183. closedResult, _ := closedCountSession.Count(new(Issue))
  1184. return openResult, closedResult
  1185. }
  1186. func updateIssue(e Engine, issue *Issue) error {
  1187. _, err := e.ID(issue.ID).AllCols().Update(issue)
  1188. return err
  1189. }
  1190. // UpdateIssue updates all fields of given issue.
  1191. func UpdateIssue(issue *Issue) error {
  1192. return updateIssue(x, issue)
  1193. }
  1194. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  1195. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  1196. return err
  1197. }
  1198. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  1199. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  1200. return updateIssueUsersByStatus(x, issueID, isClosed)
  1201. }
  1202. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  1203. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE issue_id = ?", false, issue.ID); err != nil {
  1204. return err
  1205. }
  1206. // Assignee ID equals to 0 means clear assignee.
  1207. if issue.AssigneeID > 0 {
  1208. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE uid = ? AND issue_id = ?", true, issue.AssigneeID, issue.ID); err != nil {
  1209. return err
  1210. }
  1211. }
  1212. return updateIssue(e, issue)
  1213. }
  1214. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  1215. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  1216. sess := x.NewSession()
  1217. defer sess.Close()
  1218. if err = sess.Begin(); err != nil {
  1219. return err
  1220. }
  1221. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  1222. return err
  1223. }
  1224. return sess.Commit()
  1225. }
  1226. // UpdateIssueUserByRead updates issue-user relation for reading.
  1227. func UpdateIssueUserByRead(uid, issueID int64) error {
  1228. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  1229. return err
  1230. }
  1231. // updateIssueUsersByMentions updates issue-user pairs by mentioning.
  1232. func updateIssueUsersByMentions(e Engine, issueID int64, uids []int64) error {
  1233. for _, uid := range uids {
  1234. iu := &IssueUser{
  1235. UID: uid,
  1236. IssueID: issueID,
  1237. }
  1238. has, err := e.Get(iu)
  1239. if err != nil {
  1240. return err
  1241. }
  1242. iu.IsMentioned = true
  1243. if has {
  1244. _, err = e.ID(iu.ID).AllCols().Update(iu)
  1245. } else {
  1246. _, err = e.Insert(iu)
  1247. }
  1248. if err != nil {
  1249. return err
  1250. }
  1251. }
  1252. return nil
  1253. }