comment.go 15 KB

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