comment.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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. // HashTag returns unique hash tag for comment.
  126. func (c *Comment) HashTag() string {
  127. return "issuecomment-" + com.ToStr(c.ID)
  128. }
  129. // EventTag returns unique event hash tag for comment.
  130. func (c *Comment) EventTag() string {
  131. return "event-" + com.ToStr(c.ID)
  132. }
  133. // mailParticipants sends new comment emails to repository watchers
  134. // and mentioned people.
  135. func (cmt *Comment) mailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
  136. mentions := markdown.FindAllMentions(cmt.Content)
  137. if err = updateIssueMentions(e, cmt.IssueID, mentions); err != nil {
  138. return fmt.Errorf("UpdateIssueMentions [%d]: %v", cmt.IssueID, err)
  139. }
  140. switch opType {
  141. case ACTION_COMMENT_ISSUE:
  142. issue.Content = cmt.Content
  143. case ACTION_CLOSE_ISSUE:
  144. issue.Content = fmt.Sprintf("Closed #%d", issue.Index)
  145. case ACTION_REOPEN_ISSUE:
  146. issue.Content = fmt.Sprintf("Reopened #%d", issue.Index)
  147. }
  148. if err = mailIssueCommentToParticipants(issue, cmt.Poster, mentions); err != nil {
  149. log.Error(4, "mailIssueCommentToParticipants: %v", err)
  150. }
  151. return nil
  152. }
  153. func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err error) {
  154. comment := &Comment{
  155. Type: opts.Type,
  156. PosterID: opts.Doer.ID,
  157. Poster: opts.Doer,
  158. IssueID: opts.Issue.ID,
  159. CommitID: opts.CommitID,
  160. CommitSHA: opts.CommitSHA,
  161. Line: opts.LineNum,
  162. Content: opts.Content,
  163. }
  164. if _, err = e.Insert(comment); err != nil {
  165. return nil, err
  166. }
  167. // Compose comment action, could be plain comment, close or reopen issue/pull request.
  168. // This object will be used to notify watchers in the end of function.
  169. act := &Action{
  170. ActUserID: opts.Doer.ID,
  171. ActUserName: opts.Doer.Name,
  172. Content: fmt.Sprintf("%d|%s", opts.Issue.Index, strings.Split(opts.Content, "\n")[0]),
  173. RepoID: opts.Repo.ID,
  174. RepoUserName: opts.Repo.Owner.Name,
  175. RepoName: opts.Repo.Name,
  176. IsPrivate: opts.Repo.IsPrivate,
  177. }
  178. // Check comment type.
  179. switch opts.Type {
  180. case COMMENT_TYPE_COMMENT:
  181. act.OpType = ACTION_COMMENT_ISSUE
  182. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
  183. return nil, err
  184. }
  185. // Check attachments
  186. attachments := make([]*Attachment, 0, len(opts.Attachments))
  187. for _, uuid := range opts.Attachments {
  188. attach, err := getAttachmentByUUID(e, uuid)
  189. if err != nil {
  190. if IsErrAttachmentNotExist(err) {
  191. continue
  192. }
  193. return nil, fmt.Errorf("getAttachmentByUUID [%s]: %v", uuid, err)
  194. }
  195. attachments = append(attachments, attach)
  196. }
  197. for i := range attachments {
  198. attachments[i].IssueID = opts.Issue.ID
  199. attachments[i].CommentID = comment.ID
  200. // No assign value could be 0, so ignore AllCols().
  201. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  202. return nil, fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  203. }
  204. }
  205. case COMMENT_TYPE_REOPEN:
  206. act.OpType = ACTION_REOPEN_ISSUE
  207. if opts.Issue.IsPull {
  208. act.OpType = ACTION_REOPEN_PULL_REQUEST
  209. }
  210. if opts.Issue.IsPull {
  211. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls-1 WHERE id=?", opts.Repo.ID)
  212. } else {
  213. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", opts.Repo.ID)
  214. }
  215. if err != nil {
  216. return nil, err
  217. }
  218. case COMMENT_TYPE_CLOSE:
  219. act.OpType = ACTION_CLOSE_ISSUE
  220. if opts.Issue.IsPull {
  221. act.OpType = ACTION_CLOSE_PULL_REQUEST
  222. }
  223. if opts.Issue.IsPull {
  224. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls+1 WHERE id=?", opts.Repo.ID)
  225. } else {
  226. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", opts.Repo.ID)
  227. }
  228. if err != nil {
  229. return nil, err
  230. }
  231. }
  232. // Notify watchers for whatever action comes in, ignore if no action type.
  233. if act.OpType > 0 {
  234. if err = notifyWatchers(e, act); err != nil {
  235. log.Error(4, "notifyWatchers: %v", err)
  236. }
  237. if err = comment.mailParticipants(e, act.OpType, opts.Issue); err != nil {
  238. log.Error(4, "MailParticipants: %v", err)
  239. }
  240. }
  241. return comment, comment.loadAttributes(e)
  242. }
  243. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  244. cmtType := COMMENT_TYPE_CLOSE
  245. if !issue.IsClosed {
  246. cmtType = COMMENT_TYPE_REOPEN
  247. }
  248. return createComment(e, &CreateCommentOptions{
  249. Type: cmtType,
  250. Doer: doer,
  251. Repo: repo,
  252. Issue: issue,
  253. })
  254. }
  255. type CreateCommentOptions struct {
  256. Type CommentType
  257. Doer *User
  258. Repo *Repository
  259. Issue *Issue
  260. CommitID int64
  261. CommitSHA string
  262. LineNum int64
  263. Content string
  264. Attachments []string // UUIDs of attachments
  265. }
  266. // CreateComment creates comment of issue or commit.
  267. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
  268. sess := x.NewSession()
  269. defer sessionRelease(sess)
  270. if err = sess.Begin(); err != nil {
  271. return nil, err
  272. }
  273. comment, err = createComment(sess, opts)
  274. if err != nil {
  275. return nil, err
  276. }
  277. return comment, sess.Commit()
  278. }
  279. // CreateIssueComment creates a plain issue comment.
  280. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  281. return CreateComment(&CreateCommentOptions{
  282. Type: COMMENT_TYPE_COMMENT,
  283. Doer: doer,
  284. Repo: repo,
  285. Issue: issue,
  286. Content: content,
  287. Attachments: attachments,
  288. })
  289. }
  290. // CreateRefComment creates a commit reference comment to issue.
  291. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  292. if len(commitSHA) == 0 {
  293. return fmt.Errorf("cannot create reference with empty commit SHA")
  294. }
  295. // Check if same reference from same commit has already existed.
  296. has, err := x.Get(&Comment{
  297. Type: COMMENT_TYPE_COMMIT_REF,
  298. IssueID: issue.ID,
  299. CommitSHA: commitSHA,
  300. })
  301. if err != nil {
  302. return fmt.Errorf("check reference comment: %v", err)
  303. } else if has {
  304. return nil
  305. }
  306. _, err = CreateComment(&CreateCommentOptions{
  307. Type: COMMENT_TYPE_COMMIT_REF,
  308. Doer: doer,
  309. Repo: repo,
  310. Issue: issue,
  311. CommitSHA: commitSHA,
  312. Content: content,
  313. })
  314. return err
  315. }
  316. // GetCommentByID returns the comment by given ID.
  317. func GetCommentByID(id int64) (*Comment, error) {
  318. c := new(Comment)
  319. has, err := x.Id(id).Get(c)
  320. if err != nil {
  321. return nil, err
  322. } else if !has {
  323. return nil, ErrCommentNotExist{id, 0}
  324. }
  325. return c, c.LoadAttributes()
  326. }
  327. // FIXME: use CommentList to improve performance.
  328. func loadCommentsAttributes(e Engine, comments []*Comment) (err error) {
  329. for i := range comments {
  330. if err = comments[i].loadAttributes(e); err != nil {
  331. return fmt.Errorf("loadAttributes [%d]: %v", comments[i].ID, err)
  332. }
  333. }
  334. return nil
  335. }
  336. func getCommentsByIssueIDSince(e Engine, issueID, since int64) ([]*Comment, error) {
  337. comments := make([]*Comment, 0, 10)
  338. sess := e.Where("issue_id = ?", issueID).Asc("created_unix")
  339. if since > 0 {
  340. sess.And("updated_unix >= ?", since)
  341. }
  342. if err := sess.Find(&comments); err != nil {
  343. return nil, err
  344. }
  345. return comments, loadCommentsAttributes(e, comments)
  346. }
  347. func getCommentsByRepoIDSince(e Engine, repoID, since int64) ([]*Comment, error) {
  348. comments := make([]*Comment, 0, 10)
  349. sess := e.Where("issue.repo_id = ?", repoID).Join("INNER", "issue", "issue.id = comment.issue_id", repoID).Asc("created_unix")
  350. if since > 0 {
  351. sess.And("updated_unix >= ?", since)
  352. }
  353. if err := sess.Find(&comments); err != nil {
  354. return nil, err
  355. }
  356. return comments, loadCommentsAttributes(e, comments)
  357. }
  358. func getCommentsByIssueID(e Engine, issueID int64) ([]*Comment, error) {
  359. return getCommentsByIssueIDSince(e, issueID, -1)
  360. }
  361. // GetCommentsByIssueID returns all comments of an issue.
  362. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  363. return getCommentsByIssueID(x, issueID)
  364. }
  365. // GetCommentsByIssueIDSince returns a list of comments of an issue since a given time point.
  366. func GetCommentsByIssueIDSince(issueID, since int64) ([]*Comment, error) {
  367. return getCommentsByIssueIDSince(x, issueID, since)
  368. }
  369. // GetCommentsByRepoIDSince returns a list of comments for all issues in a repo since a given time point.
  370. func GetCommentsByRepoIDSince(repoID, since int64) ([]*Comment, error) {
  371. return getCommentsByRepoIDSince(x, repoID, since)
  372. }
  373. // UpdateComment updates information of comment.
  374. func UpdateComment(c *Comment) error {
  375. _, err := x.Id(c.ID).AllCols().Update(c)
  376. return err
  377. }
  378. // DeleteCommentByID deletes the comment by given ID.
  379. func DeleteCommentByID(id int64) error {
  380. comment, err := GetCommentByID(id)
  381. if err != nil {
  382. if IsErrCommentNotExist(err) {
  383. return nil
  384. }
  385. return err
  386. }
  387. sess := x.NewSession()
  388. defer sessionRelease(sess)
  389. if err = sess.Begin(); err != nil {
  390. return err
  391. }
  392. if _, err = sess.Id(comment.ID).Delete(new(Comment)); err != nil {
  393. return err
  394. }
  395. if comment.Type == COMMENT_TYPE_COMMENT {
  396. if _, err = sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  397. return err
  398. }
  399. }
  400. return sess.Commit()
  401. }