issue.go 39 KB

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