1
0

issue.go 39 KB

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