Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

issue_comment.go 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  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. "github.com/Unknwon/com"
  9. "github.com/go-xorm/builder"
  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/markup"
  14. "code.gitea.io/gitea/modules/util"
  15. )
  16. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  17. type CommentType int
  18. // define unknown comment type
  19. const (
  20. CommentTypeUnknown CommentType = -1
  21. )
  22. // Enumerate all the comment types
  23. const (
  24. // Plain comment, can be associated with a commit (CommitID > 0) and a line (LineNum > 0)
  25. CommentTypeComment CommentType = iota
  26. CommentTypeReopen
  27. CommentTypeClose
  28. // References.
  29. CommentTypeIssueRef
  30. // Reference from a commit (not part of a pull request)
  31. CommentTypeCommitRef
  32. // Reference from a comment
  33. CommentTypeCommentRef
  34. // Reference from a pull request
  35. CommentTypePullRef
  36. // Labels changed
  37. CommentTypeLabel
  38. // Milestone changed
  39. CommentTypeMilestone
  40. // Assignees changed
  41. CommentTypeAssignees
  42. // Change Title
  43. CommentTypeChangeTitle
  44. // Delete Branch
  45. CommentTypeDeleteBranch
  46. // Start a stopwatch for time tracking
  47. CommentTypeStartTracking
  48. // Stop a stopwatch for time tracking
  49. CommentTypeStopTracking
  50. // Add time manual for time tracking
  51. CommentTypeAddTimeManual
  52. // Cancel a stopwatch for time tracking
  53. CommentTypeCancelTracking
  54. // Added a due date
  55. CommentTypeAddedDeadline
  56. // Modified the due date
  57. CommentTypeModifiedDeadline
  58. // Removed a due date
  59. CommentTypeRemovedDeadline
  60. )
  61. // CommentTag defines comment tag type
  62. type CommentTag int
  63. // Enumerate all the comment tag types
  64. const (
  65. CommentTagNone CommentTag = iota
  66. CommentTagPoster
  67. CommentTagWriter
  68. CommentTagOwner
  69. )
  70. // Comment represents a comment in commit and issue page.
  71. type Comment struct {
  72. ID int64 `xorm:"pk autoincr"`
  73. Type CommentType
  74. PosterID int64 `xorm:"INDEX"`
  75. Poster *User `xorm:"-"`
  76. IssueID int64 `xorm:"INDEX"`
  77. Issue *Issue `xorm:"-"`
  78. LabelID int64
  79. Label *Label `xorm:"-"`
  80. OldMilestoneID int64
  81. MilestoneID int64
  82. OldMilestone *Milestone `xorm:"-"`
  83. Milestone *Milestone `xorm:"-"`
  84. AssigneeID int64
  85. RemovedAssignee bool
  86. Assignee *User `xorm:"-"`
  87. OldTitle string
  88. NewTitle string
  89. CommitID int64
  90. Line int64
  91. Content string `xorm:"TEXT"`
  92. RenderedContent string `xorm:"-"`
  93. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  94. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  95. // Reference issue in commit message
  96. CommitSHA string `xorm:"VARCHAR(40)"`
  97. Attachments []*Attachment `xorm:"-"`
  98. Reactions ReactionList `xorm:"-"`
  99. // For view issue page.
  100. ShowTag CommentTag `xorm:"-"`
  101. }
  102. // LoadIssue loads issue from database
  103. func (c *Comment) LoadIssue() (err error) {
  104. if c.Issue != nil {
  105. return nil
  106. }
  107. c.Issue, err = GetIssueByID(c.IssueID)
  108. return
  109. }
  110. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  111. func (c *Comment) AfterLoad(session *xorm.Session) {
  112. var err error
  113. c.Attachments, err = getAttachmentsByCommentID(session, c.ID)
  114. if err != nil {
  115. log.Error(3, "getAttachmentsByCommentID[%d]: %v", c.ID, err)
  116. }
  117. c.Poster, err = getUserByID(session, c.PosterID)
  118. if err != nil {
  119. if IsErrUserNotExist(err) {
  120. c.PosterID = -1
  121. c.Poster = NewGhostUser()
  122. } else {
  123. log.Error(3, "getUserByID[%d]: %v", c.ID, err)
  124. }
  125. }
  126. }
  127. // AfterDelete is invoked from XORM after the object is deleted.
  128. func (c *Comment) AfterDelete() {
  129. _, err := DeleteAttachmentsByComment(c.ID, true)
  130. if err != nil {
  131. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  132. }
  133. }
  134. // HTMLURL formats a URL-string to the issue-comment
  135. func (c *Comment) HTMLURL() string {
  136. err := c.LoadIssue()
  137. if err != nil { // Silently dropping errors :unamused:
  138. log.Error(4, "LoadIssue(%d): %v", c.IssueID, err)
  139. return ""
  140. }
  141. return fmt.Sprintf("%s#%s", c.Issue.HTMLURL(), c.HashTag())
  142. }
  143. // IssueURL formats a URL-string to the issue
  144. func (c *Comment) IssueURL() string {
  145. err := c.LoadIssue()
  146. if err != nil { // Silently dropping errors :unamused:
  147. log.Error(4, "LoadIssue(%d): %v", c.IssueID, err)
  148. return ""
  149. }
  150. if c.Issue.IsPull {
  151. return ""
  152. }
  153. return c.Issue.HTMLURL()
  154. }
  155. // PRURL formats a URL-string to the pull-request
  156. func (c *Comment) PRURL() string {
  157. err := c.LoadIssue()
  158. if err != nil { // Silently dropping errors :unamused:
  159. log.Error(4, "LoadIssue(%d): %v", c.IssueID, err)
  160. return ""
  161. }
  162. if !c.Issue.IsPull {
  163. return ""
  164. }
  165. return c.Issue.HTMLURL()
  166. }
  167. // APIFormat converts a Comment to the api.Comment format
  168. func (c *Comment) APIFormat() *api.Comment {
  169. return &api.Comment{
  170. ID: c.ID,
  171. Poster: c.Poster.APIFormat(),
  172. HTMLURL: c.HTMLURL(),
  173. IssueURL: c.IssueURL(),
  174. PRURL: c.PRURL(),
  175. Body: c.Content,
  176. Created: c.CreatedUnix.AsTime(),
  177. Updated: c.UpdatedUnix.AsTime(),
  178. }
  179. }
  180. // CommentHashTag returns unique hash tag for comment id.
  181. func CommentHashTag(id int64) string {
  182. return fmt.Sprintf("issuecomment-%d", id)
  183. }
  184. // HashTag returns unique hash tag for comment.
  185. func (c *Comment) HashTag() string {
  186. return CommentHashTag(c.ID)
  187. }
  188. // EventTag returns unique event hash tag for comment.
  189. func (c *Comment) EventTag() string {
  190. return "event-" + com.ToStr(c.ID)
  191. }
  192. // LoadLabel if comment.Type is CommentTypeLabel, then load Label
  193. func (c *Comment) LoadLabel() error {
  194. var label Label
  195. has, err := x.ID(c.LabelID).Get(&label)
  196. if err != nil {
  197. return err
  198. } else if has {
  199. c.Label = &label
  200. } else {
  201. // Ignore Label is deleted, but not clear this table
  202. log.Warn("Commit %d cannot load label %d", c.ID, c.LabelID)
  203. }
  204. return nil
  205. }
  206. // LoadMilestone if comment.Type is CommentTypeMilestone, then load milestone
  207. func (c *Comment) LoadMilestone() error {
  208. if c.OldMilestoneID > 0 {
  209. var oldMilestone Milestone
  210. has, err := x.ID(c.OldMilestoneID).Get(&oldMilestone)
  211. if err != nil {
  212. return err
  213. } else if has {
  214. c.OldMilestone = &oldMilestone
  215. }
  216. }
  217. if c.MilestoneID > 0 {
  218. var milestone Milestone
  219. has, err := x.ID(c.MilestoneID).Get(&milestone)
  220. if err != nil {
  221. return err
  222. } else if has {
  223. c.Milestone = &milestone
  224. }
  225. }
  226. return nil
  227. }
  228. // LoadAssigneeUser if comment.Type is CommentTypeAssignees, then load assignees
  229. func (c *Comment) LoadAssigneeUser() error {
  230. var err error
  231. if c.AssigneeID > 0 {
  232. c.Assignee, err = getUserByID(x, c.AssigneeID)
  233. if err != nil {
  234. if !IsErrUserNotExist(err) {
  235. return err
  236. }
  237. c.Assignee = NewGhostUser()
  238. }
  239. }
  240. return nil
  241. }
  242. // MailParticipants sends new comment emails to repository watchers
  243. // and mentioned people.
  244. func (c *Comment) MailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
  245. mentions := markup.FindAllMentions(c.Content)
  246. if err = UpdateIssueMentions(e, c.IssueID, mentions); err != nil {
  247. return fmt.Errorf("UpdateIssueMentions [%d]: %v", c.IssueID, err)
  248. }
  249. content := c.Content
  250. switch opType {
  251. case ActionCloseIssue:
  252. content = fmt.Sprintf("Closed #%d", issue.Index)
  253. case ActionReopenIssue:
  254. content = fmt.Sprintf("Reopened #%d", issue.Index)
  255. }
  256. if err = mailIssueCommentToParticipants(e, issue, c.Poster, content, c, mentions); err != nil {
  257. log.Error(4, "mailIssueCommentToParticipants: %v", err)
  258. }
  259. return nil
  260. }
  261. func (c *Comment) loadReactions(e Engine) (err error) {
  262. if c.Reactions != nil {
  263. return nil
  264. }
  265. c.Reactions, err = findReactions(e, FindReactionsOptions{
  266. IssueID: c.IssueID,
  267. CommentID: c.ID,
  268. })
  269. if err != nil {
  270. return err
  271. }
  272. // Load reaction user data
  273. if _, err := c.Reactions.LoadUsers(); err != nil {
  274. return err
  275. }
  276. return nil
  277. }
  278. // LoadReactions loads comment reactions
  279. func (c *Comment) LoadReactions() error {
  280. return c.loadReactions(x)
  281. }
  282. func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err error) {
  283. var LabelID int64
  284. if opts.Label != nil {
  285. LabelID = opts.Label.ID
  286. }
  287. comment := &Comment{
  288. Type: opts.Type,
  289. PosterID: opts.Doer.ID,
  290. Poster: opts.Doer,
  291. IssueID: opts.Issue.ID,
  292. LabelID: LabelID,
  293. OldMilestoneID: opts.OldMilestoneID,
  294. MilestoneID: opts.MilestoneID,
  295. RemovedAssignee: opts.RemovedAssignee,
  296. AssigneeID: opts.AssigneeID,
  297. CommitID: opts.CommitID,
  298. CommitSHA: opts.CommitSHA,
  299. Line: opts.LineNum,
  300. Content: opts.Content,
  301. OldTitle: opts.OldTitle,
  302. NewTitle: opts.NewTitle,
  303. }
  304. if _, err = e.Insert(comment); err != nil {
  305. return nil, err
  306. }
  307. if err = opts.Repo.getOwner(e); err != nil {
  308. return nil, err
  309. }
  310. // Compose comment action, could be plain comment, close or reopen issue/pull request.
  311. // This object will be used to notify watchers in the end of function.
  312. act := &Action{
  313. ActUserID: opts.Doer.ID,
  314. ActUser: opts.Doer,
  315. Content: fmt.Sprintf("%d|%s", opts.Issue.Index, strings.Split(opts.Content, "\n")[0]),
  316. RepoID: opts.Repo.ID,
  317. Repo: opts.Repo,
  318. Comment: comment,
  319. CommentID: comment.ID,
  320. IsPrivate: opts.Repo.IsPrivate,
  321. }
  322. // Check comment type.
  323. switch opts.Type {
  324. case CommentTypeComment:
  325. act.OpType = ActionCommentIssue
  326. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
  327. return nil, err
  328. }
  329. // Check attachments
  330. attachments := make([]*Attachment, 0, len(opts.Attachments))
  331. for _, uuid := range opts.Attachments {
  332. attach, err := getAttachmentByUUID(e, uuid)
  333. if err != nil {
  334. if IsErrAttachmentNotExist(err) {
  335. continue
  336. }
  337. return nil, fmt.Errorf("getAttachmentByUUID [%s]: %v", uuid, err)
  338. }
  339. attachments = append(attachments, attach)
  340. }
  341. for i := range attachments {
  342. attachments[i].IssueID = opts.Issue.ID
  343. attachments[i].CommentID = comment.ID
  344. // No assign value could be 0, so ignore AllCols().
  345. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  346. return nil, fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  347. }
  348. }
  349. case CommentTypeReopen:
  350. act.OpType = ActionReopenIssue
  351. if opts.Issue.IsPull {
  352. act.OpType = ActionReopenPullRequest
  353. }
  354. if opts.Issue.IsPull {
  355. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls-1 WHERE id=?", opts.Repo.ID)
  356. } else {
  357. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", opts.Repo.ID)
  358. }
  359. if err != nil {
  360. return nil, err
  361. }
  362. case CommentTypeClose:
  363. act.OpType = ActionCloseIssue
  364. if opts.Issue.IsPull {
  365. act.OpType = ActionClosePullRequest
  366. }
  367. if opts.Issue.IsPull {
  368. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls+1 WHERE id=?", opts.Repo.ID)
  369. } else {
  370. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", opts.Repo.ID)
  371. }
  372. if err != nil {
  373. return nil, err
  374. }
  375. }
  376. // update the issue's updated_unix column
  377. if err = updateIssueCols(e, opts.Issue, "updated_unix"); err != nil {
  378. return nil, err
  379. }
  380. // Notify watchers for whatever action comes in, ignore if no action type.
  381. if act.OpType > 0 {
  382. if err = notifyWatchers(e, act); err != nil {
  383. log.Error(4, "notifyWatchers: %v", err)
  384. }
  385. if err = comment.MailParticipants(e, act.OpType, opts.Issue); err != nil {
  386. log.Error(4, "MailParticipants: %v", err)
  387. }
  388. }
  389. return comment, nil
  390. }
  391. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  392. cmtType := CommentTypeClose
  393. if !issue.IsClosed {
  394. cmtType = CommentTypeReopen
  395. }
  396. return createComment(e, &CreateCommentOptions{
  397. Type: cmtType,
  398. Doer: doer,
  399. Repo: repo,
  400. Issue: issue,
  401. })
  402. }
  403. func createLabelComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, label *Label, add bool) (*Comment, error) {
  404. var content string
  405. if add {
  406. content = "1"
  407. }
  408. return createComment(e, &CreateCommentOptions{
  409. Type: CommentTypeLabel,
  410. Doer: doer,
  411. Repo: repo,
  412. Issue: issue,
  413. Label: label,
  414. Content: content,
  415. })
  416. }
  417. func createMilestoneComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldMilestoneID, milestoneID int64) (*Comment, error) {
  418. return createComment(e, &CreateCommentOptions{
  419. Type: CommentTypeMilestone,
  420. Doer: doer,
  421. Repo: repo,
  422. Issue: issue,
  423. OldMilestoneID: oldMilestoneID,
  424. MilestoneID: milestoneID,
  425. })
  426. }
  427. func createAssigneeComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, assigneeID int64, removedAssignee bool) (*Comment, error) {
  428. return createComment(e, &CreateCommentOptions{
  429. Type: CommentTypeAssignees,
  430. Doer: doer,
  431. Repo: repo,
  432. Issue: issue,
  433. RemovedAssignee: removedAssignee,
  434. AssigneeID: assigneeID,
  435. })
  436. }
  437. func createDeadlineComment(e *xorm.Session, doer *User, issue *Issue, newDeadlineUnix util.TimeStamp) (*Comment, error) {
  438. var content string
  439. var commentType CommentType
  440. // newDeadline = 0 means deleting
  441. if newDeadlineUnix == 0 {
  442. commentType = CommentTypeRemovedDeadline
  443. content = issue.DeadlineUnix.Format("2006-01-02")
  444. } else if issue.DeadlineUnix == 0 {
  445. // Check if the new date was added or modified
  446. // If the actual deadline is 0 => deadline added
  447. commentType = CommentTypeAddedDeadline
  448. content = newDeadlineUnix.Format("2006-01-02")
  449. } else { // Otherwise modified
  450. commentType = CommentTypeModifiedDeadline
  451. content = newDeadlineUnix.Format("2006-01-02") + "|" + issue.DeadlineUnix.Format("2006-01-02")
  452. }
  453. return createComment(e, &CreateCommentOptions{
  454. Type: commentType,
  455. Doer: doer,
  456. Repo: issue.Repo,
  457. Issue: issue,
  458. Content: content,
  459. })
  460. }
  461. func createChangeTitleComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldTitle, newTitle string) (*Comment, error) {
  462. return createComment(e, &CreateCommentOptions{
  463. Type: CommentTypeChangeTitle,
  464. Doer: doer,
  465. Repo: repo,
  466. Issue: issue,
  467. OldTitle: oldTitle,
  468. NewTitle: newTitle,
  469. })
  470. }
  471. func createDeleteBranchComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, branchName string) (*Comment, error) {
  472. return createComment(e, &CreateCommentOptions{
  473. Type: CommentTypeDeleteBranch,
  474. Doer: doer,
  475. Repo: repo,
  476. Issue: issue,
  477. CommitSHA: branchName,
  478. })
  479. }
  480. // CreateCommentOptions defines options for creating comment
  481. type CreateCommentOptions struct {
  482. Type CommentType
  483. Doer *User
  484. Repo *Repository
  485. Issue *Issue
  486. Label *Label
  487. OldMilestoneID int64
  488. MilestoneID int64
  489. AssigneeID int64
  490. RemovedAssignee bool
  491. OldTitle string
  492. NewTitle string
  493. CommitID int64
  494. CommitSHA string
  495. LineNum int64
  496. Content string
  497. Attachments []string // UUIDs of attachments
  498. }
  499. // CreateComment creates comment of issue or commit.
  500. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
  501. sess := x.NewSession()
  502. defer sess.Close()
  503. if err = sess.Begin(); err != nil {
  504. return nil, err
  505. }
  506. comment, err = createComment(sess, opts)
  507. if err != nil {
  508. return nil, err
  509. }
  510. if err = sess.Commit(); err != nil {
  511. return nil, err
  512. }
  513. if opts.Type == CommentTypeComment {
  514. UpdateIssueIndexer(opts.Issue.ID)
  515. }
  516. return comment, nil
  517. }
  518. // CreateIssueComment creates a plain issue comment.
  519. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  520. comment, err := CreateComment(&CreateCommentOptions{
  521. Type: CommentTypeComment,
  522. Doer: doer,
  523. Repo: repo,
  524. Issue: issue,
  525. Content: content,
  526. Attachments: attachments,
  527. })
  528. if err != nil {
  529. return nil, fmt.Errorf("CreateComment: %v", err)
  530. }
  531. mode, _ := AccessLevel(doer.ID, repo)
  532. if err = PrepareWebhooks(repo, HookEventIssueComment, &api.IssueCommentPayload{
  533. Action: api.HookIssueCommentCreated,
  534. Issue: issue.APIFormat(),
  535. Comment: comment.APIFormat(),
  536. Repository: repo.APIFormat(mode),
  537. Sender: doer.APIFormat(),
  538. }); err != nil {
  539. log.Error(2, "PrepareWebhooks [comment_id: %d]: %v", comment.ID, err)
  540. }
  541. return comment, nil
  542. }
  543. // CreateRefComment creates a commit reference comment to issue.
  544. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  545. if len(commitSHA) == 0 {
  546. return fmt.Errorf("cannot create reference with empty commit SHA")
  547. }
  548. // Check if same reference from same commit has already existed.
  549. has, err := x.Get(&Comment{
  550. Type: CommentTypeCommitRef,
  551. IssueID: issue.ID,
  552. CommitSHA: commitSHA,
  553. })
  554. if err != nil {
  555. return fmt.Errorf("check reference comment: %v", err)
  556. } else if has {
  557. return nil
  558. }
  559. _, err = CreateComment(&CreateCommentOptions{
  560. Type: CommentTypeCommitRef,
  561. Doer: doer,
  562. Repo: repo,
  563. Issue: issue,
  564. CommitSHA: commitSHA,
  565. Content: content,
  566. })
  567. return err
  568. }
  569. // GetCommentByID returns the comment by given ID.
  570. func GetCommentByID(id int64) (*Comment, error) {
  571. c := new(Comment)
  572. has, err := x.ID(id).Get(c)
  573. if err != nil {
  574. return nil, err
  575. } else if !has {
  576. return nil, ErrCommentNotExist{id, 0}
  577. }
  578. return c, nil
  579. }
  580. // FindCommentsOptions describes the conditions to Find comments
  581. type FindCommentsOptions struct {
  582. RepoID int64
  583. IssueID int64
  584. Since int64
  585. Type CommentType
  586. }
  587. func (opts *FindCommentsOptions) toConds() builder.Cond {
  588. var cond = builder.NewCond()
  589. if opts.RepoID > 0 {
  590. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  591. }
  592. if opts.IssueID > 0 {
  593. cond = cond.And(builder.Eq{"comment.issue_id": opts.IssueID})
  594. }
  595. if opts.Since > 0 {
  596. cond = cond.And(builder.Gte{"comment.updated_unix": opts.Since})
  597. }
  598. if opts.Type != CommentTypeUnknown {
  599. cond = cond.And(builder.Eq{"comment.type": opts.Type})
  600. }
  601. return cond
  602. }
  603. func findComments(e Engine, opts FindCommentsOptions) ([]*Comment, error) {
  604. comments := make([]*Comment, 0, 10)
  605. sess := e.Where(opts.toConds())
  606. if opts.RepoID > 0 {
  607. sess.Join("INNER", "issue", "issue.id = comment.issue_id")
  608. }
  609. return comments, sess.
  610. Asc("comment.created_unix").
  611. Asc("comment.id").
  612. Find(&comments)
  613. }
  614. // FindComments returns all comments according options
  615. func FindComments(opts FindCommentsOptions) ([]*Comment, error) {
  616. return findComments(x, opts)
  617. }
  618. // GetCommentsByIssueID returns all comments of an issue.
  619. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  620. return findComments(x, FindCommentsOptions{
  621. IssueID: issueID,
  622. Type: CommentTypeUnknown,
  623. })
  624. }
  625. // GetCommentsByIssueIDSince returns a list of comments of an issue since a given time point.
  626. func GetCommentsByIssueIDSince(issueID, since int64) ([]*Comment, error) {
  627. return findComments(x, FindCommentsOptions{
  628. IssueID: issueID,
  629. Type: CommentTypeUnknown,
  630. Since: since,
  631. })
  632. }
  633. // GetCommentsByRepoIDSince returns a list of comments for all issues in a repo since a given time point.
  634. func GetCommentsByRepoIDSince(repoID, since int64) ([]*Comment, error) {
  635. return findComments(x, FindCommentsOptions{
  636. RepoID: repoID,
  637. Type: CommentTypeUnknown,
  638. Since: since,
  639. })
  640. }
  641. // UpdateComment updates information of comment.
  642. func UpdateComment(doer *User, c *Comment, oldContent string) error {
  643. if _, err := x.ID(c.ID).AllCols().Update(c); err != nil {
  644. return err
  645. } else if c.Type == CommentTypeComment {
  646. UpdateIssueIndexer(c.IssueID)
  647. }
  648. if err := c.LoadIssue(); err != nil {
  649. return err
  650. }
  651. if err := c.Issue.LoadAttributes(); err != nil {
  652. return err
  653. }
  654. mode, _ := AccessLevel(doer.ID, c.Issue.Repo)
  655. if err := PrepareWebhooks(c.Issue.Repo, HookEventIssueComment, &api.IssueCommentPayload{
  656. Action: api.HookIssueCommentEdited,
  657. Issue: c.Issue.APIFormat(),
  658. Comment: c.APIFormat(),
  659. Changes: &api.ChangesPayload{
  660. Body: &api.ChangesFromPayload{
  661. From: oldContent,
  662. },
  663. },
  664. Repository: c.Issue.Repo.APIFormat(mode),
  665. Sender: doer.APIFormat(),
  666. }); err != nil {
  667. log.Error(2, "PrepareWebhooks [comment_id: %d]: %v", c.ID, err)
  668. }
  669. return nil
  670. }
  671. // DeleteComment deletes the comment
  672. func DeleteComment(doer *User, comment *Comment) error {
  673. sess := x.NewSession()
  674. defer sess.Close()
  675. if err := sess.Begin(); err != nil {
  676. return err
  677. }
  678. if _, err := sess.Delete(&Comment{
  679. ID: comment.ID,
  680. }); err != nil {
  681. return err
  682. }
  683. if comment.Type == CommentTypeComment {
  684. if _, err := sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  685. return err
  686. }
  687. }
  688. if _, err := sess.Where("comment_id = ?", comment.ID).Cols("is_deleted").Update(&Action{IsDeleted: true}); err != nil {
  689. return err
  690. }
  691. if err := sess.Commit(); err != nil {
  692. return err
  693. } else if comment.Type == CommentTypeComment {
  694. UpdateIssueIndexer(comment.IssueID)
  695. }
  696. if err := comment.LoadIssue(); err != nil {
  697. return err
  698. }
  699. if err := comment.Issue.LoadAttributes(); err != nil {
  700. return err
  701. }
  702. mode, _ := AccessLevel(doer.ID, comment.Issue.Repo)
  703. if err := PrepareWebhooks(comment.Issue.Repo, HookEventIssueComment, &api.IssueCommentPayload{
  704. Action: api.HookIssueCommentDeleted,
  705. Issue: comment.Issue.APIFormat(),
  706. Comment: comment.APIFormat(),
  707. Repository: comment.Issue.Repo.APIFormat(mode),
  708. Sender: doer.APIFormat(),
  709. }); err != nil {
  710. log.Error(2, "PrepareWebhooks [comment_id: %d]: %v", comment.ID, err)
  711. }
  712. return nil
  713. }