comment.go 15 KB

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