comment.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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 models
  5. import (
  6. "fmt"
  7. "strings"
  8. "time"
  9. "github.com/Unknwon/com"
  10. "github.com/go-xorm/xorm"
  11. log "gopkg.in/clog.v1"
  12. api "github.com/gogs/go-gogs-client"
  13. "github.com/gogs/gogs/models/errors"
  14. "github.com/gogs/gogs/pkg/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 errors.IsUserNotExist(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(2, "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(2, "notifyWatchers: %v", err)
  243. }
  244. if err = comment.mailParticipants(e, act.OpType, opts.Issue); err != nil {
  245. log.Error(2, "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(2, "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. // GetCommentByID returns the comment by given ID.
  338. func GetCommentByID(id int64) (*Comment, error) {
  339. c := new(Comment)
  340. has, err := x.Id(id).Get(c)
  341. if err != nil {
  342. return nil, err
  343. } else if !has {
  344. return nil, ErrCommentNotExist{id, 0}
  345. }
  346. return c, c.LoadAttributes()
  347. }
  348. // FIXME: use CommentList to improve performance.
  349. func loadCommentsAttributes(e Engine, comments []*Comment) (err error) {
  350. for i := range comments {
  351. if err = comments[i].loadAttributes(e); err != nil {
  352. return fmt.Errorf("loadAttributes [%d]: %v", comments[i].ID, err)
  353. }
  354. }
  355. return nil
  356. }
  357. func getCommentsByIssueIDSince(e Engine, issueID, since int64) ([]*Comment, error) {
  358. comments := make([]*Comment, 0, 10)
  359. sess := e.Where("issue_id = ?", issueID).Asc("created_unix")
  360. if since > 0 {
  361. sess.And("updated_unix >= ?", since)
  362. }
  363. if err := sess.Find(&comments); err != nil {
  364. return nil, err
  365. }
  366. return comments, loadCommentsAttributes(e, comments)
  367. }
  368. func getCommentsByRepoIDSince(e Engine, repoID, since int64) ([]*Comment, error) {
  369. comments := make([]*Comment, 0, 10)
  370. sess := e.Where("issue.repo_id = ?", repoID).Join("INNER", "issue", "issue.id = comment.issue_id").Asc("comment.created_unix")
  371. if since > 0 {
  372. sess.And("comment.updated_unix >= ?", since)
  373. }
  374. if err := sess.Find(&comments); err != nil {
  375. return nil, err
  376. }
  377. return comments, loadCommentsAttributes(e, comments)
  378. }
  379. func getCommentsByIssueID(e Engine, issueID int64) ([]*Comment, error) {
  380. return getCommentsByIssueIDSince(e, issueID, -1)
  381. }
  382. // GetCommentsByIssueID returns all comments of an issue.
  383. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  384. return getCommentsByIssueID(x, issueID)
  385. }
  386. // GetCommentsByIssueIDSince returns a list of comments of an issue since a given time point.
  387. func GetCommentsByIssueIDSince(issueID, since int64) ([]*Comment, error) {
  388. return getCommentsByIssueIDSince(x, issueID, since)
  389. }
  390. // GetCommentsByRepoIDSince returns a list of comments for all issues in a repo since a given time point.
  391. func GetCommentsByRepoIDSince(repoID, since int64) ([]*Comment, error) {
  392. return getCommentsByRepoIDSince(x, repoID, since)
  393. }
  394. // UpdateComment updates information of comment.
  395. func UpdateComment(doer *User, c *Comment, oldContent string) (err error) {
  396. if _, err = x.Id(c.ID).AllCols().Update(c); err != nil {
  397. return err
  398. }
  399. if err = c.Issue.LoadAttributes(); err != nil {
  400. log.Error(2, "Issue.LoadAttributes [issue_id: %d]: %v", c.IssueID, err)
  401. } else if err = PrepareWebhooks(c.Issue.Repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
  402. Action: api.HOOK_ISSUE_COMMENT_EDITED,
  403. Issue: c.Issue.APIFormat(),
  404. Comment: c.APIFormat(),
  405. Changes: &api.ChangesPayload{
  406. Body: &api.ChangesFromPayload{
  407. From: oldContent,
  408. },
  409. },
  410. Repository: c.Issue.Repo.APIFormat(nil),
  411. Sender: doer.APIFormat(),
  412. }); err != nil {
  413. log.Error(2, "PrepareWebhooks [comment_id: %d]: %v", c.ID, err)
  414. }
  415. return nil
  416. }
  417. // DeleteCommentByID deletes the comment by given ID.
  418. func DeleteCommentByID(doer *User, id int64) error {
  419. comment, err := GetCommentByID(id)
  420. if err != nil {
  421. if IsErrCommentNotExist(err) {
  422. return nil
  423. }
  424. return err
  425. }
  426. sess := x.NewSession()
  427. defer sess.Close()
  428. if err = sess.Begin(); err != nil {
  429. return err
  430. }
  431. if _, err = sess.ID(comment.ID).Delete(new(Comment)); err != nil {
  432. return err
  433. }
  434. if comment.Type == COMMENT_TYPE_COMMENT {
  435. if _, err = sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  436. return err
  437. }
  438. }
  439. if err = sess.Commit(); err != nil {
  440. return fmt.Errorf("commit: %v", err)
  441. }
  442. _, err = DeleteAttachmentsByComment(comment.ID, true)
  443. if err != nil {
  444. log.Error(2, "Failed to delete attachments by comment[%d]: %v", comment.ID, err)
  445. }
  446. if err = comment.Issue.LoadAttributes(); err != nil {
  447. log.Error(2, "Issue.LoadAttributes [issue_id: %d]: %v", comment.IssueID, err)
  448. } else if err = PrepareWebhooks(comment.Issue.Repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
  449. Action: api.HOOK_ISSUE_COMMENT_DELETED,
  450. Issue: comment.Issue.APIFormat(),
  451. Comment: comment.APIFormat(),
  452. Repository: comment.Issue.Repo.APIFormat(nil),
  453. Sender: doer.APIFormat(),
  454. }); err != nil {
  455. log.Error(2, "PrepareWebhooks [comment_id: %d]: %v", comment.ID, err)
  456. }
  457. return nil
  458. }