comment.go 15 KB

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