issue.go 38 KB

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