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 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. // Copyright 2018 The Gitea Authors.
  2. // Copyright 2016 The Gogs Authors.
  3. // All rights reserved.
  4. // Use of this source code is governed by a MIT-style
  5. // license that can be found in the LICENSE file.
  6. package models
  7. import (
  8. "fmt"
  9. "strings"
  10. "code.gitea.io/gitea/modules/git"
  11. "code.gitea.io/gitea/modules/log"
  12. "code.gitea.io/gitea/modules/markup/markdown"
  13. "code.gitea.io/gitea/modules/references"
  14. "code.gitea.io/gitea/modules/structs"
  15. api "code.gitea.io/gitea/modules/structs"
  16. "code.gitea.io/gitea/modules/timeutil"
  17. "github.com/go-xorm/xorm"
  18. "github.com/unknwon/com"
  19. "xorm.io/builder"
  20. )
  21. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  22. type CommentType int
  23. // define unknown comment type
  24. const (
  25. CommentTypeUnknown CommentType = -1
  26. )
  27. // Enumerate all the comment types
  28. const (
  29. // Plain comment, can be associated with a commit (CommitID > 0) and a line (LineNum > 0)
  30. CommentTypeComment CommentType = iota
  31. CommentTypeReopen
  32. CommentTypeClose
  33. // References.
  34. CommentTypeIssueRef
  35. // Reference from a commit (not part of a pull request)
  36. CommentTypeCommitRef
  37. // Reference from a comment
  38. CommentTypeCommentRef
  39. // Reference from a pull request
  40. CommentTypePullRef
  41. // Labels changed
  42. CommentTypeLabel
  43. // Milestone changed
  44. CommentTypeMilestone
  45. // Assignees changed
  46. CommentTypeAssignees
  47. // Change Title
  48. CommentTypeChangeTitle
  49. // Delete Branch
  50. CommentTypeDeleteBranch
  51. // Start a stopwatch for time tracking
  52. CommentTypeStartTracking
  53. // Stop a stopwatch for time tracking
  54. CommentTypeStopTracking
  55. // Add time manual for time tracking
  56. CommentTypeAddTimeManual
  57. // Cancel a stopwatch for time tracking
  58. CommentTypeCancelTracking
  59. // Added a due date
  60. CommentTypeAddedDeadline
  61. // Modified the due date
  62. CommentTypeModifiedDeadline
  63. // Removed a due date
  64. CommentTypeRemovedDeadline
  65. // Dependency added
  66. CommentTypeAddDependency
  67. //Dependency removed
  68. CommentTypeRemoveDependency
  69. // Comment a line of code
  70. CommentTypeCode
  71. // Reviews a pull request by giving general feedback
  72. CommentTypeReview
  73. // Lock an issue, giving only collaborators access
  74. CommentTypeLock
  75. // Unlocks a previously locked issue
  76. CommentTypeUnlock
  77. )
  78. // CommentTag defines comment tag type
  79. type CommentTag int
  80. // Enumerate all the comment tag types
  81. const (
  82. CommentTagNone CommentTag = iota
  83. CommentTagPoster
  84. CommentTagWriter
  85. CommentTagOwner
  86. )
  87. // Comment represents a comment in commit and issue page.
  88. type Comment struct {
  89. ID int64 `xorm:"pk autoincr"`
  90. Type CommentType `xorm:"index"`
  91. PosterID int64 `xorm:"INDEX"`
  92. Poster *User `xorm:"-"`
  93. OriginalAuthor string
  94. OriginalAuthorID int64
  95. IssueID int64 `xorm:"INDEX"`
  96. Issue *Issue `xorm:"-"`
  97. LabelID int64
  98. Label *Label `xorm:"-"`
  99. OldMilestoneID int64
  100. MilestoneID int64
  101. OldMilestone *Milestone `xorm:"-"`
  102. Milestone *Milestone `xorm:"-"`
  103. AssigneeID int64
  104. RemovedAssignee bool
  105. Assignee *User `xorm:"-"`
  106. OldTitle string
  107. NewTitle string
  108. DependentIssueID int64
  109. DependentIssue *Issue `xorm:"-"`
  110. CommitID int64
  111. Line int64 // - previous line / + proposed line
  112. TreePath string
  113. Content string `xorm:"TEXT"`
  114. RenderedContent string `xorm:"-"`
  115. // Path represents the 4 lines of code cemented by this comment
  116. Patch string `xorm:"TEXT"`
  117. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  118. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  119. // Reference issue in commit message
  120. CommitSHA string `xorm:"VARCHAR(40)"`
  121. Attachments []*Attachment `xorm:"-"`
  122. Reactions ReactionList `xorm:"-"`
  123. // For view issue page.
  124. ShowTag CommentTag `xorm:"-"`
  125. Review *Review `xorm:"-"`
  126. ReviewID int64 `xorm:"index"`
  127. Invalidated bool
  128. // Reference an issue or pull from another comment, issue or PR
  129. // All information is about the origin of the reference
  130. RefRepoID int64 `xorm:"index"` // Repo where the referencing
  131. RefIssueID int64 `xorm:"index"`
  132. RefCommentID int64 `xorm:"index"` // 0 if origin is Issue title or content (or PR's)
  133. RefAction references.XRefAction `xorm:"SMALLINT"` // What hapens if RefIssueID resolves
  134. RefIsPull bool
  135. RefRepo *Repository `xorm:"-"`
  136. RefIssue *Issue `xorm:"-"`
  137. RefComment *Comment `xorm:"-"`
  138. }
  139. // LoadIssue loads issue from database
  140. func (c *Comment) LoadIssue() (err error) {
  141. return c.loadIssue(x)
  142. }
  143. func (c *Comment) loadIssue(e Engine) (err error) {
  144. if c.Issue != nil {
  145. return nil
  146. }
  147. c.Issue, err = getIssueByID(e, c.IssueID)
  148. return
  149. }
  150. func (c *Comment) loadPoster(e Engine) (err error) {
  151. if c.PosterID <= 0 || c.Poster != nil {
  152. return nil
  153. }
  154. c.Poster, err = getUserByID(e, c.PosterID)
  155. if err != nil {
  156. if IsErrUserNotExist(err) {
  157. c.PosterID = -1
  158. c.Poster = NewGhostUser()
  159. } else {
  160. log.Error("getUserByID[%d]: %v", c.ID, err)
  161. }
  162. }
  163. return err
  164. }
  165. // AfterDelete is invoked from XORM after the object is deleted.
  166. func (c *Comment) AfterDelete() {
  167. if c.ID <= 0 {
  168. return
  169. }
  170. _, err := DeleteAttachmentsByComment(c.ID, true)
  171. if err != nil {
  172. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  173. }
  174. }
  175. // HTMLURL formats a URL-string to the issue-comment
  176. func (c *Comment) HTMLURL() string {
  177. err := c.LoadIssue()
  178. if err != nil { // Silently dropping errors :unamused:
  179. log.Error("LoadIssue(%d): %v", c.IssueID, err)
  180. return ""
  181. }
  182. err = c.Issue.loadRepo(x)
  183. if err != nil { // Silently dropping errors :unamused:
  184. log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
  185. return ""
  186. }
  187. if c.Type == CommentTypeCode {
  188. if c.ReviewID == 0 {
  189. return fmt.Sprintf("%s/files#%s", c.Issue.HTMLURL(), c.HashTag())
  190. }
  191. if c.Review == nil {
  192. if err := c.LoadReview(); err != nil {
  193. log.Warn("LoadReview(%d): %v", c.ReviewID, err)
  194. return fmt.Sprintf("%s/files#%s", c.Issue.HTMLURL(), c.HashTag())
  195. }
  196. }
  197. if c.Review.Type <= ReviewTypePending {
  198. return fmt.Sprintf("%s/files#%s", c.Issue.HTMLURL(), c.HashTag())
  199. }
  200. }
  201. return fmt.Sprintf("%s#%s", c.Issue.HTMLURL(), c.HashTag())
  202. }
  203. // IssueURL formats a URL-string to the issue
  204. func (c *Comment) IssueURL() string {
  205. err := c.LoadIssue()
  206. if err != nil { // Silently dropping errors :unamused:
  207. log.Error("LoadIssue(%d): %v", c.IssueID, err)
  208. return ""
  209. }
  210. if c.Issue.IsPull {
  211. return ""
  212. }
  213. err = c.Issue.loadRepo(x)
  214. if err != nil { // Silently dropping errors :unamused:
  215. log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
  216. return ""
  217. }
  218. return c.Issue.HTMLURL()
  219. }
  220. // PRURL formats a URL-string to the pull-request
  221. func (c *Comment) PRURL() string {
  222. err := c.LoadIssue()
  223. if err != nil { // Silently dropping errors :unamused:
  224. log.Error("LoadIssue(%d): %v", c.IssueID, err)
  225. return ""
  226. }
  227. err = c.Issue.loadRepo(x)
  228. if err != nil { // Silently dropping errors :unamused:
  229. log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
  230. return ""
  231. }
  232. if !c.Issue.IsPull {
  233. return ""
  234. }
  235. return c.Issue.HTMLURL()
  236. }
  237. // APIFormat converts a Comment to the api.Comment format
  238. func (c *Comment) APIFormat() *api.Comment {
  239. return &api.Comment{
  240. ID: c.ID,
  241. Poster: c.Poster.APIFormat(),
  242. HTMLURL: c.HTMLURL(),
  243. IssueURL: c.IssueURL(),
  244. PRURL: c.PRURL(),
  245. Body: c.Content,
  246. Created: c.CreatedUnix.AsTime(),
  247. Updated: c.UpdatedUnix.AsTime(),
  248. }
  249. }
  250. // CommentHashTag returns unique hash tag for comment id.
  251. func CommentHashTag(id int64) string {
  252. return fmt.Sprintf("issuecomment-%d", id)
  253. }
  254. // HashTag returns unique hash tag for comment.
  255. func (c *Comment) HashTag() string {
  256. return CommentHashTag(c.ID)
  257. }
  258. // EventTag returns unique event hash tag for comment.
  259. func (c *Comment) EventTag() string {
  260. return "event-" + com.ToStr(c.ID)
  261. }
  262. // LoadLabel if comment.Type is CommentTypeLabel, then load Label
  263. func (c *Comment) LoadLabel() error {
  264. var label Label
  265. has, err := x.ID(c.LabelID).Get(&label)
  266. if err != nil {
  267. return err
  268. } else if has {
  269. c.Label = &label
  270. } else {
  271. // Ignore Label is deleted, but not clear this table
  272. log.Warn("Commit %d cannot load label %d", c.ID, c.LabelID)
  273. }
  274. return nil
  275. }
  276. // LoadMilestone if comment.Type is CommentTypeMilestone, then load milestone
  277. func (c *Comment) LoadMilestone() error {
  278. if c.OldMilestoneID > 0 {
  279. var oldMilestone Milestone
  280. has, err := x.ID(c.OldMilestoneID).Get(&oldMilestone)
  281. if err != nil {
  282. return err
  283. } else if has {
  284. c.OldMilestone = &oldMilestone
  285. }
  286. }
  287. if c.MilestoneID > 0 {
  288. var milestone Milestone
  289. has, err := x.ID(c.MilestoneID).Get(&milestone)
  290. if err != nil {
  291. return err
  292. } else if has {
  293. c.Milestone = &milestone
  294. }
  295. }
  296. return nil
  297. }
  298. // LoadPoster loads comment poster
  299. func (c *Comment) LoadPoster() error {
  300. return c.loadPoster(x)
  301. }
  302. // LoadAttachments loads attachments
  303. func (c *Comment) LoadAttachments() error {
  304. if len(c.Attachments) > 0 {
  305. return nil
  306. }
  307. var err error
  308. c.Attachments, err = getAttachmentsByCommentID(x, c.ID)
  309. if err != nil {
  310. log.Error("getAttachmentsByCommentID[%d]: %v", c.ID, err)
  311. }
  312. return nil
  313. }
  314. // LoadAssigneeUser if comment.Type is CommentTypeAssignees, then load assignees
  315. func (c *Comment) LoadAssigneeUser() error {
  316. var err error
  317. if c.AssigneeID > 0 {
  318. c.Assignee, err = getUserByID(x, c.AssigneeID)
  319. if err != nil {
  320. if !IsErrUserNotExist(err) {
  321. return err
  322. }
  323. c.Assignee = NewGhostUser()
  324. }
  325. }
  326. return nil
  327. }
  328. // LoadDepIssueDetails loads Dependent Issue Details
  329. func (c *Comment) LoadDepIssueDetails() (err error) {
  330. if c.DependentIssueID <= 0 || c.DependentIssue != nil {
  331. return nil
  332. }
  333. c.DependentIssue, err = getIssueByID(x, c.DependentIssueID)
  334. return err
  335. }
  336. func (c *Comment) loadReactions(e Engine) (err error) {
  337. if c.Reactions != nil {
  338. return nil
  339. }
  340. c.Reactions, err = findReactions(e, FindReactionsOptions{
  341. IssueID: c.IssueID,
  342. CommentID: c.ID,
  343. })
  344. if err != nil {
  345. return err
  346. }
  347. // Load reaction user data
  348. if _, err := c.Reactions.LoadUsers(); err != nil {
  349. return err
  350. }
  351. return nil
  352. }
  353. // LoadReactions loads comment reactions
  354. func (c *Comment) LoadReactions() error {
  355. return c.loadReactions(x)
  356. }
  357. func (c *Comment) loadReview(e Engine) (err error) {
  358. if c.Review == nil {
  359. if c.Review, err = getReviewByID(e, c.ReviewID); err != nil {
  360. return err
  361. }
  362. }
  363. c.Review.Issue = c.Issue
  364. return nil
  365. }
  366. // LoadReview loads the associated review
  367. func (c *Comment) LoadReview() error {
  368. return c.loadReview(x)
  369. }
  370. func (c *Comment) checkInvalidation(doer *User, repo *git.Repository, branch string) error {
  371. // FIXME differentiate between previous and proposed line
  372. commit, err := repo.LineBlame(branch, repo.Path, c.TreePath, uint(c.UnsignedLine()))
  373. if err != nil {
  374. return err
  375. }
  376. if c.CommitSHA != "" && c.CommitSHA != commit.ID.String() {
  377. c.Invalidated = true
  378. return UpdateComment(c, doer)
  379. }
  380. return nil
  381. }
  382. // CheckInvalidation checks if the line of code comment got changed by another commit.
  383. // If the line got changed the comment is going to be invalidated.
  384. func (c *Comment) CheckInvalidation(repo *git.Repository, doer *User, branch string) error {
  385. return c.checkInvalidation(doer, repo, branch)
  386. }
  387. // DiffSide returns "previous" if Comment.Line is a LOC of the previous changes and "proposed" if it is a LOC of the proposed changes.
  388. func (c *Comment) DiffSide() string {
  389. if c.Line < 0 {
  390. return "previous"
  391. }
  392. return "proposed"
  393. }
  394. // UnsignedLine returns the LOC of the code comment without + or -
  395. func (c *Comment) UnsignedLine() uint64 {
  396. if c.Line < 0 {
  397. return uint64(c.Line * -1)
  398. }
  399. return uint64(c.Line)
  400. }
  401. // CodeCommentURL returns the url to a comment in code
  402. func (c *Comment) CodeCommentURL() string {
  403. err := c.LoadIssue()
  404. if err != nil { // Silently dropping errors :unamused:
  405. log.Error("LoadIssue(%d): %v", c.IssueID, err)
  406. return ""
  407. }
  408. err = c.Issue.loadRepo(x)
  409. if err != nil { // Silently dropping errors :unamused:
  410. log.Error("loadRepo(%d): %v", c.Issue.RepoID, err)
  411. return ""
  412. }
  413. return fmt.Sprintf("%s/files#%s", c.Issue.HTMLURL(), c.HashTag())
  414. }
  415. func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err error) {
  416. var LabelID int64
  417. if opts.Label != nil {
  418. LabelID = opts.Label.ID
  419. }
  420. comment := &Comment{
  421. Type: opts.Type,
  422. PosterID: opts.Doer.ID,
  423. Poster: opts.Doer,
  424. IssueID: opts.Issue.ID,
  425. LabelID: LabelID,
  426. OldMilestoneID: opts.OldMilestoneID,
  427. MilestoneID: opts.MilestoneID,
  428. RemovedAssignee: opts.RemovedAssignee,
  429. AssigneeID: opts.AssigneeID,
  430. CommitID: opts.CommitID,
  431. CommitSHA: opts.CommitSHA,
  432. Line: opts.LineNum,
  433. Content: opts.Content,
  434. OldTitle: opts.OldTitle,
  435. NewTitle: opts.NewTitle,
  436. DependentIssueID: opts.DependentIssueID,
  437. TreePath: opts.TreePath,
  438. ReviewID: opts.ReviewID,
  439. Patch: opts.Patch,
  440. RefRepoID: opts.RefRepoID,
  441. RefIssueID: opts.RefIssueID,
  442. RefCommentID: opts.RefCommentID,
  443. RefAction: opts.RefAction,
  444. RefIsPull: opts.RefIsPull,
  445. }
  446. if _, err = e.Insert(comment); err != nil {
  447. return nil, err
  448. }
  449. if err = opts.Repo.getOwner(e); err != nil {
  450. return nil, err
  451. }
  452. if err = sendCreateCommentAction(e, opts, comment); err != nil {
  453. return nil, err
  454. }
  455. if err = comment.addCrossReferences(e, opts.Doer); err != nil {
  456. return nil, err
  457. }
  458. return comment, nil
  459. }
  460. func sendCreateCommentAction(e *xorm.Session, opts *CreateCommentOptions, comment *Comment) (err error) {
  461. // Compose comment action, could be plain comment, close or reopen issue/pull request.
  462. // This object will be used to notify watchers in the end of function.
  463. act := &Action{
  464. ActUserID: opts.Doer.ID,
  465. ActUser: opts.Doer,
  466. Content: fmt.Sprintf("%d|%s", opts.Issue.Index, strings.Split(opts.Content, "\n")[0]),
  467. RepoID: opts.Repo.ID,
  468. Repo: opts.Repo,
  469. Comment: comment,
  470. CommentID: comment.ID,
  471. IsPrivate: opts.Repo.IsPrivate,
  472. }
  473. // Check comment type.
  474. switch opts.Type {
  475. case CommentTypeCode:
  476. if comment.ReviewID != 0 {
  477. // Hotfix for 1.10.0 as the Review object has not yet been committed in the other session
  478. if opts.Review != nil {
  479. comment.Review = opts.Review
  480. }
  481. if comment.Review == nil {
  482. if err := comment.loadReview(e); err != nil {
  483. return err
  484. }
  485. }
  486. if comment.Review.Type <= ReviewTypePending {
  487. return nil
  488. }
  489. }
  490. fallthrough
  491. case CommentTypeComment:
  492. act.OpType = ActionCommentIssue
  493. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
  494. return err
  495. }
  496. // Check attachments
  497. attachments := make([]*Attachment, 0, len(opts.Attachments))
  498. for _, uuid := range opts.Attachments {
  499. attach, err := getAttachmentByUUID(e, uuid)
  500. if err != nil {
  501. if IsErrAttachmentNotExist(err) {
  502. continue
  503. }
  504. return fmt.Errorf("getAttachmentByUUID [%s]: %v", uuid, err)
  505. }
  506. attachments = append(attachments, attach)
  507. }
  508. for i := range attachments {
  509. attachments[i].IssueID = opts.Issue.ID
  510. attachments[i].CommentID = comment.ID
  511. // No assign value could be 0, so ignore AllCols().
  512. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  513. return fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  514. }
  515. }
  516. case CommentTypeReopen:
  517. act.OpType = ActionReopenIssue
  518. if opts.Issue.IsPull {
  519. act.OpType = ActionReopenPullRequest
  520. }
  521. if err = opts.Issue.updateClosedNum(e); err != nil {
  522. return err
  523. }
  524. case CommentTypeClose:
  525. act.OpType = ActionCloseIssue
  526. if opts.Issue.IsPull {
  527. act.OpType = ActionClosePullRequest
  528. }
  529. if err = opts.Issue.updateClosedNum(e); err != nil {
  530. return err
  531. }
  532. case CommentTypeReview:
  533. // Hotfix for 1.10.0; make sure a dashboard entry is created
  534. if opts.Content == "" {
  535. return nil
  536. }
  537. act.OpType = ActionCommentIssue
  538. }
  539. // update the issue's updated_unix column
  540. if err = updateIssueCols(e, opts.Issue, "updated_unix"); err != nil {
  541. return err
  542. }
  543. // Notify watchers for whatever action comes in, ignore if no action type.
  544. if act.OpType > 0 {
  545. if err = notifyWatchers(e, act); err != nil {
  546. log.Error("notifyWatchers: %v", err)
  547. }
  548. }
  549. return nil
  550. }
  551. func createStatusComment(e *xorm.Session, doer *User, issue *Issue) (*Comment, error) {
  552. cmtType := CommentTypeClose
  553. if !issue.IsClosed {
  554. cmtType = CommentTypeReopen
  555. }
  556. return createComment(e, &CreateCommentOptions{
  557. Type: cmtType,
  558. Doer: doer,
  559. Repo: issue.Repo,
  560. Issue: issue,
  561. })
  562. }
  563. func createLabelComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, label *Label, add bool) (*Comment, error) {
  564. var content string
  565. if add {
  566. content = "1"
  567. }
  568. return createComment(e, &CreateCommentOptions{
  569. Type: CommentTypeLabel,
  570. Doer: doer,
  571. Repo: repo,
  572. Issue: issue,
  573. Label: label,
  574. Content: content,
  575. })
  576. }
  577. func createMilestoneComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldMilestoneID, milestoneID int64) (*Comment, error) {
  578. return createComment(e, &CreateCommentOptions{
  579. Type: CommentTypeMilestone,
  580. Doer: doer,
  581. Repo: repo,
  582. Issue: issue,
  583. OldMilestoneID: oldMilestoneID,
  584. MilestoneID: milestoneID,
  585. })
  586. }
  587. func createAssigneeComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, assigneeID int64, removedAssignee bool) (*Comment, error) {
  588. return createComment(e, &CreateCommentOptions{
  589. Type: CommentTypeAssignees,
  590. Doer: doer,
  591. Repo: repo,
  592. Issue: issue,
  593. RemovedAssignee: removedAssignee,
  594. AssigneeID: assigneeID,
  595. })
  596. }
  597. func createDeadlineComment(e *xorm.Session, doer *User, issue *Issue, newDeadlineUnix timeutil.TimeStamp) (*Comment, error) {
  598. var content string
  599. var commentType CommentType
  600. // newDeadline = 0 means deleting
  601. if newDeadlineUnix == 0 {
  602. commentType = CommentTypeRemovedDeadline
  603. content = issue.DeadlineUnix.Format("2006-01-02")
  604. } else if issue.DeadlineUnix == 0 {
  605. // Check if the new date was added or modified
  606. // If the actual deadline is 0 => deadline added
  607. commentType = CommentTypeAddedDeadline
  608. content = newDeadlineUnix.Format("2006-01-02")
  609. } else { // Otherwise modified
  610. commentType = CommentTypeModifiedDeadline
  611. content = newDeadlineUnix.Format("2006-01-02") + "|" + issue.DeadlineUnix.Format("2006-01-02")
  612. }
  613. if err := issue.loadRepo(e); err != nil {
  614. return nil, err
  615. }
  616. return createComment(e, &CreateCommentOptions{
  617. Type: commentType,
  618. Doer: doer,
  619. Repo: issue.Repo,
  620. Issue: issue,
  621. Content: content,
  622. })
  623. }
  624. func createChangeTitleComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldTitle, newTitle string) (*Comment, error) {
  625. return createComment(e, &CreateCommentOptions{
  626. Type: CommentTypeChangeTitle,
  627. Doer: doer,
  628. Repo: repo,
  629. Issue: issue,
  630. OldTitle: oldTitle,
  631. NewTitle: newTitle,
  632. })
  633. }
  634. func createDeleteBranchComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, branchName string) (*Comment, error) {
  635. return createComment(e, &CreateCommentOptions{
  636. Type: CommentTypeDeleteBranch,
  637. Doer: doer,
  638. Repo: repo,
  639. Issue: issue,
  640. CommitSHA: branchName,
  641. })
  642. }
  643. // Creates issue dependency comment
  644. func createIssueDependencyComment(e *xorm.Session, doer *User, issue *Issue, dependentIssue *Issue, add bool) (err error) {
  645. cType := CommentTypeAddDependency
  646. if !add {
  647. cType = CommentTypeRemoveDependency
  648. }
  649. if err = issue.loadRepo(e); err != nil {
  650. return
  651. }
  652. // Make two comments, one in each issue
  653. _, err = createComment(e, &CreateCommentOptions{
  654. Type: cType,
  655. Doer: doer,
  656. Repo: issue.Repo,
  657. Issue: issue,
  658. DependentIssueID: dependentIssue.ID,
  659. })
  660. if err != nil {
  661. return
  662. }
  663. _, err = createComment(e, &CreateCommentOptions{
  664. Type: cType,
  665. Doer: doer,
  666. Repo: issue.Repo,
  667. Issue: dependentIssue,
  668. DependentIssueID: issue.ID,
  669. })
  670. if err != nil {
  671. return
  672. }
  673. return
  674. }
  675. // CreateCommentOptions defines options for creating comment
  676. type CreateCommentOptions struct {
  677. Type CommentType
  678. Doer *User
  679. Repo *Repository
  680. Issue *Issue
  681. Label *Label
  682. Review *Review
  683. DependentIssueID int64
  684. OldMilestoneID int64
  685. MilestoneID int64
  686. AssigneeID int64
  687. RemovedAssignee bool
  688. OldTitle string
  689. NewTitle string
  690. CommitID int64
  691. CommitSHA string
  692. Patch string
  693. LineNum int64
  694. TreePath string
  695. ReviewID int64
  696. Content string
  697. Attachments []string // UUIDs of attachments
  698. RefRepoID int64
  699. RefIssueID int64
  700. RefCommentID int64
  701. RefAction references.XRefAction
  702. RefIsPull bool
  703. }
  704. // CreateComment creates comment of issue or commit.
  705. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
  706. sess := x.NewSession()
  707. defer sess.Close()
  708. if err = sess.Begin(); err != nil {
  709. return nil, err
  710. }
  711. comment, err = createComment(sess, opts)
  712. if err != nil {
  713. return nil, err
  714. }
  715. if err = sess.Commit(); err != nil {
  716. return nil, err
  717. }
  718. return comment, nil
  719. }
  720. // CreateRefComment creates a commit reference comment to issue.
  721. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  722. if len(commitSHA) == 0 {
  723. return fmt.Errorf("cannot create reference with empty commit SHA")
  724. }
  725. // Check if same reference from same commit has already existed.
  726. has, err := x.Get(&Comment{
  727. Type: CommentTypeCommitRef,
  728. IssueID: issue.ID,
  729. CommitSHA: commitSHA,
  730. })
  731. if err != nil {
  732. return fmt.Errorf("check reference comment: %v", err)
  733. } else if has {
  734. return nil
  735. }
  736. _, err = CreateComment(&CreateCommentOptions{
  737. Type: CommentTypeCommitRef,
  738. Doer: doer,
  739. Repo: repo,
  740. Issue: issue,
  741. CommitSHA: commitSHA,
  742. Content: content,
  743. })
  744. return err
  745. }
  746. // GetCommentByID returns the comment by given ID.
  747. func GetCommentByID(id int64) (*Comment, error) {
  748. c := new(Comment)
  749. has, err := x.ID(id).Get(c)
  750. if err != nil {
  751. return nil, err
  752. } else if !has {
  753. return nil, ErrCommentNotExist{id, 0}
  754. }
  755. return c, nil
  756. }
  757. // FindCommentsOptions describes the conditions to Find comments
  758. type FindCommentsOptions struct {
  759. RepoID int64
  760. IssueID int64
  761. ReviewID int64
  762. Since int64
  763. Type CommentType
  764. }
  765. func (opts *FindCommentsOptions) toConds() builder.Cond {
  766. var cond = builder.NewCond()
  767. if opts.RepoID > 0 {
  768. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  769. }
  770. if opts.IssueID > 0 {
  771. cond = cond.And(builder.Eq{"comment.issue_id": opts.IssueID})
  772. }
  773. if opts.ReviewID > 0 {
  774. cond = cond.And(builder.Eq{"comment.review_id": opts.ReviewID})
  775. }
  776. if opts.Since > 0 {
  777. cond = cond.And(builder.Gte{"comment.updated_unix": opts.Since})
  778. }
  779. if opts.Type != CommentTypeUnknown {
  780. cond = cond.And(builder.Eq{"comment.type": opts.Type})
  781. }
  782. return cond
  783. }
  784. func findComments(e Engine, opts FindCommentsOptions) ([]*Comment, error) {
  785. comments := make([]*Comment, 0, 10)
  786. sess := e.Where(opts.toConds())
  787. if opts.RepoID > 0 {
  788. sess.Join("INNER", "issue", "issue.id = comment.issue_id")
  789. }
  790. return comments, sess.
  791. Asc("comment.created_unix").
  792. Asc("comment.id").
  793. Find(&comments)
  794. }
  795. // FindComments returns all comments according options
  796. func FindComments(opts FindCommentsOptions) ([]*Comment, error) {
  797. return findComments(x, opts)
  798. }
  799. // UpdateComment updates information of comment.
  800. func UpdateComment(c *Comment, doer *User) error {
  801. sess := x.NewSession()
  802. defer sess.Close()
  803. if err := sess.Begin(); err != nil {
  804. return err
  805. }
  806. if _, err := sess.ID(c.ID).AllCols().Update(c); err != nil {
  807. return err
  808. }
  809. if err := c.loadIssue(sess); err != nil {
  810. return err
  811. }
  812. if err := c.neuterCrossReferences(sess); err != nil {
  813. return err
  814. }
  815. if err := c.addCrossReferences(sess, doer); err != nil {
  816. return err
  817. }
  818. if err := sess.Commit(); err != nil {
  819. return fmt.Errorf("Commit: %v", err)
  820. }
  821. return nil
  822. }
  823. // DeleteComment deletes the comment
  824. func DeleteComment(comment *Comment, doer *User) error {
  825. sess := x.NewSession()
  826. defer sess.Close()
  827. if err := sess.Begin(); err != nil {
  828. return err
  829. }
  830. if _, err := sess.Delete(&Comment{
  831. ID: comment.ID,
  832. }); err != nil {
  833. return err
  834. }
  835. if comment.Type == CommentTypeComment {
  836. if _, err := sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  837. return err
  838. }
  839. }
  840. if _, err := sess.Where("comment_id = ?", comment.ID).Cols("is_deleted").Update(&Action{IsDeleted: true}); err != nil {
  841. return err
  842. }
  843. if err := comment.neuterCrossReferences(sess); err != nil {
  844. return err
  845. }
  846. return sess.Commit()
  847. }
  848. // CodeComments represents comments on code by using this structure: FILENAME -> LINE (+ == proposed; - == previous) -> COMMENTS
  849. type CodeComments map[string]map[int64][]*Comment
  850. func fetchCodeComments(e Engine, issue *Issue, currentUser *User) (CodeComments, error) {
  851. return fetchCodeCommentsByReview(e, issue, currentUser, nil)
  852. }
  853. func fetchCodeCommentsByReview(e Engine, issue *Issue, currentUser *User, review *Review) (CodeComments, error) {
  854. pathToLineToComment := make(CodeComments)
  855. if review == nil {
  856. review = &Review{ID: 0}
  857. }
  858. //Find comments
  859. opts := FindCommentsOptions{
  860. Type: CommentTypeCode,
  861. IssueID: issue.ID,
  862. ReviewID: review.ID,
  863. }
  864. conds := opts.toConds()
  865. if review.ID == 0 {
  866. conds = conds.And(builder.Eq{"invalidated": false})
  867. }
  868. var comments []*Comment
  869. if err := e.Where(conds).
  870. Asc("comment.created_unix").
  871. Asc("comment.id").
  872. Find(&comments); err != nil {
  873. return nil, err
  874. }
  875. if err := CommentList(comments).loadPosters(e); err != nil {
  876. return nil, err
  877. }
  878. if err := issue.loadRepo(e); err != nil {
  879. return nil, err
  880. }
  881. if err := CommentList(comments).loadPosters(e); err != nil {
  882. return nil, err
  883. }
  884. // Find all reviews by ReviewID
  885. reviews := make(map[int64]*Review)
  886. var ids = make([]int64, 0, len(comments))
  887. for _, comment := range comments {
  888. if comment.ReviewID != 0 {
  889. ids = append(ids, comment.ReviewID)
  890. }
  891. }
  892. if err := e.In("id", ids).Find(&reviews); err != nil {
  893. return nil, err
  894. }
  895. for _, comment := range comments {
  896. if re, ok := reviews[comment.ReviewID]; ok && re != nil {
  897. // If the review is pending only the author can see the comments (except the review is set)
  898. if review.ID == 0 {
  899. if re.Type == ReviewTypePending &&
  900. (currentUser == nil || currentUser.ID != re.ReviewerID) {
  901. continue
  902. }
  903. }
  904. comment.Review = re
  905. }
  906. comment.RenderedContent = string(markdown.Render([]byte(comment.Content), issue.Repo.Link(),
  907. issue.Repo.ComposeMetas()))
  908. if pathToLineToComment[comment.TreePath] == nil {
  909. pathToLineToComment[comment.TreePath] = make(map[int64][]*Comment)
  910. }
  911. pathToLineToComment[comment.TreePath][comment.Line] = append(pathToLineToComment[comment.TreePath][comment.Line], comment)
  912. }
  913. return pathToLineToComment, nil
  914. }
  915. // FetchCodeComments will return a 2d-map: ["Path"]["Line"] = Comments at line
  916. func FetchCodeComments(issue *Issue, currentUser *User) (CodeComments, error) {
  917. return fetchCodeComments(x, issue, currentUser)
  918. }
  919. // UpdateCommentsMigrationsByType updates comments' migrations information via given git service type and original id and poster id
  920. func UpdateCommentsMigrationsByType(tp structs.GitServiceType, originalAuthorID string, posterID int64) error {
  921. _, err := x.Table("comment").
  922. Where(builder.In("issue_id",
  923. builder.Select("issue.id").
  924. From("issue").
  925. InnerJoin("repository", "issue.repo_id = repository.id").
  926. Where(builder.Eq{
  927. "repository.original_service_type": tp,
  928. }),
  929. )).
  930. And("comment.original_author_id = ?", originalAuthorID).
  931. Update(map[string]interface{}{
  932. "poster_id": posterID,
  933. "original_author": "",
  934. "original_author_id": 0,
  935. })
  936. return err
  937. }