comment.go 14 KB

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