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