issue.go 39 KB

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