comment.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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/gogits/go-gogs-client"
  13. "github.com/gogits/gogs/modules/markdown"
  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. COMMENT_TYPE_COMMENT CommentType = iota
  20. COMMENT_TYPE_REOPEN
  21. COMMENT_TYPE_CLOSE
  22. // References.
  23. COMMENT_TYPE_ISSUE_REF
  24. // Reference from a commit (not part of a pull request)
  25. COMMENT_TYPE_COMMIT_REF
  26. // Reference from a comment
  27. COMMENT_TYPE_COMMENT_REF
  28. // Reference from a pull request
  29. COMMENT_TYPE_PULL_REF
  30. )
  31. type CommentTag int
  32. const (
  33. COMMENT_TAG_NONE CommentTag = iota
  34. COMMENT_TAG_POSTER
  35. COMMENT_TAG_WRITER
  36. COMMENT_TAG_OWNER
  37. )
  38. // Comment represents a comment in commit and issue page.
  39. type Comment struct {
  40. ID int64 `xorm:"pk autoincr"`
  41. Type CommentType
  42. PosterID int64
  43. Poster *User `xorm:"-"`
  44. IssueID int64 `xorm:"INDEX"`
  45. Issue *Issue `xorm:"-"`
  46. CommitID int64
  47. Line int64
  48. Content string `xorm:"TEXT"`
  49. RenderedContent string `xorm:"-"`
  50. Created time.Time `xorm:"-"`
  51. CreatedUnix int64
  52. Updated time.Time `xorm:"-"`
  53. UpdatedUnix int64
  54. // Reference issue in commit message
  55. CommitSHA string `xorm:"VARCHAR(40)"`
  56. Attachments []*Attachment `xorm:"-"`
  57. // For view issue page.
  58. ShowTag CommentTag `xorm:"-"`
  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 = GetUserByID(c.PosterID)
  78. if err != nil {
  79. if IsErrUserNotExist(err) {
  80. c.PosterID = -1
  81. c.Poster = NewGhostUser()
  82. } else {
  83. return fmt.Errorf("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 fmt.Errorf("getIssueByID [%d]: %v", c.IssueID, err)
  91. }
  92. }
  93. if c.Attachments == nil {
  94. c.Attachments, err = getAttachmentsByCommentID(e, c.ID)
  95. if err != nil {
  96. return fmt.Errorf("getAttachmentsByCommentID [%d]: %v", c.ID, err)
  97. }
  98. }
  99. return nil
  100. }
  101. func (c *Comment) LoadAttributes() error {
  102. return c.loadAttributes(x)
  103. }
  104. func (c *Comment) AfterDelete() {
  105. _, err := DeleteAttachmentsByComment(c.ID, true)
  106. if err != nil {
  107. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  108. }
  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-" + com.ToStr(id)
  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-" + com.ToStr(c.ID)
  135. }
  136. // mailParticipants sends new comment emails to repository watchers
  137. // and mentioned people.
  138. func (cmt *Comment) mailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
  139. mentions := markdown.FindAllMentions(cmt.Content)
  140. if err = updateIssueMentions(e, cmt.IssueID, mentions); err != nil {
  141. return fmt.Errorf("UpdateIssueMentions [%d]: %v", cmt.IssueID, err)
  142. }
  143. switch opType {
  144. case ACTION_COMMENT_ISSUE:
  145. issue.Content = cmt.Content
  146. case ACTION_CLOSE_ISSUE:
  147. issue.Content = fmt.Sprintf("Closed #%d", issue.Index)
  148. case ACTION_REOPEN_ISSUE:
  149. issue.Content = fmt.Sprintf("Reopened #%d", issue.Index)
  150. }
  151. if err = mailIssueCommentToParticipants(issue, cmt.Poster, mentions); err != nil {
  152. log.Error(4, "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 COMMENT_TYPE_COMMENT:
  184. act.OpType = ACTION_COMMENT_ISSUE
  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, fmt.Errorf("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, fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  206. }
  207. }
  208. case COMMENT_TYPE_REOPEN:
  209. act.OpType = ACTION_REOPEN_ISSUE
  210. if opts.Issue.IsPull {
  211. act.OpType = ACTION_REOPEN_PULL_REQUEST
  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 COMMENT_TYPE_CLOSE:
  222. act.OpType = ACTION_CLOSE_ISSUE
  223. if opts.Issue.IsPull {
  224. act.OpType = ACTION_CLOSE_PULL_REQUEST
  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. // Notify watchers for whatever action comes in, ignore if no action type.
  236. if act.OpType > 0 {
  237. if err = notifyWatchers(e, act); err != nil {
  238. log.Error(4, "notifyWatchers: %v", err)
  239. }
  240. if err = comment.mailParticipants(e, act.OpType, opts.Issue); err != nil {
  241. log.Error(4, "MailParticipants: %v", err)
  242. }
  243. }
  244. return comment, comment.loadAttributes(e)
  245. }
  246. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  247. cmtType := COMMENT_TYPE_CLOSE
  248. if !issue.IsClosed {
  249. cmtType = COMMENT_TYPE_REOPEN
  250. }
  251. return createComment(e, &CreateCommentOptions{
  252. Type: cmtType,
  253. Doer: doer,
  254. Repo: repo,
  255. Issue: issue,
  256. })
  257. }
  258. type CreateCommentOptions struct {
  259. Type CommentType
  260. Doer *User
  261. Repo *Repository
  262. Issue *Issue
  263. CommitID int64
  264. CommitSHA string
  265. LineNum int64
  266. Content string
  267. Attachments []string // UUIDs of attachments
  268. }
  269. // CreateComment creates comment of issue or commit.
  270. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
  271. sess := x.NewSession()
  272. defer sessionRelease(sess)
  273. if err = sess.Begin(); err != nil {
  274. return nil, err
  275. }
  276. comment, err = createComment(sess, opts)
  277. if err != nil {
  278. return nil, err
  279. }
  280. return comment, sess.Commit()
  281. }
  282. // CreateIssueComment creates a plain issue comment.
  283. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  284. comment, err := CreateComment(&CreateCommentOptions{
  285. Type: COMMENT_TYPE_COMMENT,
  286. Doer: doer,
  287. Repo: repo,
  288. Issue: issue,
  289. Content: content,
  290. Attachments: attachments,
  291. })
  292. if err != nil {
  293. return nil, fmt.Errorf("CreateComment: %v", err)
  294. }
  295. comment.Issue = issue
  296. if err = PrepareWebhooks(repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
  297. Action: api.HOOK_ISSUE_COMMENT_CREATED,
  298. Issue: issue.APIFormat(),
  299. Comment: comment.APIFormat(),
  300. Repository: repo.APIFormat(nil),
  301. Sender: doer.APIFormat(),
  302. }); err != nil {
  303. log.Error(2, "PrepareWebhooks [comment_id: %d]: %v", comment.ID, err)
  304. }
  305. return comment, nil
  306. }
  307. // CreateRefComment creates a commit reference comment to issue.
  308. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  309. if len(commitSHA) == 0 {
  310. return fmt.Errorf("cannot create reference with empty commit SHA")
  311. }
  312. // Check if same reference from same commit has already existed.
  313. has, err := x.Get(&Comment{
  314. Type: COMMENT_TYPE_COMMIT_REF,
  315. IssueID: issue.ID,
  316. CommitSHA: commitSHA,
  317. })
  318. if err != nil {
  319. return fmt.Errorf("check reference comment: %v", err)
  320. } else if has {
  321. return nil
  322. }
  323. _, err = CreateComment(&CreateCommentOptions{
  324. Type: COMMENT_TYPE_COMMIT_REF,
  325. Doer: doer,
  326. Repo: repo,
  327. Issue: issue,
  328. CommitSHA: commitSHA,
  329. Content: content,
  330. })
  331. return err
  332. }
  333. // GetCommentByID returns the comment by given ID.
  334. func GetCommentByID(id int64) (*Comment, error) {
  335. c := new(Comment)
  336. has, err := x.Id(id).Get(c)
  337. if err != nil {
  338. return nil, err
  339. } else if !has {
  340. return nil, ErrCommentNotExist{id, 0}
  341. }
  342. return c, c.LoadAttributes()
  343. }
  344. // FIXME: use CommentList to improve performance.
  345. func loadCommentsAttributes(e Engine, comments []*Comment) (err error) {
  346. for i := range comments {
  347. if err = comments[i].loadAttributes(e); err != nil {
  348. return fmt.Errorf("loadAttributes [%d]: %v", comments[i].ID, err)
  349. }
  350. }
  351. return nil
  352. }
  353. func getCommentsByIssueIDSince(e Engine, issueID, since int64) ([]*Comment, error) {
  354. comments := make([]*Comment, 0, 10)
  355. sess := e.Where("issue_id = ?", issueID).Asc("created_unix")
  356. if since > 0 {
  357. sess.And("updated_unix >= ?", since)
  358. }
  359. if err := sess.Find(&comments); err != nil {
  360. return nil, err
  361. }
  362. return comments, loadCommentsAttributes(e, comments)
  363. }
  364. func getCommentsByRepoIDSince(e Engine, repoID, since int64) ([]*Comment, error) {
  365. comments := make([]*Comment, 0, 10)
  366. sess := e.Where("issue.repo_id = ?", repoID).Join("INNER", "issue", "issue.id = comment.issue_id", repoID).Asc("created_unix")
  367. if since > 0 {
  368. sess.And("updated_unix >= ?", since)
  369. }
  370. if err := sess.Find(&comments); err != nil {
  371. return nil, err
  372. }
  373. return comments, loadCommentsAttributes(e, comments)
  374. }
  375. func getCommentsByIssueID(e Engine, issueID int64) ([]*Comment, error) {
  376. return getCommentsByIssueIDSince(e, issueID, -1)
  377. }
  378. // GetCommentsByIssueID returns all comments of an issue.
  379. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  380. return getCommentsByIssueID(x, issueID)
  381. }
  382. // GetCommentsByIssueIDSince returns a list of comments of an issue since a given time point.
  383. func GetCommentsByIssueIDSince(issueID, since int64) ([]*Comment, error) {
  384. return getCommentsByIssueIDSince(x, issueID, since)
  385. }
  386. // GetCommentsByRepoIDSince returns a list of comments for all issues in a repo since a given time point.
  387. func GetCommentsByRepoIDSince(repoID, since int64) ([]*Comment, error) {
  388. return getCommentsByRepoIDSince(x, repoID, since)
  389. }
  390. // UpdateComment updates information of comment.
  391. func UpdateComment(doer *User, c *Comment, oldContent string) (err error) {
  392. if _, err = x.Id(c.ID).AllCols().Update(c); err != nil {
  393. return err
  394. }
  395. if err = c.Issue.LoadAttributes(); err != nil {
  396. log.Error(2, "Issue.LoadAttributes [issue_id: %d]: %v", c.IssueID, err)
  397. } else if err = PrepareWebhooks(c.Issue.Repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
  398. Action: api.HOOK_ISSUE_COMMENT_EDITED,
  399. Issue: c.Issue.APIFormat(),
  400. Comment: c.APIFormat(),
  401. Changes: &api.ChangesPayload{
  402. Body: &api.ChangesFromPayload{
  403. From: oldContent,
  404. },
  405. },
  406. Repository: c.Issue.Repo.APIFormat(nil),
  407. Sender: doer.APIFormat(),
  408. }); err != nil {
  409. log.Error(2, "PrepareWebhooks [comment_id: %d]: %v", c.ID, err)
  410. }
  411. return nil
  412. }
  413. // DeleteCommentByID deletes the comment by given ID.
  414. func DeleteCommentByID(doer *User, id int64) error {
  415. comment, err := GetCommentByID(id)
  416. if err != nil {
  417. if IsErrCommentNotExist(err) {
  418. return nil
  419. }
  420. return err
  421. }
  422. sess := x.NewSession()
  423. defer sessionRelease(sess)
  424. if err = sess.Begin(); err != nil {
  425. return err
  426. }
  427. if _, err = sess.Id(comment.ID).Delete(new(Comment)); err != nil {
  428. return err
  429. }
  430. if comment.Type == COMMENT_TYPE_COMMENT {
  431. if _, err = sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  432. return err
  433. }
  434. }
  435. if err = sess.Commit(); err != nil {
  436. return fmt.Errorf("Commit: %v", err)
  437. }
  438. if err = comment.Issue.LoadAttributes(); err != nil {
  439. log.Error(2, "Issue.LoadAttributes [issue_id: %d]: %v", comment.IssueID, err)
  440. } else if err = PrepareWebhooks(comment.Issue.Repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
  441. Action: api.HOOK_ISSUE_COMMENT_DELETED,
  442. Issue: comment.Issue.APIFormat(),
  443. Comment: comment.APIFormat(),
  444. Repository: comment.Issue.Repo.APIFormat(nil),
  445. Sender: doer.APIFormat(),
  446. }); err != nil {
  447. log.Error(2, "PrepareWebhooks [comment_id: %d]: %v", comment.ID, err)
  448. }
  449. return nil
  450. }