comment.go 14 KB

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