issue.go 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461
  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. // Assume assignee is invalid and drop silently.
  596. opts.Issue.AssigneeID = 0
  597. if assignee != nil {
  598. valid, err := hasAccess(e, assignee.ID, opts.Repo, AccessModeRead)
  599. if err != nil {
  600. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assignee.ID, opts.Repo.ID, err)
  601. }
  602. if valid {
  603. opts.Issue.AssigneeID = assignee.ID
  604. opts.Issue.Assignee = assignee
  605. }
  606. }
  607. }
  608. // Milestone and assignee validation should happen before insert actual object.
  609. if _, err = e.Insert(opts.Issue); err != nil {
  610. return err
  611. }
  612. if opts.IsPull {
  613. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  614. } else {
  615. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  616. }
  617. if err != nil {
  618. return err
  619. }
  620. if len(opts.LableIDs) > 0 {
  621. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  622. // So we have to get all needed labels first.
  623. labels := make([]*Label, 0, len(opts.LableIDs))
  624. if err = e.In("id", opts.LableIDs).Find(&labels); err != nil {
  625. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LableIDs, err)
  626. }
  627. for _, label := range labels {
  628. // Silently drop invalid labels.
  629. if label.RepoID != opts.Repo.ID {
  630. continue
  631. }
  632. if err = opts.Issue.addLabel(e, label); err != nil {
  633. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  634. }
  635. }
  636. }
  637. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  638. return err
  639. }
  640. if len(opts.Attachments) > 0 {
  641. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  642. if err != nil {
  643. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  644. }
  645. for i := 0; i < len(attachments); i++ {
  646. attachments[i].IssueID = opts.Issue.ID
  647. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  648. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  649. }
  650. }
  651. }
  652. return opts.Issue.loadAttributes(e)
  653. }
  654. // NewIssue creates new issue with labels and attachments for repository.
  655. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  656. sess := x.NewSession()
  657. defer sess.Close()
  658. if err = sess.Begin(); err != nil {
  659. return err
  660. }
  661. if err = newIssue(sess, NewIssueOptions{
  662. Repo: repo,
  663. Issue: issue,
  664. LableIDs: labelIDs,
  665. Attachments: uuids,
  666. }); err != nil {
  667. return fmt.Errorf("newIssue: %v", err)
  668. }
  669. if err = sess.Commit(); err != nil {
  670. return fmt.Errorf("Commit: %v", err)
  671. }
  672. if err = NotifyWatchers(&Action{
  673. ActUserID: issue.Poster.ID,
  674. ActUserName: issue.Poster.Name,
  675. OpType: ACTION_CREATE_ISSUE,
  676. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  677. RepoID: repo.ID,
  678. RepoUserName: repo.Owner.Name,
  679. RepoName: repo.Name,
  680. IsPrivate: repo.IsPrivate,
  681. }); err != nil {
  682. log.Error("NotifyWatchers: %v", err)
  683. }
  684. if err = issue.MailParticipants(); err != nil {
  685. log.Error("MailParticipants: %v", err)
  686. }
  687. if err = PrepareWebhooks(repo, HOOK_EVENT_ISSUES, &api.IssuesPayload{
  688. Action: api.HOOK_ISSUE_OPENED,
  689. Index: issue.Index,
  690. Issue: issue.APIFormat(),
  691. Repository: repo.APIFormat(nil),
  692. Sender: issue.Poster.APIFormat(),
  693. }); err != nil {
  694. log.Error("PrepareWebhooks: %v", err)
  695. }
  696. return nil
  697. }
  698. var _ errutil.NotFound = (*ErrIssueNotExist)(nil)
  699. type ErrIssueNotExist struct {
  700. args map[string]interface{}
  701. }
  702. func IsErrIssueNotExist(err error) bool {
  703. _, ok := err.(ErrIssueNotExist)
  704. return ok
  705. }
  706. func (err ErrIssueNotExist) Error() string {
  707. return fmt.Sprintf("issue does not exist: %v", err.args)
  708. }
  709. func (ErrIssueNotExist) NotFound() bool {
  710. return true
  711. }
  712. // GetIssueByRef returns an Issue specified by a GFM reference.
  713. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  714. func GetIssueByRef(ref string) (*Issue, error) {
  715. n := strings.IndexByte(ref, byte('#'))
  716. if n == -1 {
  717. return nil, errors.InvalidIssueReference{Ref: ref}
  718. }
  719. index := com.StrTo(ref[n+1:]).MustInt64()
  720. if index == 0 {
  721. return nil, ErrIssueNotExist{args: map[string]interface{}{"ref": ref}}
  722. }
  723. repo, err := GetRepositoryByRef(ref[:n])
  724. if err != nil {
  725. return nil, err
  726. }
  727. issue, err := GetIssueByIndex(repo.ID, index)
  728. if err != nil {
  729. return nil, err
  730. }
  731. return issue, issue.LoadAttributes()
  732. }
  733. // GetIssueByIndex returns raw issue without loading attributes by index in a repository.
  734. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  735. issue := &Issue{
  736. RepoID: repoID,
  737. Index: index,
  738. }
  739. has, err := x.Get(issue)
  740. if err != nil {
  741. return nil, err
  742. } else if !has {
  743. return nil, ErrIssueNotExist{args: map[string]interface{}{"repoID": repoID, "index": index}}
  744. }
  745. return issue, nil
  746. }
  747. // GetIssueByIndex returns issue by index in a repository.
  748. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  749. issue, err := GetRawIssueByIndex(repoID, index)
  750. if err != nil {
  751. return nil, err
  752. }
  753. return issue, issue.LoadAttributes()
  754. }
  755. func getRawIssueByID(e Engine, id int64) (*Issue, error) {
  756. issue := new(Issue)
  757. has, err := e.ID(id).Get(issue)
  758. if err != nil {
  759. return nil, err
  760. } else if !has {
  761. return nil, ErrIssueNotExist{args: map[string]interface{}{"issueID": id}}
  762. }
  763. return issue, nil
  764. }
  765. func getIssueByID(e Engine, id int64) (*Issue, error) {
  766. issue, err := getRawIssueByID(e, id)
  767. if err != nil {
  768. return nil, err
  769. }
  770. return issue, issue.loadAttributes(e)
  771. }
  772. // GetIssueByID returns an issue by given ID.
  773. func GetIssueByID(id int64) (*Issue, error) {
  774. return getIssueByID(x, id)
  775. }
  776. type IssuesOptions struct {
  777. UserID int64
  778. AssigneeID int64
  779. RepoID int64
  780. PosterID int64
  781. MilestoneID int64
  782. RepoIDs []int64
  783. Page int
  784. IsClosed bool
  785. IsMention bool
  786. IsPull bool
  787. Labels string
  788. SortType string
  789. }
  790. // buildIssuesQuery returns nil if it foresees there won't be any value returned.
  791. func buildIssuesQuery(opts *IssuesOptions) *xorm.Session {
  792. sess := x.NewSession()
  793. if opts.Page <= 0 {
  794. opts.Page = 1
  795. }
  796. if opts.RepoID > 0 {
  797. sess.Where("issue.repo_id=?", opts.RepoID).And("issue.is_closed=?", opts.IsClosed)
  798. } else if opts.RepoIDs != nil {
  799. // In case repository IDs are provided but actually no repository has issue.
  800. if len(opts.RepoIDs) == 0 {
  801. return nil
  802. }
  803. sess.In("issue.repo_id", opts.RepoIDs).And("issue.is_closed=?", opts.IsClosed)
  804. } else {
  805. sess.Where("issue.is_closed=?", opts.IsClosed)
  806. }
  807. if opts.AssigneeID > 0 {
  808. sess.And("issue.assignee_id=?", opts.AssigneeID)
  809. } else if opts.PosterID > 0 {
  810. sess.And("issue.poster_id=?", opts.PosterID)
  811. }
  812. if opts.MilestoneID > 0 {
  813. sess.And("issue.milestone_id=?", opts.MilestoneID)
  814. }
  815. sess.And("issue.is_pull=?", opts.IsPull)
  816. switch opts.SortType {
  817. case "oldest":
  818. sess.Asc("issue.created_unix")
  819. case "recentupdate":
  820. sess.Desc("issue.updated_unix")
  821. case "leastupdate":
  822. sess.Asc("issue.updated_unix")
  823. case "mostcomment":
  824. sess.Desc("issue.num_comments")
  825. case "leastcomment":
  826. sess.Asc("issue.num_comments")
  827. case "priority":
  828. sess.Desc("issue.priority")
  829. default:
  830. sess.Desc("issue.created_unix")
  831. }
  832. if len(opts.Labels) > 0 && opts.Labels != "0" {
  833. labelIDs := strings.Split(opts.Labels, ",")
  834. if len(labelIDs) > 0 {
  835. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").In("issue_label.label_id", labelIDs)
  836. }
  837. }
  838. if opts.IsMention {
  839. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").And("issue_user.is_mentioned = ?", true)
  840. if opts.UserID > 0 {
  841. sess.And("issue_user.uid = ?", opts.UserID)
  842. }
  843. }
  844. return sess
  845. }
  846. // IssuesCount returns the number of issues by given conditions.
  847. func IssuesCount(opts *IssuesOptions) (int64, error) {
  848. sess := buildIssuesQuery(opts)
  849. if sess == nil {
  850. return 0, nil
  851. }
  852. return sess.Count(&Issue{})
  853. }
  854. // Issues returns a list of issues by given conditions.
  855. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  856. sess := buildIssuesQuery(opts)
  857. if sess == nil {
  858. return make([]*Issue, 0), nil
  859. }
  860. sess.Limit(conf.UI.IssuePagingNum, (opts.Page-1)*conf.UI.IssuePagingNum)
  861. issues := make([]*Issue, 0, conf.UI.IssuePagingNum)
  862. if err := sess.Find(&issues); err != nil {
  863. return nil, fmt.Errorf("Find: %v", err)
  864. }
  865. // FIXME: use IssueList to improve performance.
  866. for i := range issues {
  867. if err := issues[i].LoadAttributes(); err != nil {
  868. return nil, fmt.Errorf("LoadAttributes [%d]: %v", issues[i].ID, err)
  869. }
  870. }
  871. return issues, nil
  872. }
  873. // GetParticipantsByIssueID returns all users who are participated in comments of an issue.
  874. func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
  875. userIDs := make([]int64, 0, 5)
  876. if err := x.Table("comment").Cols("poster_id").
  877. Where("issue_id = ?", issueID).
  878. Distinct("poster_id").
  879. Find(&userIDs); err != nil {
  880. return nil, fmt.Errorf("get poster IDs: %v", err)
  881. }
  882. if len(userIDs) == 0 {
  883. return nil, nil
  884. }
  885. users := make([]*User, 0, len(userIDs))
  886. return users, x.In("id", userIDs).Find(&users)
  887. }
  888. // .___ ____ ___
  889. // | | ______ ________ __ ____ | | \______ ___________
  890. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  891. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  892. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  893. // \/ \/ \/ \/ \/
  894. // IssueUser represents an issue-user relation.
  895. type IssueUser struct {
  896. ID int64
  897. UID int64 `xorm:"INDEX"` // User ID.
  898. IssueID int64
  899. RepoID int64 `xorm:"INDEX"`
  900. MilestoneID int64
  901. IsRead bool
  902. IsAssigned bool
  903. IsMentioned bool
  904. IsPoster bool
  905. IsClosed bool
  906. }
  907. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  908. assignees, err := repo.getAssignees(e)
  909. if err != nil {
  910. return fmt.Errorf("getAssignees: %v", err)
  911. }
  912. // Poster can be anyone, append later if not one of assignees.
  913. isPosterAssignee := false
  914. // Leave a seat for poster itself to append later, but if poster is one of assignee
  915. // and just waste 1 unit is cheaper than re-allocate memory once.
  916. issueUsers := make([]*IssueUser, 0, len(assignees)+1)
  917. for _, assignee := range assignees {
  918. isPoster := assignee.ID == issue.PosterID
  919. issueUsers = append(issueUsers, &IssueUser{
  920. IssueID: issue.ID,
  921. RepoID: repo.ID,
  922. UID: assignee.ID,
  923. IsPoster: isPoster,
  924. IsAssigned: assignee.ID == issue.AssigneeID,
  925. })
  926. if !isPosterAssignee && isPoster {
  927. isPosterAssignee = true
  928. }
  929. }
  930. if !isPosterAssignee {
  931. issueUsers = append(issueUsers, &IssueUser{
  932. IssueID: issue.ID,
  933. RepoID: repo.ID,
  934. UID: issue.PosterID,
  935. IsPoster: true,
  936. })
  937. }
  938. if _, err = e.Insert(issueUsers); err != nil {
  939. return err
  940. }
  941. return nil
  942. }
  943. // NewIssueUsers adds new issue-user relations for new issue of repository.
  944. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  945. sess := x.NewSession()
  946. defer sess.Close()
  947. if err = sess.Begin(); err != nil {
  948. return err
  949. }
  950. if err = newIssueUsers(sess, repo, issue); err != nil {
  951. return err
  952. }
  953. return sess.Commit()
  954. }
  955. // PairsContains returns true when pairs list contains given issue.
  956. func PairsContains(ius []*IssueUser, issueId, uid int64) int {
  957. for i := range ius {
  958. if ius[i].IssueID == issueId &&
  959. ius[i].UID == uid {
  960. return i
  961. }
  962. }
  963. return -1
  964. }
  965. // GetIssueUsers returns issue-user pairs by given repository and user.
  966. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  967. ius := make([]*IssueUser, 0, 10)
  968. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  969. return ius, err
  970. }
  971. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  972. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  973. if len(rids) == 0 {
  974. return []*IssueUser{}, nil
  975. }
  976. ius := make([]*IssueUser, 0, 10)
  977. sess := x.Limit(20, (page-1)*20).Where("is_closed=?", isClosed).In("repo_id", rids)
  978. err := sess.Find(&ius)
  979. return ius, err
  980. }
  981. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  982. func GetIssueUserPairsByMode(userID, repoID int64, filterMode FilterMode, isClosed bool, page int) ([]*IssueUser, error) {
  983. ius := make([]*IssueUser, 0, 10)
  984. sess := x.Limit(20, (page-1)*20).Where("uid=?", userID).And("is_closed=?", isClosed)
  985. if repoID > 0 {
  986. sess.And("repo_id=?", repoID)
  987. }
  988. switch filterMode {
  989. case FILTER_MODE_ASSIGN:
  990. sess.And("is_assigned=?", true)
  991. case FILTER_MODE_CREATE:
  992. sess.And("is_poster=?", true)
  993. default:
  994. return ius, nil
  995. }
  996. err := sess.Find(&ius)
  997. return ius, err
  998. }
  999. // updateIssueMentions extracts mentioned people from content and
  1000. // updates issue-user relations for them.
  1001. func updateIssueMentions(e Engine, issueID int64, mentions []string) error {
  1002. if len(mentions) == 0 {
  1003. return nil
  1004. }
  1005. for i := range mentions {
  1006. mentions[i] = strings.ToLower(mentions[i])
  1007. }
  1008. users := make([]*User, 0, len(mentions))
  1009. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  1010. return fmt.Errorf("find mentioned users: %v", err)
  1011. }
  1012. ids := make([]int64, 0, len(mentions))
  1013. for _, user := range users {
  1014. ids = append(ids, user.ID)
  1015. if !user.IsOrganization() || user.NumMembers == 0 {
  1016. continue
  1017. }
  1018. memberIDs := make([]int64, 0, user.NumMembers)
  1019. orgUsers, err := getOrgUsersByOrgID(e, user.ID, 0)
  1020. if err != nil {
  1021. return fmt.Errorf("getOrgUsersByOrgID [%d]: %v", user.ID, err)
  1022. }
  1023. for _, orgUser := range orgUsers {
  1024. memberIDs = append(memberIDs, orgUser.ID)
  1025. }
  1026. ids = append(ids, memberIDs...)
  1027. }
  1028. if err := updateIssueUsersByMentions(e, issueID, ids); err != nil {
  1029. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1030. }
  1031. return nil
  1032. }
  1033. // IssueStats represents issue statistic information.
  1034. type IssueStats struct {
  1035. OpenCount, ClosedCount int64
  1036. YourReposCount int64
  1037. AssignCount int64
  1038. CreateCount int64
  1039. MentionCount int64
  1040. }
  1041. type FilterMode string
  1042. const (
  1043. FILTER_MODE_YOUR_REPOS FilterMode = "your_repositories"
  1044. FILTER_MODE_ASSIGN FilterMode = "assigned"
  1045. FILTER_MODE_CREATE FilterMode = "created_by"
  1046. FILTER_MODE_MENTION FilterMode = "mentioned"
  1047. )
  1048. func parseCountResult(results []map[string][]byte) int64 {
  1049. if len(results) == 0 {
  1050. return 0
  1051. }
  1052. for _, result := range results[0] {
  1053. return com.StrTo(string(result)).MustInt64()
  1054. }
  1055. return 0
  1056. }
  1057. type IssueStatsOptions struct {
  1058. RepoID int64
  1059. UserID int64
  1060. Labels string
  1061. MilestoneID int64
  1062. AssigneeID int64
  1063. FilterMode FilterMode
  1064. IsPull bool
  1065. }
  1066. // GetIssueStats returns issue statistic information by given conditions.
  1067. func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
  1068. stats := &IssueStats{}
  1069. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1070. sess := x.Where("issue.repo_id = ?", opts.RepoID).And("is_pull = ?", opts.IsPull)
  1071. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1072. labelIDs := tool.StringsToInt64s(strings.Split(opts.Labels, ","))
  1073. if len(labelIDs) > 0 {
  1074. sess.Join("INNER", "issue_label", "issue.id = issue_id").In("label_id", labelIDs)
  1075. }
  1076. }
  1077. if opts.MilestoneID > 0 {
  1078. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1079. }
  1080. if opts.AssigneeID > 0 {
  1081. sess.And("assignee_id = ?", opts.AssigneeID)
  1082. }
  1083. return sess
  1084. }
  1085. switch opts.FilterMode {
  1086. case FILTER_MODE_YOUR_REPOS, FILTER_MODE_ASSIGN:
  1087. stats.OpenCount, _ = countSession(opts).
  1088. And("is_closed = ?", false).
  1089. Count(new(Issue))
  1090. stats.ClosedCount, _ = countSession(opts).
  1091. And("is_closed = ?", true).
  1092. Count(new(Issue))
  1093. case FILTER_MODE_CREATE:
  1094. stats.OpenCount, _ = countSession(opts).
  1095. And("poster_id = ?", opts.UserID).
  1096. And("is_closed = ?", false).
  1097. Count(new(Issue))
  1098. stats.ClosedCount, _ = countSession(opts).
  1099. And("poster_id = ?", opts.UserID).
  1100. And("is_closed = ?", true).
  1101. Count(new(Issue))
  1102. case FILTER_MODE_MENTION:
  1103. stats.OpenCount, _ = 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 = ?", false).
  1108. Count(new(Issue))
  1109. stats.ClosedCount, _ = countSession(opts).
  1110. Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1111. And("issue_user.uid = ?", opts.UserID).
  1112. And("issue_user.is_mentioned = ?", true).
  1113. And("issue.is_closed = ?", true).
  1114. Count(new(Issue))
  1115. }
  1116. return stats
  1117. }
  1118. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1119. func GetUserIssueStats(repoID, userID int64, repoIDs []int64, filterMode FilterMode, isPull bool) *IssueStats {
  1120. stats := &IssueStats{}
  1121. hasAnyRepo := repoID > 0 || len(repoIDs) > 0
  1122. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1123. sess := x.Where("issue.is_closed = ?", isClosed).And("issue.is_pull = ?", isPull)
  1124. if repoID > 0 {
  1125. sess.And("repo_id = ?", repoID)
  1126. } else if len(repoIDs) > 0 {
  1127. sess.In("repo_id", repoIDs)
  1128. }
  1129. return sess
  1130. }
  1131. stats.AssignCount, _ = countSession(false, isPull, repoID, nil).
  1132. And("assignee_id = ?", userID).
  1133. Count(new(Issue))
  1134. stats.CreateCount, _ = countSession(false, isPull, repoID, nil).
  1135. And("poster_id = ?", userID).
  1136. Count(new(Issue))
  1137. if hasAnyRepo {
  1138. stats.YourReposCount, _ = countSession(false, isPull, repoID, repoIDs).
  1139. Count(new(Issue))
  1140. }
  1141. switch filterMode {
  1142. case FILTER_MODE_YOUR_REPOS:
  1143. if !hasAnyRepo {
  1144. break
  1145. }
  1146. stats.OpenCount, _ = countSession(false, isPull, repoID, repoIDs).
  1147. Count(new(Issue))
  1148. stats.ClosedCount, _ = countSession(true, isPull, repoID, repoIDs).
  1149. Count(new(Issue))
  1150. case FILTER_MODE_ASSIGN:
  1151. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1152. And("assignee_id = ?", userID).
  1153. Count(new(Issue))
  1154. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1155. And("assignee_id = ?", userID).
  1156. Count(new(Issue))
  1157. case FILTER_MODE_CREATE:
  1158. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1159. And("poster_id = ?", userID).
  1160. Count(new(Issue))
  1161. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1162. And("poster_id = ?", userID).
  1163. Count(new(Issue))
  1164. }
  1165. return stats
  1166. }
  1167. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1168. func GetRepoIssueStats(repoID, userID int64, filterMode FilterMode, isPull bool) (numOpen int64, numClosed int64) {
  1169. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1170. sess := x.Where("issue.repo_id = ?", isClosed).
  1171. And("is_pull = ?", isPull).
  1172. And("repo_id = ?", repoID)
  1173. return sess
  1174. }
  1175. openCountSession := countSession(false, isPull, repoID)
  1176. closedCountSession := countSession(true, isPull, repoID)
  1177. switch filterMode {
  1178. case FILTER_MODE_ASSIGN:
  1179. openCountSession.And("assignee_id = ?", userID)
  1180. closedCountSession.And("assignee_id = ?", userID)
  1181. case FILTER_MODE_CREATE:
  1182. openCountSession.And("poster_id = ?", userID)
  1183. closedCountSession.And("poster_id = ?", userID)
  1184. }
  1185. openResult, _ := openCountSession.Count(new(Issue))
  1186. closedResult, _ := closedCountSession.Count(new(Issue))
  1187. return openResult, closedResult
  1188. }
  1189. func updateIssue(e Engine, issue *Issue) error {
  1190. _, err := e.ID(issue.ID).AllCols().Update(issue)
  1191. return err
  1192. }
  1193. // UpdateIssue updates all fields of given issue.
  1194. func UpdateIssue(issue *Issue) error {
  1195. return updateIssue(x, issue)
  1196. }
  1197. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  1198. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  1199. return err
  1200. }
  1201. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  1202. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  1203. return updateIssueUsersByStatus(x, issueID, isClosed)
  1204. }
  1205. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  1206. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE issue_id = ?", false, issue.ID); err != nil {
  1207. return err
  1208. }
  1209. // Assignee ID equals to 0 means clear assignee.
  1210. if issue.AssigneeID > 0 {
  1211. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE uid = ? AND issue_id = ?", true, issue.AssigneeID, issue.ID); err != nil {
  1212. return err
  1213. }
  1214. }
  1215. return updateIssue(e, issue)
  1216. }
  1217. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  1218. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  1219. sess := x.NewSession()
  1220. defer sess.Close()
  1221. if err = sess.Begin(); err != nil {
  1222. return err
  1223. }
  1224. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  1225. return err
  1226. }
  1227. return sess.Commit()
  1228. }
  1229. // UpdateIssueUserByRead updates issue-user relation for reading.
  1230. func UpdateIssueUserByRead(uid, issueID int64) error {
  1231. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  1232. return err
  1233. }
  1234. // updateIssueUsersByMentions updates issue-user pairs by mentioning.
  1235. func updateIssueUsersByMentions(e Engine, issueID int64, uids []int64) error {
  1236. for _, uid := range uids {
  1237. iu := &IssueUser{
  1238. UID: uid,
  1239. IssueID: issueID,
  1240. }
  1241. has, err := e.Get(iu)
  1242. if err != nil {
  1243. return err
  1244. }
  1245. iu.IsMentioned = true
  1246. if has {
  1247. _, err = e.ID(iu.ID).AllCols().Update(iu)
  1248. } else {
  1249. _, err = e.Insert(iu)
  1250. }
  1251. if err != nil {
  1252. return err
  1253. }
  1254. }
  1255. return nil
  1256. }