comment.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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. log "gopkg.in/clog.v1"
  12. api "github.com/gogits/go-gogs-client"
  13. "github.com/gogits/gogs/models/errors"
  14. "github.com/gogits/gogs/modules/markup"
  15. )
  16. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  17. type CommentType int
  18. const (
  19. // Plain comment, can be associated with a commit (CommitID > 0) and a line (LineNum > 0)
  20. COMMENT_TYPE_COMMENT CommentType = iota
  21. COMMENT_TYPE_REOPEN
  22. COMMENT_TYPE_CLOSE
  23. // References.
  24. COMMENT_TYPE_ISSUE_REF
  25. // Reference from a commit (not part of a pull request)
  26. COMMENT_TYPE_COMMIT_REF
  27. // Reference from a comment
  28. COMMENT_TYPE_COMMENT_REF
  29. // Reference from a pull request
  30. COMMENT_TYPE_PULL_REF
  31. )
  32. type CommentTag int
  33. const (
  34. COMMENT_TAG_NONE CommentTag = iota
  35. COMMENT_TAG_POSTER
  36. COMMENT_TAG_WRITER
  37. COMMENT_TAG_OWNER
  38. )
  39. // Comment represents a comment in commit and issue page.
  40. type Comment struct {
  41. ID int64 `xorm:"pk autoincr"`
  42. Type CommentType
  43. PosterID int64
  44. Poster *User `xorm:"-"`
  45. IssueID int64 `xorm:"INDEX"`
  46. Issue *Issue `xorm:"-"`
  47. CommitID int64
  48. Line int64
  49. Content string `xorm:"TEXT"`
  50. RenderedContent string `xorm:"-"`
  51. Created time.Time `xorm:"-"`
  52. CreatedUnix int64
  53. Updated time.Time `xorm:"-"`
  54. UpdatedUnix int64
  55. // Reference issue in commit message
  56. CommitSHA string `xorm:"VARCHAR(40)"`
  57. Attachments []*Attachment `xorm:"-"`
  58. // For view issue page.
  59. ShowTag CommentTag `xorm:"-"`
  60. }
  61. func (c *Comment) BeforeInsert() {
  62. c.CreatedUnix = time.Now().Unix()
  63. c.UpdatedUnix = c.CreatedUnix
  64. }
  65. func (c *Comment) BeforeUpdate() {
  66. c.UpdatedUnix = time.Now().Unix()
  67. }
  68. func (c *Comment) AfterSet(colName string, _ xorm.Cell) {
  69. switch colName {
  70. case "created_unix":
  71. c.Created = time.Unix(c.CreatedUnix, 0).Local()
  72. case "updated_unix":
  73. c.Updated = time.Unix(c.UpdatedUnix, 0).Local()
  74. }
  75. }
  76. func (c *Comment) loadAttributes(e Engine) (err error) {
  77. if c.Poster == nil {
  78. c.Poster, err = GetUserByID(c.PosterID)
  79. if err != nil {
  80. if errors.IsUserNotExist(err) {
  81. c.PosterID = -1
  82. c.Poster = NewGhostUser()
  83. } else {
  84. return fmt.Errorf("getUserByID.(Poster) [%d]: %v", c.PosterID, err)
  85. }
  86. }
  87. }
  88. if c.Issue == nil {
  89. c.Issue, err = getRawIssueByID(e, c.IssueID)
  90. if err != nil {
  91. return fmt.Errorf("getIssueByID [%d]: %v", c.IssueID, err)
  92. }
  93. }
  94. if c.Attachments == nil {
  95. c.Attachments, err = getAttachmentsByCommentID(e, c.ID)
  96. if err != nil {
  97. return fmt.Errorf("getAttachmentsByCommentID [%d]: %v", c.ID, err)
  98. }
  99. }
  100. return nil
  101. }
  102. func (c *Comment) LoadAttributes() error {
  103. return c.loadAttributes(x)
  104. }
  105. func (c *Comment) AfterDelete() {
  106. _, err := DeleteAttachmentsByComment(c.ID, true)
  107. if err != nil {
  108. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  109. }
  110. }
  111. func (c *Comment) HTMLURL() string {
  112. return fmt.Sprintf("%s#issuecomment-%d", c.Issue.HTMLURL(), c.ID)
  113. }
  114. // This method assumes following fields have been assigned with valid values:
  115. // Required - Poster, Issue
  116. func (c *Comment) APIFormat() *api.Comment {
  117. return &api.Comment{
  118. ID: c.ID,
  119. HTMLURL: c.HTMLURL(),
  120. Poster: c.Poster.APIFormat(),
  121. Body: c.Content,
  122. Created: c.Created,
  123. Updated: c.Updated,
  124. }
  125. }
  126. func CommentHashTag(id int64) string {
  127. return "issuecomment-" + com.ToStr(id)
  128. }
  129. // HashTag returns unique hash tag for comment.
  130. func (c *Comment) HashTag() string {
  131. return CommentHashTag(c.ID)
  132. }
  133. // EventTag returns unique event hash tag for comment.
  134. func (c *Comment) EventTag() string {
  135. return "event-" + com.ToStr(c.ID)
  136. }
  137. // mailParticipants sends new comment emails to repository watchers
  138. // and mentioned people.
  139. func (cmt *Comment) mailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
  140. mentions := markup.FindAllMentions(cmt.Content)
  141. if err = updateIssueMentions(e, cmt.IssueID, mentions); err != nil {
  142. return fmt.Errorf("UpdateIssueMentions [%d]: %v", cmt.IssueID, err)
  143. }
  144. switch opType {
  145. case ACTION_COMMENT_ISSUE:
  146. issue.Content = cmt.Content
  147. case ACTION_CLOSE_ISSUE:
  148. issue.Content = fmt.Sprintf("Closed #%d", issue.Index)
  149. case ACTION_REOPEN_ISSUE:
  150. issue.Content = fmt.Sprintf("Reopened #%d", issue.Index)
  151. }
  152. if err = mailIssueCommentToParticipants(issue, cmt.Poster, mentions); err != nil {
  153. log.Error(4, "mailIssueCommentToParticipants: %v", err)
  154. }
  155. return nil
  156. }
  157. func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err error) {
  158. comment := &Comment{
  159. Type: opts.Type,
  160. PosterID: opts.Doer.ID,
  161. Poster: opts.Doer,
  162. IssueID: opts.Issue.ID,
  163. CommitID: opts.CommitID,
  164. CommitSHA: opts.CommitSHA,
  165. Line: opts.LineNum,
  166. Content: opts.Content,
  167. }
  168. if _, err = e.Insert(comment); err != nil {
  169. return nil, err
  170. }
  171. // Compose comment action, could be plain comment, close or reopen issue/pull request.
  172. // This object will be used to notify watchers in the end of function.
  173. act := &Action{
  174. ActUserID: opts.Doer.ID,
  175. ActUserName: opts.Doer.Name,
  176. Content: fmt.Sprintf("%d|%s", opts.Issue.Index, strings.Split(opts.Content, "\n")[0]),
  177. RepoID: opts.Repo.ID,
  178. RepoUserName: opts.Repo.Owner.Name,
  179. RepoName: opts.Repo.Name,
  180. IsPrivate: opts.Repo.IsPrivate,
  181. }
  182. // Check comment type.
  183. switch opts.Type {
  184. case COMMENT_TYPE_COMMENT:
  185. act.OpType = ACTION_COMMENT_ISSUE
  186. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
  187. return nil, err
  188. }
  189. // Check attachments
  190. attachments := make([]*Attachment, 0, len(opts.Attachments))
  191. for _, uuid := range opts.Attachments {
  192. attach, err := getAttachmentByUUID(e, uuid)
  193. if err != nil {
  194. if IsErrAttachmentNotExist(err) {
  195. continue
  196. }
  197. return nil, fmt.Errorf("getAttachmentByUUID [%s]: %v", uuid, err)
  198. }
  199. attachments = append(attachments, attach)
  200. }
  201. for i := range attachments {
  202. attachments[i].IssueID = opts.Issue.ID
  203. attachments[i].CommentID = comment.ID
  204. // No assign value could be 0, so ignore AllCols().
  205. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  206. return nil, fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  207. }
  208. }
  209. case COMMENT_TYPE_REOPEN:
  210. act.OpType = ACTION_REOPEN_ISSUE
  211. if opts.Issue.IsPull {
  212. act.OpType = ACTION_REOPEN_PULL_REQUEST
  213. }
  214. if opts.Issue.IsPull {
  215. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls-1 WHERE id=?", opts.Repo.ID)
  216. } else {
  217. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", opts.Repo.ID)
  218. }
  219. if err != nil {
  220. return nil, err
  221. }
  222. case COMMENT_TYPE_CLOSE:
  223. act.OpType = ACTION_CLOSE_ISSUE
  224. if opts.Issue.IsPull {
  225. act.OpType = ACTION_CLOSE_PULL_REQUEST
  226. }
  227. if opts.Issue.IsPull {
  228. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls+1 WHERE id=?", opts.Repo.ID)
  229. } else {
  230. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", opts.Repo.ID)
  231. }
  232. if err != nil {
  233. return nil, err
  234. }
  235. }
  236. // Notify watchers for whatever action comes in, ignore if no action type.
  237. if act.OpType > 0 {
  238. if err = notifyWatchers(e, act); err != nil {
  239. log.Error(4, "notifyWatchers: %v", err)
  240. }
  241. if err = comment.mailParticipants(e, act.OpType, opts.Issue); err != nil {
  242. log.Error(4, "MailParticipants: %v", err)
  243. }
  244. }
  245. return comment, comment.loadAttributes(e)
  246. }
  247. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  248. cmtType := COMMENT_TYPE_CLOSE
  249. if !issue.IsClosed {
  250. cmtType = COMMENT_TYPE_REOPEN
  251. }
  252. return createComment(e, &CreateCommentOptions{
  253. Type: cmtType,
  254. Doer: doer,
  255. Repo: repo,
  256. Issue: issue,
  257. })
  258. }
  259. type CreateCommentOptions struct {
  260. Type CommentType
  261. Doer *User
  262. Repo *Repository
  263. Issue *Issue
  264. CommitID int64
  265. CommitSHA string
  266. LineNum int64
  267. Content string
  268. Attachments []string // UUIDs of attachments
  269. }
  270. // CreateComment creates comment of issue or commit.
  271. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
  272. sess := x.NewSession()
  273. defer sessionRelease(sess)
  274. if err = sess.Begin(); err != nil {
  275. return nil, err
  276. }
  277. comment, err = createComment(sess, opts)
  278. if err != nil {
  279. return nil, err
  280. }
  281. return comment, sess.Commit()
  282. }
  283. // CreateIssueComment creates a plain issue comment.
  284. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  285. comment, err := CreateComment(&CreateCommentOptions{
  286. Type: COMMENT_TYPE_COMMENT,
  287. Doer: doer,
  288. Repo: repo,
  289. Issue: issue,
  290. Content: content,
  291. Attachments: attachments,
  292. })
  293. if err != nil {
  294. return nil, fmt.Errorf("CreateComment: %v", err)
  295. }
  296. comment.Issue = issue
  297. if err = PrepareWebhooks(repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
  298. Action: api.HOOK_ISSUE_COMMENT_CREATED,
  299. Issue: issue.APIFormat(),
  300. Comment: comment.APIFormat(),
  301. Repository: repo.APIFormat(nil),
  302. Sender: doer.APIFormat(),
  303. }); err != nil {
  304. log.Error(2, "PrepareWebhooks [comment_id: %d]: %v", comment.ID, err)
  305. }
  306. return comment, nil
  307. }
  308. // CreateRefComment creates a commit reference comment to issue.
  309. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  310. if len(commitSHA) == 0 {
  311. return fmt.Errorf("cannot create reference with empty commit SHA")
  312. }
  313. // Check if same reference from same commit has already existed.
  314. has, err := x.Get(&Comment{
  315. Type: COMMENT_TYPE_COMMIT_REF,
  316. IssueID: issue.ID,
  317. CommitSHA: commitSHA,
  318. })
  319. if err != nil {
  320. return fmt.Errorf("check reference comment: %v", err)
  321. } else if has {
  322. return nil
  323. }
  324. _, err = CreateComment(&CreateCommentOptions{
  325. Type: COMMENT_TYPE_COMMIT_REF,
  326. Doer: doer,
  327. Repo: repo,
  328. Issue: issue,
  329. CommitSHA: commitSHA,
  330. Content: content,
  331. })
  332. return err
  333. }
  334. // GetCommentByID returns the comment by given ID.
  335. func GetCommentByID(id int64) (*Comment, error) {
  336. c := new(Comment)
  337. has, err := x.Id(id).Get(c)
  338. if err != nil {
  339. return nil, err
  340. } else if !has {
  341. return nil, ErrCommentNotExist{id, 0}
  342. }
  343. return c, c.LoadAttributes()
  344. }
  345. // FIXME: use CommentList to improve performance.
  346. func loadCommentsAttributes(e Engine, comments []*Comment) (err error) {
  347. for i := range comments {
  348. if err = comments[i].loadAttributes(e); err != nil {
  349. return fmt.Errorf("loadAttributes [%d]: %v", comments[i].ID, err)
  350. }
  351. }
  352. return nil
  353. }
  354. func getCommentsByIssueIDSince(e Engine, issueID, since int64) ([]*Comment, error) {
  355. comments := make([]*Comment, 0, 10)
  356. sess := e.Where("issue_id = ?", issueID).Asc("created_unix")
  357. if since > 0 {
  358. sess.And("updated_unix >= ?", since)
  359. }
  360. if err := sess.Find(&comments); err != nil {
  361. return nil, err
  362. }
  363. return comments, loadCommentsAttributes(e, comments)
  364. }
  365. func getCommentsByRepoIDSince(e Engine, repoID, since int64) ([]*Comment, error) {
  366. comments := make([]*Comment, 0, 10)
  367. sess := e.Where("issue.repo_id = ?", repoID).Join("INNER", "issue", "issue.id = comment.issue_id", repoID).Asc("created_unix")
  368. if since > 0 {
  369. sess.And("updated_unix >= ?", since)
  370. }
  371. if err := sess.Find(&comments); err != nil {
  372. return nil, err
  373. }
  374. return comments, loadCommentsAttributes(e, comments)
  375. }
  376. func getCommentsByIssueID(e Engine, issueID int64) ([]*Comment, error) {
  377. return getCommentsByIssueIDSince(e, issueID, -1)
  378. }
  379. // GetCommentsByIssueID returns all comments of an issue.
  380. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  381. return getCommentsByIssueID(x, issueID)
  382. }
  383. // GetCommentsByIssueIDSince returns a list of comments of an issue since a given time point.
  384. func GetCommentsByIssueIDSince(issueID, since int64) ([]*Comment, error) {
  385. return getCommentsByIssueIDSince(x, issueID, since)
  386. }
  387. // GetCommentsByRepoIDSince returns a list of comments for all issues in a repo since a given time point.
  388. func GetCommentsByRepoIDSince(repoID, since int64) ([]*Comment, error) {
  389. return getCommentsByRepoIDSince(x, repoID, since)
  390. }
  391. // UpdateComment updates information of comment.
  392. func UpdateComment(doer *User, c *Comment, oldContent string) (err error) {
  393. if _, err = x.Id(c.ID).AllCols().Update(c); err != nil {
  394. return err
  395. }
  396. if err = c.Issue.LoadAttributes(); err != nil {
  397. log.Error(2, "Issue.LoadAttributes [issue_id: %d]: %v", c.IssueID, err)
  398. } else if err = PrepareWebhooks(c.Issue.Repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
  399. Action: api.HOOK_ISSUE_COMMENT_EDITED,
  400. Issue: c.Issue.APIFormat(),
  401. Comment: c.APIFormat(),
  402. Changes: &api.ChangesPayload{
  403. Body: &api.ChangesFromPayload{
  404. From: oldContent,
  405. },
  406. },
  407. Repository: c.Issue.Repo.APIFormat(nil),
  408. Sender: doer.APIFormat(),
  409. }); err != nil {
  410. log.Error(2, "PrepareWebhooks [comment_id: %d]: %v", c.ID, err)
  411. }
  412. return nil
  413. }
  414. // DeleteCommentByID deletes the comment by given ID.
  415. func DeleteCommentByID(doer *User, id int64) error {
  416. comment, err := GetCommentByID(id)
  417. if err != nil {
  418. if IsErrCommentNotExist(err) {
  419. return nil
  420. }
  421. return err
  422. }
  423. sess := x.NewSession()
  424. defer sessionRelease(sess)
  425. if err = sess.Begin(); err != nil {
  426. return err
  427. }
  428. if _, err = sess.Id(comment.ID).Delete(new(Comment)); err != nil {
  429. return err
  430. }
  431. if comment.Type == COMMENT_TYPE_COMMENT {
  432. if _, err = sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  433. return err
  434. }
  435. }
  436. if err = sess.Commit(); err != nil {
  437. return fmt.Errorf("Commit: %v", err)
  438. }
  439. if err = comment.Issue.LoadAttributes(); err != nil {
  440. log.Error(2, "Issue.LoadAttributes [issue_id: %d]: %v", comment.IssueID, err)
  441. } else if err = PrepareWebhooks(comment.Issue.Repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
  442. Action: api.HOOK_ISSUE_COMMENT_DELETED,
  443. Issue: comment.Issue.APIFormat(),
  444. Comment: comment.APIFormat(),
  445. Repository: comment.Issue.Repo.APIFormat(nil),
  446. Sender: doer.APIFormat(),
  447. }); err != nil {
  448. log.Error(2, "PrepareWebhooks [comment_id: %d]: %v", comment.ID, err)
  449. }
  450. return nil
  451. }