issue.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468
  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
  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. memberIDs := make([]int64, 0, user.NumMembers)
  1024. orgUsers, err := getOrgUsersByOrgID(e, user.ID, 0)
  1025. if err != nil {
  1026. return fmt.Errorf("getOrgUsersByOrgID [%d]: %v", user.ID, err)
  1027. }
  1028. for _, orgUser := range orgUsers {
  1029. memberIDs = append(memberIDs, orgUser.ID)
  1030. }
  1031. ids = append(ids, memberIDs...)
  1032. }
  1033. if err := updateIssueUsersByMentions(e, issueID, ids); err != nil {
  1034. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1035. }
  1036. return nil
  1037. }
  1038. // IssueStats represents issue statistic information.
  1039. type IssueStats struct {
  1040. OpenCount, ClosedCount int64
  1041. YourReposCount int64
  1042. AssignCount int64
  1043. CreateCount int64
  1044. MentionCount int64
  1045. }
  1046. type FilterMode string
  1047. const (
  1048. FILTER_MODE_YOUR_REPOS FilterMode = "your_repositories"
  1049. FILTER_MODE_ASSIGN FilterMode = "assigned"
  1050. FILTER_MODE_CREATE FilterMode = "created_by"
  1051. FILTER_MODE_MENTION FilterMode = "mentioned"
  1052. )
  1053. func parseCountResult(results []map[string][]byte) int64 {
  1054. if len(results) == 0 {
  1055. return 0
  1056. }
  1057. for _, result := range results[0] {
  1058. return com.StrTo(string(result)).MustInt64()
  1059. }
  1060. return 0
  1061. }
  1062. type IssueStatsOptions struct {
  1063. RepoID int64
  1064. UserID int64
  1065. Labels string
  1066. MilestoneID int64
  1067. AssigneeID int64
  1068. FilterMode FilterMode
  1069. IsPull bool
  1070. }
  1071. // GetIssueStats returns issue statistic information by given conditions.
  1072. func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
  1073. stats := &IssueStats{}
  1074. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1075. sess := x.Where("issue.repo_id = ?", opts.RepoID).And("is_pull = ?", opts.IsPull)
  1076. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1077. labelIDs := tool.StringsToInt64s(strings.Split(opts.Labels, ","))
  1078. if len(labelIDs) > 0 {
  1079. sess.Join("INNER", "issue_label", "issue.id = issue_id").In("label_id", labelIDs)
  1080. }
  1081. }
  1082. if opts.MilestoneID > 0 {
  1083. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1084. }
  1085. if opts.AssigneeID > 0 {
  1086. sess.And("assignee_id = ?", opts.AssigneeID)
  1087. }
  1088. return sess
  1089. }
  1090. switch opts.FilterMode {
  1091. case FILTER_MODE_YOUR_REPOS, FILTER_MODE_ASSIGN:
  1092. stats.OpenCount, _ = countSession(opts).
  1093. And("is_closed = ?", false).
  1094. Count(new(Issue))
  1095. stats.ClosedCount, _ = countSession(opts).
  1096. And("is_closed = ?", true).
  1097. Count(new(Issue))
  1098. case FILTER_MODE_CREATE:
  1099. stats.OpenCount, _ = countSession(opts).
  1100. And("poster_id = ?", opts.UserID).
  1101. And("is_closed = ?", false).
  1102. Count(new(Issue))
  1103. stats.ClosedCount, _ = countSession(opts).
  1104. And("poster_id = ?", opts.UserID).
  1105. And("is_closed = ?", true).
  1106. Count(new(Issue))
  1107. case FILTER_MODE_MENTION:
  1108. stats.OpenCount, _ = countSession(opts).
  1109. Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1110. And("issue_user.uid = ?", opts.UserID).
  1111. And("issue_user.is_mentioned = ?", true).
  1112. And("issue.is_closed = ?", false).
  1113. Count(new(Issue))
  1114. stats.ClosedCount, _ = countSession(opts).
  1115. Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1116. And("issue_user.uid = ?", opts.UserID).
  1117. And("issue_user.is_mentioned = ?", true).
  1118. And("issue.is_closed = ?", true).
  1119. Count(new(Issue))
  1120. }
  1121. return stats
  1122. }
  1123. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1124. func GetUserIssueStats(repoID, userID int64, repoIDs []int64, filterMode FilterMode, isPull bool) *IssueStats {
  1125. stats := &IssueStats{}
  1126. hasAnyRepo := repoID > 0 || len(repoIDs) > 0
  1127. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1128. sess := x.Where("issue.is_closed = ?", isClosed).And("issue.is_pull = ?", isPull)
  1129. if repoID > 0 {
  1130. sess.And("repo_id = ?", repoID)
  1131. } else if len(repoIDs) > 0 {
  1132. sess.In("repo_id", repoIDs)
  1133. }
  1134. return sess
  1135. }
  1136. stats.AssignCount, _ = countSession(false, isPull, repoID, nil).
  1137. And("assignee_id = ?", userID).
  1138. Count(new(Issue))
  1139. stats.CreateCount, _ = countSession(false, isPull, repoID, nil).
  1140. And("poster_id = ?", userID).
  1141. Count(new(Issue))
  1142. if hasAnyRepo {
  1143. stats.YourReposCount, _ = countSession(false, isPull, repoID, repoIDs).
  1144. Count(new(Issue))
  1145. }
  1146. switch filterMode {
  1147. case FILTER_MODE_YOUR_REPOS:
  1148. if !hasAnyRepo {
  1149. break
  1150. }
  1151. stats.OpenCount, _ = countSession(false, isPull, repoID, repoIDs).
  1152. Count(new(Issue))
  1153. stats.ClosedCount, _ = countSession(true, isPull, repoID, repoIDs).
  1154. Count(new(Issue))
  1155. case FILTER_MODE_ASSIGN:
  1156. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1157. And("assignee_id = ?", userID).
  1158. Count(new(Issue))
  1159. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1160. And("assignee_id = ?", userID).
  1161. Count(new(Issue))
  1162. case FILTER_MODE_CREATE:
  1163. stats.OpenCount, _ = countSession(false, isPull, repoID, nil).
  1164. And("poster_id = ?", userID).
  1165. Count(new(Issue))
  1166. stats.ClosedCount, _ = countSession(true, isPull, repoID, nil).
  1167. And("poster_id = ?", userID).
  1168. Count(new(Issue))
  1169. }
  1170. return stats
  1171. }
  1172. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1173. func GetRepoIssueStats(repoID, userID int64, filterMode FilterMode, isPull bool) (numOpen, numClosed int64) {
  1174. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1175. sess := x.Where("issue.repo_id = ?", isClosed).
  1176. And("is_pull = ?", isPull).
  1177. And("repo_id = ?", repoID)
  1178. return sess
  1179. }
  1180. openCountSession := countSession(false, isPull, repoID)
  1181. closedCountSession := countSession(true, isPull, repoID)
  1182. switch filterMode {
  1183. case FILTER_MODE_ASSIGN:
  1184. openCountSession.And("assignee_id = ?", userID)
  1185. closedCountSession.And("assignee_id = ?", userID)
  1186. case FILTER_MODE_CREATE:
  1187. openCountSession.And("poster_id = ?", userID)
  1188. closedCountSession.And("poster_id = ?", userID)
  1189. }
  1190. openResult, _ := openCountSession.Count(new(Issue))
  1191. closedResult, _ := closedCountSession.Count(new(Issue))
  1192. return openResult, closedResult
  1193. }
  1194. func updateIssue(e Engine, issue *Issue) error {
  1195. _, err := e.ID(issue.ID).AllCols().Update(issue)
  1196. return err
  1197. }
  1198. // UpdateIssue updates all fields of given issue.
  1199. func UpdateIssue(issue *Issue) error {
  1200. return updateIssue(x, issue)
  1201. }
  1202. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  1203. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  1204. return err
  1205. }
  1206. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  1207. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  1208. return updateIssueUsersByStatus(x, issueID, isClosed)
  1209. }
  1210. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  1211. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE issue_id = ?", false, issue.ID); err != nil {
  1212. return err
  1213. }
  1214. // Assignee ID equals to 0 means clear assignee.
  1215. if issue.AssigneeID > 0 {
  1216. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE uid = ? AND issue_id = ?", true, issue.AssigneeID, issue.ID); err != nil {
  1217. return err
  1218. }
  1219. }
  1220. return updateIssue(e, issue)
  1221. }
  1222. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  1223. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  1224. sess := x.NewSession()
  1225. defer sess.Close()
  1226. if err = sess.Begin(); err != nil {
  1227. return err
  1228. }
  1229. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  1230. return err
  1231. }
  1232. return sess.Commit()
  1233. }
  1234. // UpdateIssueUserByRead updates issue-user relation for reading.
  1235. func UpdateIssueUserByRead(uid, issueID int64) error {
  1236. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  1237. return err
  1238. }
  1239. // updateIssueUsersByMentions updates issue-user pairs by mentioning.
  1240. func updateIssueUsersByMentions(e Engine, issueID int64, uids []int64) error {
  1241. for _, uid := range uids {
  1242. iu := &IssueUser{
  1243. UserID: uid,
  1244. IssueID: issueID,
  1245. }
  1246. has, err := e.Get(iu)
  1247. if err != nil {
  1248. return err
  1249. }
  1250. iu.IsMentioned = true
  1251. if has {
  1252. _, err = e.ID(iu.ID).AllCols().Update(iu)
  1253. } else {
  1254. _, err = e.Insert(iu)
  1255. }
  1256. if err != nil {
  1257. return err
  1258. }
  1259. }
  1260. return nil
  1261. }