issue.go 38 KB

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