comment.go 15 KB

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