comment.go 15 KB

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