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