issue_comment.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. CommitID int64
  46. Line int64
  47. Content string `xorm:"TEXT"`
  48. RenderedContent string `xorm:"-"`
  49. Created time.Time `xorm:"-"`
  50. CreatedUnix int64
  51. Updated time.Time `xorm:"-"`
  52. UpdatedUnix int64
  53. // Reference issue in commit message
  54. CommitSHA string `xorm:"VARCHAR(40)"`
  55. Attachments []*Attachment `xorm:"-"`
  56. // For view issue page.
  57. ShowTag CommentTag `xorm:"-"`
  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. var err error
  68. switch colName {
  69. case "id":
  70. c.Attachments, err = GetAttachmentsByCommentID(c.ID)
  71. if err != nil {
  72. log.Error(3, "GetAttachmentsByCommentID[%d]: %v", c.ID, err)
  73. }
  74. case "poster_id":
  75. c.Poster, err = GetUserByID(c.PosterID)
  76. if err != nil {
  77. if IsErrUserNotExist(err) {
  78. c.PosterID = -1
  79. c.Poster = NewGhostUser()
  80. } else {
  81. log.Error(3, "GetUserByID[%d]: %v", c.ID, err)
  82. }
  83. }
  84. case "created_unix":
  85. c.Created = time.Unix(c.CreatedUnix, 0).Local()
  86. case "updated_unix":
  87. c.Updated = time.Unix(c.UpdatedUnix, 0).Local()
  88. }
  89. }
  90. func (c *Comment) AfterDelete() {
  91. _, err := DeleteAttachmentsByComment(c.ID, true)
  92. if err != nil {
  93. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  94. }
  95. }
  96. func (c *Comment) HTMLURL() string {
  97. issue, err := GetIssueByID(c.IssueID)
  98. if err != nil { // Silently dropping errors :unamused:
  99. log.Error(4, "GetIssueByID(%d): %v", c.IssueID, err)
  100. return ""
  101. }
  102. return fmt.Sprintf("%s#issuecomment-%d", issue.HTMLURL(), c.ID)
  103. }
  104. func (c *Comment) IssueURL() string {
  105. issue, err := GetIssueByID(c.IssueID)
  106. if err != nil { // Silently dropping errors :unamused:
  107. log.Error(4, "GetIssueByID(%d): %v", c.IssueID, err)
  108. return ""
  109. }
  110. if issue.IsPull {
  111. return ""
  112. }
  113. return issue.HTMLURL()
  114. }
  115. func (c *Comment) PRURL() string {
  116. issue, err := GetIssueByID(c.IssueID)
  117. if err != nil { // Silently dropping errors :unamused:
  118. log.Error(4, "GetIssueByID(%d): %v", c.IssueID, err)
  119. return ""
  120. }
  121. if !issue.IsPull {
  122. return ""
  123. }
  124. return issue.HTMLURL()
  125. }
  126. func (c *Comment) APIFormat() *api.Comment {
  127. return &api.Comment{
  128. ID: c.ID,
  129. Poster: c.Poster.APIFormat(),
  130. HTMLURL: c.HTMLURL(),
  131. IssueURL: c.IssueURL(),
  132. PRURL: c.PRURL(),
  133. Body: c.Content,
  134. Created: c.Created,
  135. Updated: c.Updated,
  136. }
  137. }
  138. // HashTag returns unique hash tag for comment.
  139. func (c *Comment) HashTag() string {
  140. return "issuecomment-" + com.ToStr(c.ID)
  141. }
  142. // EventTag returns unique event hash tag for comment.
  143. func (c *Comment) EventTag() string {
  144. return "event-" + com.ToStr(c.ID)
  145. }
  146. // MailParticipants sends new comment emails to repository watchers
  147. // and mentioned people.
  148. func (cmt *Comment) MailParticipants(opType ActionType, issue *Issue) (err error) {
  149. mentions := markdown.FindAllMentions(cmt.Content)
  150. if err = UpdateIssueMentions(cmt.IssueID, mentions); err != nil {
  151. return fmt.Errorf("UpdateIssueMentions [%d]: %v", cmt.IssueID, err)
  152. }
  153. switch opType {
  154. case ACTION_COMMENT_ISSUE:
  155. issue.Content = cmt.Content
  156. case ACTION_CLOSE_ISSUE:
  157. issue.Content = fmt.Sprintf("Closed #%d", issue.Index)
  158. case ACTION_REOPEN_ISSUE:
  159. issue.Content = fmt.Sprintf("Reopened #%d", issue.Index)
  160. }
  161. if err = mailIssueCommentToParticipants(issue, cmt.Poster, mentions); err != nil {
  162. log.Error(4, "mailIssueCommentToParticipants: %v", err)
  163. }
  164. return nil
  165. }
  166. func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err error) {
  167. comment := &Comment{
  168. Type: opts.Type,
  169. PosterID: opts.Doer.ID,
  170. Poster: opts.Doer,
  171. IssueID: opts.Issue.ID,
  172. CommitID: opts.CommitID,
  173. CommitSHA: opts.CommitSHA,
  174. Line: opts.LineNum,
  175. Content: opts.Content,
  176. }
  177. if _, err = e.Insert(comment); err != nil {
  178. return nil, err
  179. }
  180. // Compose comment action, could be plain comment, close or reopen issue/pull request.
  181. // This object will be used to notify watchers in the end of function.
  182. act := &Action{
  183. ActUserID: opts.Doer.ID,
  184. ActUserName: opts.Doer.Name,
  185. Content: fmt.Sprintf("%d|%s", opts.Issue.Index, strings.Split(opts.Content, "\n")[0]),
  186. RepoID: opts.Repo.ID,
  187. RepoUserName: opts.Repo.Owner.Name,
  188. RepoName: opts.Repo.Name,
  189. IsPrivate: opts.Repo.IsPrivate,
  190. }
  191. // Check comment type.
  192. switch opts.Type {
  193. case COMMENT_TYPE_COMMENT:
  194. act.OpType = ACTION_COMMENT_ISSUE
  195. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
  196. return nil, err
  197. }
  198. // Check attachments
  199. attachments := make([]*Attachment, 0, len(opts.Attachments))
  200. for _, uuid := range opts.Attachments {
  201. attach, err := getAttachmentByUUID(e, uuid)
  202. if err != nil {
  203. if IsErrAttachmentNotExist(err) {
  204. continue
  205. }
  206. return nil, fmt.Errorf("getAttachmentByUUID [%s]: %v", uuid, err)
  207. }
  208. attachments = append(attachments, attach)
  209. }
  210. for i := range attachments {
  211. attachments[i].IssueID = opts.Issue.ID
  212. attachments[i].CommentID = comment.ID
  213. // No assign value could be 0, so ignore AllCols().
  214. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  215. return nil, fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  216. }
  217. }
  218. case COMMENT_TYPE_REOPEN:
  219. act.OpType = ACTION_REOPEN_ISSUE
  220. if opts.Issue.IsPull {
  221. act.OpType = ACTION_REOPEN_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. case COMMENT_TYPE_CLOSE:
  232. act.OpType = ACTION_CLOSE_ISSUE
  233. if opts.Issue.IsPull {
  234. act.OpType = ACTION_CLOSE_PULL_REQUEST
  235. }
  236. if opts.Issue.IsPull {
  237. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls+1 WHERE id=?", opts.Repo.ID)
  238. } else {
  239. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", opts.Repo.ID)
  240. }
  241. if err != nil {
  242. return nil, err
  243. }
  244. }
  245. // Notify watchers for whatever action comes in, ignore if no action type.
  246. if act.OpType > 0 {
  247. if err = notifyWatchers(e, act); err != nil {
  248. log.Error(4, "notifyWatchers: %v", err)
  249. }
  250. comment.MailParticipants(act.OpType, opts.Issue)
  251. }
  252. return comment, nil
  253. }
  254. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  255. cmtType := COMMENT_TYPE_CLOSE
  256. if !issue.IsClosed {
  257. cmtType = COMMENT_TYPE_REOPEN
  258. }
  259. return createComment(e, &CreateCommentOptions{
  260. Type: cmtType,
  261. Doer: doer,
  262. Repo: repo,
  263. Issue: issue,
  264. })
  265. }
  266. type CreateCommentOptions struct {
  267. Type CommentType
  268. Doer *User
  269. Repo *Repository
  270. Issue *Issue
  271. CommitID int64
  272. CommitSHA string
  273. LineNum int64
  274. Content string
  275. Attachments []string // UUIDs of attachments
  276. }
  277. // CreateComment creates comment of issue or commit.
  278. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
  279. sess := x.NewSession()
  280. defer sessionRelease(sess)
  281. if err = sess.Begin(); err != nil {
  282. return nil, err
  283. }
  284. comment, err = createComment(sess, opts)
  285. if err != nil {
  286. return nil, err
  287. }
  288. return comment, sess.Commit()
  289. }
  290. // CreateIssueComment creates a plain issue comment.
  291. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  292. return CreateComment(&CreateCommentOptions{
  293. Type: COMMENT_TYPE_COMMENT,
  294. Doer: doer,
  295. Repo: repo,
  296. Issue: issue,
  297. Content: content,
  298. Attachments: attachments,
  299. })
  300. }
  301. // CreateRefComment creates a commit reference comment to issue.
  302. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  303. if len(commitSHA) == 0 {
  304. return fmt.Errorf("cannot create reference with empty commit SHA")
  305. }
  306. // Check if same reference from same commit has already existed.
  307. has, err := x.Get(&Comment{
  308. Type: COMMENT_TYPE_COMMIT_REF,
  309. IssueID: issue.ID,
  310. CommitSHA: commitSHA,
  311. })
  312. if err != nil {
  313. return fmt.Errorf("check reference comment: %v", err)
  314. } else if has {
  315. return nil
  316. }
  317. _, err = CreateComment(&CreateCommentOptions{
  318. Type: COMMENT_TYPE_COMMIT_REF,
  319. Doer: doer,
  320. Repo: repo,
  321. Issue: issue,
  322. CommitSHA: commitSHA,
  323. Content: content,
  324. })
  325. return err
  326. }
  327. // GetCommentByID returns the comment by given ID.
  328. func GetCommentByID(id int64) (*Comment, error) {
  329. c := new(Comment)
  330. has, err := x.Id(id).Get(c)
  331. if err != nil {
  332. return nil, err
  333. } else if !has {
  334. return nil, ErrCommentNotExist{id, 0}
  335. }
  336. return c, nil
  337. }
  338. func getCommentsByIssueIDSince(e Engine, issueID, since int64) ([]*Comment, error) {
  339. comments := make([]*Comment, 0, 10)
  340. sess := e.Where("issue_id = ?", issueID).Asc("created_unix")
  341. if since > 0 {
  342. sess.And("updated_unix >= ?", since)
  343. }
  344. return comments, sess.Find(&comments)
  345. }
  346. func getCommentsByRepoIDSince(e Engine, repoID, since int64) ([]*Comment, error) {
  347. comments := make([]*Comment, 0, 10)
  348. sess := e.Where("issue.repo_id = ?", repoID).Join("INNER", "issue", "issue.id = comment.issue_id", repoID).Asc("created_unix")
  349. if since > 0 {
  350. sess.And("updated_unix >= ?", since)
  351. }
  352. return comments, sess.Find(&comments)
  353. }
  354. func getCommentsByIssueID(e Engine, issueID int64) ([]*Comment, error) {
  355. return getCommentsByIssueIDSince(e, issueID, -1)
  356. }
  357. // GetCommentsByIssueID returns all comments of an issue.
  358. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  359. return getCommentsByIssueID(x, issueID)
  360. }
  361. // GetCommentsByIssueIDSince returns a list of comments of an issue since a given time point.
  362. func GetCommentsByIssueIDSince(issueID, since int64) ([]*Comment, error) {
  363. return getCommentsByIssueIDSince(x, issueID, since)
  364. }
  365. // GetCommentsByRepoIDSince returns a list of comments for all issues in a repo since a given time point.
  366. func GetCommentsByRepoIDSince(repoID, since int64) ([]*Comment, error) {
  367. return getCommentsByRepoIDSince(x, repoID, since)
  368. }
  369. // UpdateComment updates information of comment.
  370. func UpdateComment(c *Comment) error {
  371. _, err := x.Id(c.ID).AllCols().Update(c)
  372. return err
  373. }
  374. // DeleteCommentByID deletes the comment by given ID.
  375. func DeleteCommentByID(id int64) error {
  376. comment, err := GetCommentByID(id)
  377. if err != nil {
  378. if IsErrCommentNotExist(err) {
  379. return nil
  380. }
  381. return err
  382. }
  383. sess := x.NewSession()
  384. defer sessionRelease(sess)
  385. if err = sess.Begin(); err != nil {
  386. return err
  387. }
  388. if _, err = sess.Id(comment.ID).Delete(new(Comment)); err != nil {
  389. return err
  390. }
  391. if comment.Type == COMMENT_TYPE_COMMENT {
  392. if _, err = sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  393. return err
  394. }
  395. }
  396. return sess.Commit()
  397. }