You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

issue_comment.go 13KB

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