comment.go 15 KB

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