issue.go 35 KB

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