issue.go 39 KB

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