comment.go 15 KB

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