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

issue_comment.go 11 kB

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