You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

issue_comment.go 17 kB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "fmt"
  7. "strings"
  8. "time"
  9. "github.com/Unknwon/com"
  10. "github.com/go-xorm/xorm"
  11. api "code.gitea.io/sdk/gitea"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/markdown"
  14. )
  15. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  16. type CommentType int
  17. // Enumerate all the comment types
  18. const (
  19. // Plain comment, can be associated with a commit (CommitID > 0) and a line (LineNum > 0)
  20. CommentTypeComment CommentType = iota
  21. CommentTypeReopen
  22. CommentTypeClose
  23. // References.
  24. CommentTypeIssueRef
  25. // Reference from a commit (not part of a pull request)
  26. CommentTypeCommitRef
  27. // Reference from a comment
  28. CommentTypeCommentRef
  29. // Reference from a pull request
  30. CommentTypePullRef
  31. // Labels changed
  32. CommentTypeLabel
  33. // Milestone changed
  34. CommentTypeMilestone
  35. // Assignees changed
  36. CommentTypeAssignees
  37. // Change Title
  38. CommentTypeChangeTitle
  39. )
  40. // CommentTag defines comment tag type
  41. type CommentTag int
  42. // Enumerate all the comment tag types
  43. const (
  44. CommentTagNone CommentTag = iota
  45. CommentTagPoster
  46. CommentTagWriter
  47. CommentTagOwner
  48. )
  49. // Comment represents a comment in commit and issue page.
  50. type Comment struct {
  51. ID int64 `xorm:"pk autoincr"`
  52. Type CommentType
  53. PosterID int64 `xorm:"INDEX"`
  54. Poster *User `xorm:"-"`
  55. IssueID int64 `xorm:"INDEX"`
  56. LabelID int64
  57. Label *Label `xorm:"-"`
  58. OldMilestoneID int64
  59. MilestoneID int64
  60. OldMilestone *Milestone `xorm:"-"`
  61. Milestone *Milestone `xorm:"-"`
  62. OldAssigneeID int64
  63. AssigneeID int64
  64. Assignee *User `xorm:"-"`
  65. OldAssignee *User `xorm:"-"`
  66. OldTitle string
  67. NewTitle string
  68. CommitID int64
  69. Line int64
  70. Content string `xorm:"TEXT"`
  71. RenderedContent string `xorm:"-"`
  72. Created time.Time `xorm:"-"`
  73. CreatedUnix int64 `xorm:"INDEX"`
  74. Updated time.Time `xorm:"-"`
  75. UpdatedUnix int64 `xorm:"INDEX"`
  76. // Reference issue in commit message
  77. CommitSHA string `xorm:"VARCHAR(40)"`
  78. Attachments []*Attachment `xorm:"-"`
  79. // For view issue page.
  80. ShowTag CommentTag `xorm:"-"`
  81. }
  82. // BeforeInsert will be invoked by XORM before inserting a record
  83. // representing this object.
  84. func (c *Comment) BeforeInsert() {
  85. c.CreatedUnix = time.Now().Unix()
  86. c.UpdatedUnix = c.CreatedUnix
  87. }
  88. // BeforeUpdate is invoked from XORM before updating this object.
  89. func (c *Comment) BeforeUpdate() {
  90. c.UpdatedUnix = time.Now().Unix()
  91. }
  92. // AfterSet is invoked from XORM after setting the value of a field of this object.
  93. func (c *Comment) AfterSet(colName string, _ xorm.Cell) {
  94. var err error
  95. switch colName {
  96. case "id":
  97. c.Attachments, err = GetAttachmentsByCommentID(c.ID)
  98. if err != nil {
  99. log.Error(3, "GetAttachmentsByCommentID[%d]: %v", c.ID, err)
  100. }
  101. case "poster_id":
  102. c.Poster, err = GetUserByID(c.PosterID)
  103. if err != nil {
  104. if IsErrUserNotExist(err) {
  105. c.PosterID = -1
  106. c.Poster = NewGhostUser()
  107. } else {
  108. log.Error(3, "GetUserByID[%d]: %v", c.ID, err)
  109. }
  110. }
  111. case "created_unix":
  112. c.Created = time.Unix(c.CreatedUnix, 0).Local()
  113. case "updated_unix":
  114. c.Updated = time.Unix(c.UpdatedUnix, 0).Local()
  115. }
  116. }
  117. // AfterDelete is invoked from XORM after the object is deleted.
  118. func (c *Comment) AfterDelete() {
  119. _, err := DeleteAttachmentsByComment(c.ID, true)
  120. if err != nil {
  121. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  122. }
  123. }
  124. // HTMLURL formats a URL-string to the issue-comment
  125. func (c *Comment) HTMLURL() string {
  126. issue, err := GetIssueByID(c.IssueID)
  127. if err != nil { // Silently dropping errors :unamused:
  128. log.Error(4, "GetIssueByID(%d): %v", c.IssueID, err)
  129. return ""
  130. }
  131. return fmt.Sprintf("%s#issuecomment-%d", issue.HTMLURL(), c.ID)
  132. }
  133. // IssueURL formats a URL-string to the issue
  134. func (c *Comment) IssueURL() string {
  135. issue, err := GetIssueByID(c.IssueID)
  136. if err != nil { // Silently dropping errors :unamused:
  137. log.Error(4, "GetIssueByID(%d): %v", c.IssueID, err)
  138. return ""
  139. }
  140. if issue.IsPull {
  141. return ""
  142. }
  143. return issue.HTMLURL()
  144. }
  145. // PRURL formats a URL-string to the pull-request
  146. func (c *Comment) PRURL() string {
  147. issue, err := GetIssueByID(c.IssueID)
  148. if err != nil { // Silently dropping errors :unamused:
  149. log.Error(4, "GetIssueByID(%d): %v", c.IssueID, err)
  150. return ""
  151. }
  152. if !issue.IsPull {
  153. return ""
  154. }
  155. return issue.HTMLURL()
  156. }
  157. // APIFormat converts a Comment to the api.Comment format
  158. func (c *Comment) APIFormat() *api.Comment {
  159. return &api.Comment{
  160. ID: c.ID,
  161. Poster: c.Poster.APIFormat(),
  162. HTMLURL: c.HTMLURL(),
  163. IssueURL: c.IssueURL(),
  164. PRURL: c.PRURL(),
  165. Body: c.Content,
  166. Created: c.Created,
  167. Updated: c.Updated,
  168. }
  169. }
  170. // HashTag returns unique hash tag for comment.
  171. func (c *Comment) HashTag() string {
  172. return "issuecomment-" + com.ToStr(c.ID)
  173. }
  174. // EventTag returns unique event hash tag for comment.
  175. func (c *Comment) EventTag() string {
  176. return "event-" + com.ToStr(c.ID)
  177. }
  178. // LoadLabel if comment.Type is CommentTypeLabel, then load Label
  179. func (c *Comment) LoadLabel() error {
  180. var label Label
  181. has, err := x.ID(c.LabelID).Get(&label)
  182. if err != nil {
  183. return err
  184. } else if !has {
  185. return ErrLabelNotExist{
  186. LabelID: c.LabelID,
  187. }
  188. }
  189. c.Label = &label
  190. return nil
  191. }
  192. // LoadMilestone if comment.Type is CommentTypeMilestone, then load milestone
  193. func (c *Comment) LoadMilestone() error {
  194. if c.OldMilestoneID > 0 {
  195. var oldMilestone Milestone
  196. has, err := x.ID(c.OldMilestoneID).Get(&oldMilestone)
  197. if err != nil {
  198. return err
  199. } else if !has {
  200. return ErrMilestoneNotExist{
  201. ID: c.OldMilestoneID,
  202. }
  203. }
  204. c.OldMilestone = &oldMilestone
  205. }
  206. if c.MilestoneID > 0 {
  207. var milestone Milestone
  208. has, err := x.ID(c.MilestoneID).Get(&milestone)
  209. if err != nil {
  210. return err
  211. } else if !has {
  212. return ErrMilestoneNotExist{
  213. ID: c.MilestoneID,
  214. }
  215. }
  216. c.Milestone = &milestone
  217. }
  218. return nil
  219. }
  220. // LoadAssignees if comment.Type is CommentTypeAssignees, then load assignees
  221. func (c *Comment) LoadAssignees() error {
  222. var err error
  223. if c.OldAssigneeID > 0 {
  224. c.OldAssignee, err = getUserByID(x, c.OldAssigneeID)
  225. if err != nil {
  226. return err
  227. }
  228. }
  229. if c.AssigneeID > 0 {
  230. c.Assignee, err = getUserByID(x, c.AssigneeID)
  231. if err != nil {
  232. return err
  233. }
  234. }
  235. return nil
  236. }
  237. // MailParticipants sends new comment emails to repository watchers
  238. // and mentioned people.
  239. func (c *Comment) MailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
  240. mentions := markdown.FindAllMentions(c.Content)
  241. if err = UpdateIssueMentions(e, c.IssueID, mentions); err != nil {
  242. return fmt.Errorf("UpdateIssueMentions [%d]: %v", c.IssueID, err)
  243. }
  244. switch opType {
  245. case ActionCommentIssue:
  246. issue.Content = c.Content
  247. case ActionCloseIssue:
  248. issue.Content = fmt.Sprintf("Closed #%d", issue.Index)
  249. case ActionReopenIssue:
  250. issue.Content = fmt.Sprintf("Reopened #%d", issue.Index)
  251. }
  252. if err = mailIssueCommentToParticipants(issue, c.Poster, mentions); err != nil {
  253. log.Error(4, "mailIssueCommentToParticipants: %v", err)
  254. }
  255. return nil
  256. }
  257. func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err error) {
  258. var LabelID int64
  259. if opts.Label != nil {
  260. LabelID = opts.Label.ID
  261. }
  262. comment := &Comment{
  263. Type: opts.Type,
  264. PosterID: opts.Doer.ID,
  265. Poster: opts.Doer,
  266. IssueID: opts.Issue.ID,
  267. LabelID: LabelID,
  268. OldMilestoneID: opts.OldMilestoneID,
  269. MilestoneID: opts.MilestoneID,
  270. OldAssigneeID: opts.OldAssigneeID,
  271. AssigneeID: opts.AssigneeID,
  272. CommitID: opts.CommitID,
  273. CommitSHA: opts.CommitSHA,
  274. Line: opts.LineNum,
  275. Content: opts.Content,
  276. OldTitle: opts.OldTitle,
  277. NewTitle: opts.NewTitle,
  278. }
  279. if _, err = e.Insert(comment); err != nil {
  280. return nil, err
  281. }
  282. if err = opts.Repo.getOwner(e); err != nil {
  283. return nil, err
  284. }
  285. // Compose comment action, could be plain comment, close or reopen issue/pull request.
  286. // This object will be used to notify watchers in the end of function.
  287. act := &Action{
  288. ActUserID: opts.Doer.ID,
  289. ActUserName: opts.Doer.Name,
  290. Content: fmt.Sprintf("%d|%s", opts.Issue.Index, strings.Split(opts.Content, "\n")[0]),
  291. RepoID: opts.Repo.ID,
  292. RepoUserName: opts.Repo.Owner.Name,
  293. RepoName: opts.Repo.Name,
  294. IsPrivate: opts.Repo.IsPrivate,
  295. }
  296. // Check comment type.
  297. switch opts.Type {
  298. case CommentTypeComment:
  299. act.OpType = ActionCommentIssue
  300. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
  301. return nil, err
  302. }
  303. // Check attachments
  304. attachments := make([]*Attachment, 0, len(opts.Attachments))
  305. for _, uuid := range opts.Attachments {
  306. attach, err := getAttachmentByUUID(e, uuid)
  307. if err != nil {
  308. if IsErrAttachmentNotExist(err) {
  309. continue
  310. }
  311. return nil, fmt.Errorf("getAttachmentByUUID [%s]: %v", uuid, err)
  312. }
  313. attachments = append(attachments, attach)
  314. }
  315. for i := range attachments {
  316. attachments[i].IssueID = opts.Issue.ID
  317. attachments[i].CommentID = comment.ID
  318. // No assign value could be 0, so ignore AllCols().
  319. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  320. return nil, fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  321. }
  322. }
  323. case CommentTypeReopen:
  324. act.OpType = ActionReopenIssue
  325. if opts.Issue.IsPull {
  326. act.OpType = ActionReopenPullRequest
  327. }
  328. if opts.Issue.IsPull {
  329. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls-1 WHERE id=?", opts.Repo.ID)
  330. } else {
  331. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", opts.Repo.ID)
  332. }
  333. if err != nil {
  334. return nil, err
  335. }
  336. case CommentTypeClose:
  337. act.OpType = ActionCloseIssue
  338. if opts.Issue.IsPull {
  339. act.OpType = ActionClosePullRequest
  340. }
  341. if opts.Issue.IsPull {
  342. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls+1 WHERE id=?", opts.Repo.ID)
  343. } else {
  344. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", opts.Repo.ID)
  345. }
  346. if err != nil {
  347. return nil, err
  348. }
  349. }
  350. // Notify watchers for whatever action comes in, ignore if no action type.
  351. if act.OpType > 0 {
  352. if err = notifyWatchers(e, act); err != nil {
  353. log.Error(4, "notifyWatchers: %v", err)
  354. }
  355. if err = comment.MailParticipants(e, act.OpType, opts.Issue); err != nil {
  356. log.Error(4, "MailParticipants: %v", err)
  357. }
  358. }
  359. return comment, nil
  360. }
  361. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  362. cmtType := CommentTypeClose
  363. if !issue.IsClosed {
  364. cmtType = CommentTypeReopen
  365. }
  366. return createComment(e, &CreateCommentOptions{
  367. Type: cmtType,
  368. Doer: doer,
  369. Repo: repo,
  370. Issue: issue,
  371. })
  372. }
  373. func createLabelComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, label *Label, add bool) (*Comment, error) {
  374. var content string
  375. if add {
  376. content = "1"
  377. }
  378. return createComment(e, &CreateCommentOptions{
  379. Type: CommentTypeLabel,
  380. Doer: doer,
  381. Repo: repo,
  382. Issue: issue,
  383. Label: label,
  384. Content: content,
  385. })
  386. }
  387. func createMilestoneComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldMilestoneID, milestoneID int64) (*Comment, error) {
  388. return createComment(e, &CreateCommentOptions{
  389. Type: CommentTypeMilestone,
  390. Doer: doer,
  391. Repo: repo,
  392. Issue: issue,
  393. OldMilestoneID: oldMilestoneID,
  394. MilestoneID: milestoneID,
  395. })
  396. }
  397. func createAssigneeComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldAssigneeID, assigneeID int64) (*Comment, error) {
  398. return createComment(e, &CreateCommentOptions{
  399. Type: CommentTypeAssignees,
  400. Doer: doer,
  401. Repo: repo,
  402. Issue: issue,
  403. OldAssigneeID: oldAssigneeID,
  404. AssigneeID: assigneeID,
  405. })
  406. }
  407. func createChangeTitleComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldTitle, newTitle string) (*Comment, error) {
  408. return createComment(e, &CreateCommentOptions{
  409. Type: CommentTypeChangeTitle,
  410. Doer: doer,
  411. Repo: repo,
  412. Issue: issue,
  413. OldTitle: oldTitle,
  414. NewTitle: newTitle,
  415. })
  416. }
  417. // CreateCommentOptions defines options for creating comment
  418. type CreateCommentOptions struct {
  419. Type CommentType
  420. Doer *User
  421. Repo *Repository
  422. Issue *Issue
  423. Label *Label
  424. OldMilestoneID int64
  425. MilestoneID int64
  426. OldAssigneeID int64
  427. AssigneeID int64
  428. OldTitle string
  429. NewTitle string
  430. CommitID int64
  431. CommitSHA string
  432. LineNum int64
  433. Content string
  434. Attachments []string // UUIDs of attachments
  435. }
  436. // CreateComment creates comment of issue or commit.
  437. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
  438. sess := x.NewSession()
  439. defer sessionRelease(sess)
  440. if err = sess.Begin(); err != nil {
  441. return nil, err
  442. }
  443. comment, err = createComment(sess, opts)
  444. if err != nil {
  445. return nil, err
  446. }
  447. return comment, sess.Commit()
  448. }
  449. // CreateIssueComment creates a plain issue comment.
  450. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  451. return CreateComment(&CreateCommentOptions{
  452. Type: CommentTypeComment,
  453. Doer: doer,
  454. Repo: repo,
  455. Issue: issue,
  456. Content: content,
  457. Attachments: attachments,
  458. })
  459. }
  460. // CreateRefComment creates a commit reference comment to issue.
  461. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  462. if len(commitSHA) == 0 {
  463. return fmt.Errorf("cannot create reference with empty commit SHA")
  464. }
  465. // Check if same reference from same commit has already existed.
  466. has, err := x.Get(&Comment{
  467. Type: CommentTypeCommitRef,
  468. IssueID: issue.ID,
  469. CommitSHA: commitSHA,
  470. })
  471. if err != nil {
  472. return fmt.Errorf("check reference comment: %v", err)
  473. } else if has {
  474. return nil
  475. }
  476. _, err = CreateComment(&CreateCommentOptions{
  477. Type: CommentTypeCommitRef,
  478. Doer: doer,
  479. Repo: repo,
  480. Issue: issue,
  481. CommitSHA: commitSHA,
  482. Content: content,
  483. })
  484. return err
  485. }
  486. // GetCommentByID returns the comment by given ID.
  487. func GetCommentByID(id int64) (*Comment, error) {
  488. c := new(Comment)
  489. has, err := x.Id(id).Get(c)
  490. if err != nil {
  491. return nil, err
  492. } else if !has {
  493. return nil, ErrCommentNotExist{id, 0}
  494. }
  495. return c, nil
  496. }
  497. func getCommentsByIssueIDSince(e Engine, issueID, since int64) ([]*Comment, error) {
  498. comments := make([]*Comment, 0, 10)
  499. sess := e.
  500. Where("issue_id = ?", issueID).
  501. Asc("created_unix")
  502. if since > 0 {
  503. sess.And("updated_unix >= ?", since)
  504. }
  505. return comments, sess.Find(&comments)
  506. }
  507. func getCommentsByRepoIDSince(e Engine, repoID, since int64) ([]*Comment, error) {
  508. comments := make([]*Comment, 0, 10)
  509. sess := e.Where("issue.repo_id = ?", repoID).
  510. Join("INNER", "issue", "issue.id = comment.issue_id").
  511. Asc("comment.created_unix")
  512. if since > 0 {
  513. sess.And("comment.updated_unix >= ?", since)
  514. }
  515. return comments, sess.Find(&comments)
  516. }
  517. func getCommentsByIssueID(e Engine, issueID int64) ([]*Comment, error) {
  518. return getCommentsByIssueIDSince(e, issueID, -1)
  519. }
  520. // GetCommentsByIssueID returns all comments of an issue.
  521. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  522. return getCommentsByIssueID(x, issueID)
  523. }
  524. // GetCommentsByIssueIDSince returns a list of comments of an issue since a given time point.
  525. func GetCommentsByIssueIDSince(issueID, since int64) ([]*Comment, error) {
  526. return getCommentsByIssueIDSince(x, issueID, since)
  527. }
  528. // GetCommentsByRepoIDSince returns a list of comments for all issues in a repo since a given time point.
  529. func GetCommentsByRepoIDSince(repoID, since int64) ([]*Comment, error) {
  530. return getCommentsByRepoIDSince(x, repoID, since)
  531. }
  532. // UpdateComment updates information of comment.
  533. func UpdateComment(c *Comment) error {
  534. _, err := x.Id(c.ID).AllCols().Update(c)
  535. return err
  536. }
  537. // DeleteComment deletes the comment
  538. func DeleteComment(comment *Comment) error {
  539. sess := x.NewSession()
  540. defer sessionRelease(sess)
  541. if err := sess.Begin(); err != nil {
  542. return err
  543. }
  544. if _, err := sess.Delete(&Comment{
  545. ID: comment.ID,
  546. }); err != nil {
  547. return err
  548. }
  549. if comment.Type == CommentTypeComment {
  550. if _, err := sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  551. return err
  552. }
  553. }
  554. return sess.Commit()
  555. }