You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

issue.go 37 kB

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