comment.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. package models
  2. import (
  3. "fmt"
  4. "gitote/gitote/models/errors"
  5. "gitote/gitote/pkg/markup"
  6. "strings"
  7. "time"
  8. "github.com/Unknwon/com"
  9. raven "github.com/getsentry/raven-go"
  10. "github.com/go-xorm/xorm"
  11. api "gitlab.com/gitote/go-gitote-client"
  12. log "gopkg.in/clog.v1"
  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. COMMENT_TYPE_COMMENT CommentType = iota
  19. COMMENT_TYPE_REOPEN
  20. COMMENT_TYPE_CLOSE
  21. // References.
  22. COMMENT_TYPE_ISSUE_REF
  23. // Reference from a commit (not part of a pull request)
  24. COMMENT_TYPE_COMMIT_REF
  25. // Reference from a comment
  26. COMMENT_TYPE_COMMENT_REF
  27. // Reference from a pull request
  28. COMMENT_TYPE_PULL_REF
  29. )
  30. type CommentTag int
  31. const (
  32. COMMENT_TAG_NONE CommentTag = iota
  33. COMMENT_TAG_POSTER
  34. COMMENT_TAG_WRITER
  35. COMMENT_TAG_OWNER
  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:"-"`
  43. IssueID int64 `xorm:"INDEX"`
  44. Issue *Issue `xorm:"-" json:"-"`
  45. CommitID int64
  46. Line int64
  47. Content string `xorm:"TEXT"`
  48. RenderedContent string `xorm:"-" json:"-"`
  49. Created time.Time `xorm:"-" json:"-"`
  50. CreatedUnix int64
  51. Updated time.Time `xorm:"-" json:"-"`
  52. UpdatedUnix int64
  53. // Reference issue in commit message
  54. CommitSHA string `xorm:"VARCHAR(40)"`
  55. Attachments []*Attachment `xorm:"-" json:"-"`
  56. // For view issue page.
  57. ShowTag CommentTag `xorm:"-" json:"-"`
  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 = GetUserByID(c.PosterID)
  77. if err != nil {
  78. if errors.IsUserNotExist(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 (cmt *Comment) mailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
  138. mentions := markup.FindAllMentions(cmt.Content)
  139. if err = updateIssueMentions(e, cmt.IssueID, mentions); err != nil {
  140. return fmt.Errorf("UpdateIssueMentions [%d]: %v", cmt.IssueID, err)
  141. }
  142. switch opType {
  143. case ACTION_COMMENT_ISSUE:
  144. issue.Content = cmt.Content
  145. case ACTION_CLOSE_ISSUE:
  146. issue.Content = fmt.Sprintf("Closed #%d", issue.Index)
  147. case ACTION_REOPEN_ISSUE:
  148. issue.Content = fmt.Sprintf("Reopened #%d", issue.Index)
  149. }
  150. if err = mailIssueCommentToParticipants(issue, cmt.Poster, mentions); err != nil {
  151. raven.CaptureErrorAndWait(err, nil)
  152. log.Error(2, "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. if _, err = e.Exec("UPDATE `issue` SET updated_unix = ? WHERE id = ?", time.Now().Unix(), opts.Issue.ID); err != nil {
  236. return nil, fmt.Errorf("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. raven.CaptureErrorAndWait(err, nil)
  242. log.Error(2, "notifyWatchers: %v", err)
  243. }
  244. if err = comment.mailParticipants(e, act.OpType, opts.Issue); err != nil {
  245. raven.CaptureErrorAndWait(err, nil)
  246. log.Error(2, "MailParticipants: %v", err)
  247. }
  248. }
  249. return comment, comment.loadAttributes(e)
  250. }
  251. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  252. cmtType := COMMENT_TYPE_CLOSE
  253. if !issue.IsClosed {
  254. cmtType = COMMENT_TYPE_REOPEN
  255. }
  256. return createComment(e, &CreateCommentOptions{
  257. Type: cmtType,
  258. Doer: doer,
  259. Repo: repo,
  260. Issue: issue,
  261. })
  262. }
  263. type CreateCommentOptions struct {
  264. Type CommentType
  265. Doer *User
  266. Repo *Repository
  267. Issue *Issue
  268. CommitID int64
  269. CommitSHA string
  270. LineNum int64
  271. Content string
  272. Attachments []string // UUIDs of attachments
  273. }
  274. // CreateComment creates comment of issue or commit.
  275. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
  276. sess := x.NewSession()
  277. defer sess.Close()
  278. if err = sess.Begin(); err != nil {
  279. return nil, err
  280. }
  281. comment, err = createComment(sess, opts)
  282. if err != nil {
  283. return nil, err
  284. }
  285. return comment, sess.Commit()
  286. }
  287. // CreateIssueComment creates a plain issue comment.
  288. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  289. comment, err := CreateComment(&CreateCommentOptions{
  290. Type: COMMENT_TYPE_COMMENT,
  291. Doer: doer,
  292. Repo: repo,
  293. Issue: issue,
  294. Content: content,
  295. Attachments: attachments,
  296. })
  297. if err != nil {
  298. return nil, fmt.Errorf("CreateComment: %v", err)
  299. }
  300. comment.Issue = issue
  301. if err = PrepareWebhooks(repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
  302. Action: api.HOOK_ISSUE_COMMENT_CREATED,
  303. Issue: issue.APIFormat(),
  304. Comment: comment.APIFormat(),
  305. Repository: repo.APIFormat(nil),
  306. Sender: doer.APIFormat(),
  307. }); err != nil {
  308. raven.CaptureErrorAndWait(err, nil)
  309. log.Error(2, "PrepareWebhooks [comment_id: %d]: %v", comment.ID, err)
  310. }
  311. return comment, nil
  312. }
  313. // CreateRefComment creates a commit reference comment to issue.
  314. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  315. if len(commitSHA) == 0 {
  316. return fmt.Errorf("cannot create reference with empty commit SHA")
  317. }
  318. // Check if same reference from same commit has already existed.
  319. has, err := x.Get(&Comment{
  320. Type: COMMENT_TYPE_COMMIT_REF,
  321. IssueID: issue.ID,
  322. CommitSHA: commitSHA,
  323. })
  324. if err != nil {
  325. return fmt.Errorf("check reference comment: %v", err)
  326. } else if has {
  327. return nil
  328. }
  329. _, err = CreateComment(&CreateCommentOptions{
  330. Type: COMMENT_TYPE_COMMIT_REF,
  331. Doer: doer,
  332. Repo: repo,
  333. Issue: issue,
  334. CommitSHA: commitSHA,
  335. Content: content,
  336. })
  337. return err
  338. }
  339. // GetCommentByID returns the comment by given ID.
  340. func GetCommentByID(id int64) (*Comment, error) {
  341. c := new(Comment)
  342. has, err := x.Id(id).Get(c)
  343. if err != nil {
  344. return nil, err
  345. } else if !has {
  346. return nil, ErrCommentNotExist{id, 0}
  347. }
  348. return c, c.LoadAttributes()
  349. }
  350. // FIXME: use CommentList to improve performance.
  351. func loadCommentsAttributes(e Engine, comments []*Comment) (err error) {
  352. for i := range comments {
  353. if err = comments[i].loadAttributes(e); err != nil {
  354. return fmt.Errorf("loadAttributes [%d]: %v", comments[i].ID, err)
  355. }
  356. }
  357. return nil
  358. }
  359. func getCommentsByIssueIDSince(e Engine, issueID, since int64) ([]*Comment, error) {
  360. comments := make([]*Comment, 0, 10)
  361. sess := e.Where("issue_id = ?", issueID).Asc("created_unix")
  362. if since > 0 {
  363. sess.And("updated_unix >= ?", since)
  364. }
  365. if err := sess.Find(&comments); err != nil {
  366. return nil, err
  367. }
  368. return comments, loadCommentsAttributes(e, comments)
  369. }
  370. func getCommentsByRepoIDSince(e Engine, repoID, since int64) ([]*Comment, error) {
  371. comments := make([]*Comment, 0, 10)
  372. sess := e.Where("issue.repo_id = ?", repoID).Join("INNER", "issue", "issue.id = comment.issue_id").Asc("comment.created_unix")
  373. if since > 0 {
  374. sess.And("comment.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 getCommentsByIssueID(e Engine, issueID int64) ([]*Comment, error) {
  382. return getCommentsByIssueIDSince(e, issueID, -1)
  383. }
  384. // GetCommentsByIssueID returns all comments of an issue.
  385. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  386. return getCommentsByIssueID(x, issueID)
  387. }
  388. // GetCommentsByIssueIDSince returns a list of comments of an issue since a given time point.
  389. func GetCommentsByIssueIDSince(issueID, since int64) ([]*Comment, error) {
  390. return getCommentsByIssueIDSince(x, issueID, since)
  391. }
  392. // GetCommentsByRepoIDSince returns a list of comments for all issues in a repo since a given time point.
  393. func GetCommentsByRepoIDSince(repoID, since int64) ([]*Comment, error) {
  394. return getCommentsByRepoIDSince(x, repoID, since)
  395. }
  396. // UpdateComment updates information of comment.
  397. func UpdateComment(doer *User, c *Comment, oldContent string) (err error) {
  398. if _, err = x.Id(c.ID).AllCols().Update(c); err != nil {
  399. return err
  400. }
  401. if err = c.Issue.LoadAttributes(); err != nil {
  402. raven.CaptureErrorAndWait(err, nil)
  403. log.Error(2, "Issue.LoadAttributes [issue_id: %d]: %v", c.IssueID, err)
  404. } else if err = PrepareWebhooks(c.Issue.Repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
  405. Action: api.HOOK_ISSUE_COMMENT_EDITED,
  406. Issue: c.Issue.APIFormat(),
  407. Comment: c.APIFormat(),
  408. Changes: &api.ChangesPayload{
  409. Body: &api.ChangesFromPayload{
  410. From: oldContent,
  411. },
  412. },
  413. Repository: c.Issue.Repo.APIFormat(nil),
  414. Sender: doer.APIFormat(),
  415. }); err != nil {
  416. raven.CaptureErrorAndWait(err, nil)
  417. log.Error(2, "PrepareWebhooks [comment_id: %d]: %v", c.ID, err)
  418. }
  419. return nil
  420. }
  421. // DeleteCommentByID deletes the comment by given ID.
  422. func DeleteCommentByID(doer *User, id int64) error {
  423. comment, err := GetCommentByID(id)
  424. if err != nil {
  425. if IsErrCommentNotExist(err) {
  426. return nil
  427. }
  428. return err
  429. }
  430. sess := x.NewSession()
  431. defer sess.Close()
  432. if err = sess.Begin(); err != nil {
  433. return err
  434. }
  435. if _, err = sess.ID(comment.ID).Delete(new(Comment)); err != nil {
  436. return err
  437. }
  438. if comment.Type == COMMENT_TYPE_COMMENT {
  439. if _, err = sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  440. return err
  441. }
  442. }
  443. if err = sess.Commit(); err != nil {
  444. return fmt.Errorf("commit: %v", err)
  445. }
  446. _, err = DeleteAttachmentsByComment(comment.ID, true)
  447. if err != nil {
  448. raven.CaptureErrorAndWait(err, nil)
  449. log.Error(2, "Failed to delete attachments by comment[%d]: %v", comment.ID, err)
  450. }
  451. if err = comment.Issue.LoadAttributes(); err != nil {
  452. raven.CaptureErrorAndWait(err, nil)
  453. log.Error(2, "Issue.LoadAttributes [issue_id: %d]: %v", comment.IssueID, err)
  454. } else if err = PrepareWebhooks(comment.Issue.Repo, HOOK_EVENT_ISSUE_COMMENT, &api.IssueCommentPayload{
  455. Action: api.HOOK_ISSUE_COMMENT_DELETED,
  456. Issue: comment.Issue.APIFormat(),
  457. Comment: comment.APIFormat(),
  458. Repository: comment.Issue.Repo.APIFormat(nil),
  459. Sender: doer.APIFormat(),
  460. }); err != nil {
  461. raven.CaptureErrorAndWait(err, nil)
  462. log.Error(2, "PrepareWebhooks [comment_id: %d]: %v", comment.ID, err)
  463. }
  464. return nil
  465. }