issue.go 38 KB

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