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