issue.go 39 KB

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