issue_comment.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. api "github.com/gogits/go-gogs-client"
  12. "github.com/gogits/gogs/modules/log"
  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(opType ActionType, issue *Issue) (err error) {
  136. mentions := markdown.FindAllMentions(cmt.Content)
  137. if err = UpdateIssueMentions(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. comment.MailParticipants(act.OpType, opts.Issue)
  238. }
  239. return comment, comment.loadAttributes(e)
  240. }
  241. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  242. cmtType := COMMENT_TYPE_CLOSE
  243. if !issue.IsClosed {
  244. cmtType = COMMENT_TYPE_REOPEN
  245. }
  246. return createComment(e, &CreateCommentOptions{
  247. Type: cmtType,
  248. Doer: doer,
  249. Repo: repo,
  250. Issue: issue,
  251. })
  252. }
  253. type CreateCommentOptions struct {
  254. Type CommentType
  255. Doer *User
  256. Repo *Repository
  257. Issue *Issue
  258. CommitID int64
  259. CommitSHA string
  260. LineNum int64
  261. Content string
  262. Attachments []string // UUIDs of attachments
  263. }
  264. // CreateComment creates comment of issue or commit.
  265. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
  266. sess := x.NewSession()
  267. defer sessionRelease(sess)
  268. if err = sess.Begin(); err != nil {
  269. return nil, err
  270. }
  271. comment, err = createComment(sess, opts)
  272. if err != nil {
  273. return nil, err
  274. }
  275. return comment, sess.Commit()
  276. }
  277. // CreateIssueComment creates a plain issue comment.
  278. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  279. return CreateComment(&CreateCommentOptions{
  280. Type: COMMENT_TYPE_COMMENT,
  281. Doer: doer,
  282. Repo: repo,
  283. Issue: issue,
  284. Content: content,
  285. Attachments: attachments,
  286. })
  287. }
  288. // CreateRefComment creates a commit reference comment to issue.
  289. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  290. if len(commitSHA) == 0 {
  291. return fmt.Errorf("cannot create reference with empty commit SHA")
  292. }
  293. // Check if same reference from same commit has already existed.
  294. has, err := x.Get(&Comment{
  295. Type: COMMENT_TYPE_COMMIT_REF,
  296. IssueID: issue.ID,
  297. CommitSHA: commitSHA,
  298. })
  299. if err != nil {
  300. return fmt.Errorf("check reference comment: %v", err)
  301. } else if has {
  302. return nil
  303. }
  304. _, err = CreateComment(&CreateCommentOptions{
  305. Type: COMMENT_TYPE_COMMIT_REF,
  306. Doer: doer,
  307. Repo: repo,
  308. Issue: issue,
  309. CommitSHA: commitSHA,
  310. Content: content,
  311. })
  312. return err
  313. }
  314. // GetCommentByID returns the comment by given ID.
  315. func GetCommentByID(id int64) (*Comment, error) {
  316. c := new(Comment)
  317. has, err := x.Id(id).Get(c)
  318. if err != nil {
  319. return nil, err
  320. } else if !has {
  321. return nil, ErrCommentNotExist{id, 0}
  322. }
  323. return c, c.LoadAttributes()
  324. }
  325. // FIXME: use CommentList to improve performance.
  326. func loadCommentsAttributes(e Engine, comments []*Comment) (err error) {
  327. for i := range comments {
  328. if err = comments[i].loadAttributes(e); err != nil {
  329. return fmt.Errorf("loadAttributes [%d]: %v", comments[i].ID, err)
  330. }
  331. }
  332. return nil
  333. }
  334. func getCommentsByIssueIDSince(e Engine, issueID, since int64) ([]*Comment, error) {
  335. comments := make([]*Comment, 0, 10)
  336. sess := e.Where("issue_id = ?", issueID).Asc("created_unix")
  337. if since > 0 {
  338. sess.And("updated_unix >= ?", since)
  339. }
  340. if err := sess.Find(&comments); err != nil {
  341. return nil, err
  342. }
  343. return comments, loadCommentsAttributes(e, comments)
  344. }
  345. func getCommentsByRepoIDSince(e Engine, repoID, since int64) ([]*Comment, error) {
  346. comments := make([]*Comment, 0, 10)
  347. sess := e.Where("issue.repo_id = ?", repoID).Join("INNER", "issue", "issue.id = comment.issue_id", repoID).Asc("created_unix")
  348. if since > 0 {
  349. sess.And("updated_unix >= ?", since)
  350. }
  351. if err := sess.Find(&comments); err != nil {
  352. return nil, err
  353. }
  354. return comments, loadCommentsAttributes(e, comments)
  355. }
  356. func getCommentsByIssueID(e Engine, issueID int64) ([]*Comment, error) {
  357. return getCommentsByIssueIDSince(e, issueID, -1)
  358. }
  359. // GetCommentsByIssueID returns all comments of an issue.
  360. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  361. return getCommentsByIssueID(x, issueID)
  362. }
  363. // GetCommentsByIssueIDSince returns a list of comments of an issue since a given time point.
  364. func GetCommentsByIssueIDSince(issueID, since int64) ([]*Comment, error) {
  365. return getCommentsByIssueIDSince(x, issueID, since)
  366. }
  367. // GetCommentsByRepoIDSince returns a list of comments for all issues in a repo since a given time point.
  368. func GetCommentsByRepoIDSince(repoID, since int64) ([]*Comment, error) {
  369. return getCommentsByRepoIDSince(x, repoID, since)
  370. }
  371. // UpdateComment updates information of comment.
  372. func UpdateComment(c *Comment) error {
  373. _, err := x.Id(c.ID).AllCols().Update(c)
  374. return err
  375. }
  376. // DeleteCommentByID deletes the comment by given ID.
  377. func DeleteCommentByID(id int64) error {
  378. comment, err := GetCommentByID(id)
  379. if err != nil {
  380. if IsErrCommentNotExist(err) {
  381. return nil
  382. }
  383. return err
  384. }
  385. sess := x.NewSession()
  386. defer sessionRelease(sess)
  387. if err = sess.Begin(); err != nil {
  388. return err
  389. }
  390. if _, err = sess.Id(comment.ID).Delete(new(Comment)); err != nil {
  391. return err
  392. }
  393. if comment.Type == COMMENT_TYPE_COMMENT {
  394. if _, err = sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  395. return err
  396. }
  397. }
  398. return sess.Commit()
  399. }