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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  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. if comment.Review == nil {
  478. if err := comment.loadReview(e); err != nil {
  479. return err
  480. }
  481. }
  482. if comment.Review.Type <= ReviewTypePending {
  483. return nil
  484. }
  485. }
  486. fallthrough
  487. case CommentTypeComment:
  488. act.OpType = ActionCommentIssue
  489. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
  490. return err
  491. }
  492. // Check attachments
  493. attachments := make([]*Attachment, 0, len(opts.Attachments))
  494. for _, uuid := range opts.Attachments {
  495. attach, err := getAttachmentByUUID(e, uuid)
  496. if err != nil {
  497. if IsErrAttachmentNotExist(err) {
  498. continue
  499. }
  500. return fmt.Errorf("getAttachmentByUUID [%s]: %v", uuid, err)
  501. }
  502. attachments = append(attachments, attach)
  503. }
  504. for i := range attachments {
  505. attachments[i].IssueID = opts.Issue.ID
  506. attachments[i].CommentID = comment.ID
  507. // No assign value could be 0, so ignore AllCols().
  508. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  509. return fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  510. }
  511. }
  512. case CommentTypeReopen:
  513. act.OpType = ActionReopenIssue
  514. if opts.Issue.IsPull {
  515. act.OpType = ActionReopenPullRequest
  516. }
  517. if err = opts.Issue.updateClosedNum(e); err != nil {
  518. return err
  519. }
  520. case CommentTypeClose:
  521. act.OpType = ActionCloseIssue
  522. if opts.Issue.IsPull {
  523. act.OpType = ActionClosePullRequest
  524. }
  525. if err = opts.Issue.updateClosedNum(e); err != nil {
  526. return err
  527. }
  528. }
  529. // update the issue's updated_unix column
  530. if err = updateIssueCols(e, opts.Issue, "updated_unix"); err != nil {
  531. return err
  532. }
  533. // Notify watchers for whatever action comes in, ignore if no action type.
  534. if act.OpType > 0 {
  535. if err = notifyWatchers(e, act); err != nil {
  536. log.Error("notifyWatchers: %v", err)
  537. }
  538. }
  539. return nil
  540. }
  541. func createStatusComment(e *xorm.Session, doer *User, issue *Issue) (*Comment, error) {
  542. cmtType := CommentTypeClose
  543. if !issue.IsClosed {
  544. cmtType = CommentTypeReopen
  545. }
  546. return createComment(e, &CreateCommentOptions{
  547. Type: cmtType,
  548. Doer: doer,
  549. Repo: issue.Repo,
  550. Issue: issue,
  551. })
  552. }
  553. func createLabelComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, label *Label, add bool) (*Comment, error) {
  554. var content string
  555. if add {
  556. content = "1"
  557. }
  558. return createComment(e, &CreateCommentOptions{
  559. Type: CommentTypeLabel,
  560. Doer: doer,
  561. Repo: repo,
  562. Issue: issue,
  563. Label: label,
  564. Content: content,
  565. })
  566. }
  567. func createMilestoneComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldMilestoneID, milestoneID int64) (*Comment, error) {
  568. return createComment(e, &CreateCommentOptions{
  569. Type: CommentTypeMilestone,
  570. Doer: doer,
  571. Repo: repo,
  572. Issue: issue,
  573. OldMilestoneID: oldMilestoneID,
  574. MilestoneID: milestoneID,
  575. })
  576. }
  577. func createAssigneeComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, assigneeID int64, removedAssignee bool) (*Comment, error) {
  578. return createComment(e, &CreateCommentOptions{
  579. Type: CommentTypeAssignees,
  580. Doer: doer,
  581. Repo: repo,
  582. Issue: issue,
  583. RemovedAssignee: removedAssignee,
  584. AssigneeID: assigneeID,
  585. })
  586. }
  587. func createDeadlineComment(e *xorm.Session, doer *User, issue *Issue, newDeadlineUnix timeutil.TimeStamp) (*Comment, error) {
  588. var content string
  589. var commentType CommentType
  590. // newDeadline = 0 means deleting
  591. if newDeadlineUnix == 0 {
  592. commentType = CommentTypeRemovedDeadline
  593. content = issue.DeadlineUnix.Format("2006-01-02")
  594. } else if issue.DeadlineUnix == 0 {
  595. // Check if the new date was added or modified
  596. // If the actual deadline is 0 => deadline added
  597. commentType = CommentTypeAddedDeadline
  598. content = newDeadlineUnix.Format("2006-01-02")
  599. } else { // Otherwise modified
  600. commentType = CommentTypeModifiedDeadline
  601. content = newDeadlineUnix.Format("2006-01-02") + "|" + issue.DeadlineUnix.Format("2006-01-02")
  602. }
  603. if err := issue.loadRepo(e); err != nil {
  604. return nil, err
  605. }
  606. return createComment(e, &CreateCommentOptions{
  607. Type: commentType,
  608. Doer: doer,
  609. Repo: issue.Repo,
  610. Issue: issue,
  611. Content: content,
  612. })
  613. }
  614. func createChangeTitleComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldTitle, newTitle string) (*Comment, error) {
  615. return createComment(e, &CreateCommentOptions{
  616. Type: CommentTypeChangeTitle,
  617. Doer: doer,
  618. Repo: repo,
  619. Issue: issue,
  620. OldTitle: oldTitle,
  621. NewTitle: newTitle,
  622. })
  623. }
  624. func createDeleteBranchComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, branchName string) (*Comment, error) {
  625. return createComment(e, &CreateCommentOptions{
  626. Type: CommentTypeDeleteBranch,
  627. Doer: doer,
  628. Repo: repo,
  629. Issue: issue,
  630. CommitSHA: branchName,
  631. })
  632. }
  633. // Creates issue dependency comment
  634. func createIssueDependencyComment(e *xorm.Session, doer *User, issue *Issue, dependentIssue *Issue, add bool) (err error) {
  635. cType := CommentTypeAddDependency
  636. if !add {
  637. cType = CommentTypeRemoveDependency
  638. }
  639. if err = issue.loadRepo(e); err != nil {
  640. return
  641. }
  642. // Make two comments, one in each issue
  643. _, err = createComment(e, &CreateCommentOptions{
  644. Type: cType,
  645. Doer: doer,
  646. Repo: issue.Repo,
  647. Issue: issue,
  648. DependentIssueID: dependentIssue.ID,
  649. })
  650. if err != nil {
  651. return
  652. }
  653. _, err = createComment(e, &CreateCommentOptions{
  654. Type: cType,
  655. Doer: doer,
  656. Repo: issue.Repo,
  657. Issue: dependentIssue,
  658. DependentIssueID: issue.ID,
  659. })
  660. if err != nil {
  661. return
  662. }
  663. return
  664. }
  665. // CreateCommentOptions defines options for creating comment
  666. type CreateCommentOptions struct {
  667. Type CommentType
  668. Doer *User
  669. Repo *Repository
  670. Issue *Issue
  671. Label *Label
  672. DependentIssueID int64
  673. OldMilestoneID int64
  674. MilestoneID int64
  675. AssigneeID int64
  676. RemovedAssignee bool
  677. OldTitle string
  678. NewTitle string
  679. CommitID int64
  680. CommitSHA string
  681. Patch string
  682. LineNum int64
  683. TreePath string
  684. ReviewID int64
  685. Content string
  686. Attachments []string // UUIDs of attachments
  687. RefRepoID int64
  688. RefIssueID int64
  689. RefCommentID int64
  690. RefAction references.XRefAction
  691. RefIsPull bool
  692. }
  693. // CreateComment creates comment of issue or commit.
  694. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
  695. sess := x.NewSession()
  696. defer sess.Close()
  697. if err = sess.Begin(); err != nil {
  698. return nil, err
  699. }
  700. comment, err = createComment(sess, opts)
  701. if err != nil {
  702. return nil, err
  703. }
  704. if err = sess.Commit(); err != nil {
  705. return nil, err
  706. }
  707. return comment, nil
  708. }
  709. // CreateRefComment creates a commit reference comment to issue.
  710. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  711. if len(commitSHA) == 0 {
  712. return fmt.Errorf("cannot create reference with empty commit SHA")
  713. }
  714. // Check if same reference from same commit has already existed.
  715. has, err := x.Get(&Comment{
  716. Type: CommentTypeCommitRef,
  717. IssueID: issue.ID,
  718. CommitSHA: commitSHA,
  719. })
  720. if err != nil {
  721. return fmt.Errorf("check reference comment: %v", err)
  722. } else if has {
  723. return nil
  724. }
  725. _, err = CreateComment(&CreateCommentOptions{
  726. Type: CommentTypeCommitRef,
  727. Doer: doer,
  728. Repo: repo,
  729. Issue: issue,
  730. CommitSHA: commitSHA,
  731. Content: content,
  732. })
  733. return err
  734. }
  735. // GetCommentByID returns the comment by given ID.
  736. func GetCommentByID(id int64) (*Comment, error) {
  737. c := new(Comment)
  738. has, err := x.ID(id).Get(c)
  739. if err != nil {
  740. return nil, err
  741. } else if !has {
  742. return nil, ErrCommentNotExist{id, 0}
  743. }
  744. return c, nil
  745. }
  746. // FindCommentsOptions describes the conditions to Find comments
  747. type FindCommentsOptions struct {
  748. RepoID int64
  749. IssueID int64
  750. ReviewID int64
  751. Since int64
  752. Type CommentType
  753. }
  754. func (opts *FindCommentsOptions) toConds() builder.Cond {
  755. var cond = builder.NewCond()
  756. if opts.RepoID > 0 {
  757. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  758. }
  759. if opts.IssueID > 0 {
  760. cond = cond.And(builder.Eq{"comment.issue_id": opts.IssueID})
  761. }
  762. if opts.ReviewID > 0 {
  763. cond = cond.And(builder.Eq{"comment.review_id": opts.ReviewID})
  764. }
  765. if opts.Since > 0 {
  766. cond = cond.And(builder.Gte{"comment.updated_unix": opts.Since})
  767. }
  768. if opts.Type != CommentTypeUnknown {
  769. cond = cond.And(builder.Eq{"comment.type": opts.Type})
  770. }
  771. return cond
  772. }
  773. func findComments(e Engine, opts FindCommentsOptions) ([]*Comment, error) {
  774. comments := make([]*Comment, 0, 10)
  775. sess := e.Where(opts.toConds())
  776. if opts.RepoID > 0 {
  777. sess.Join("INNER", "issue", "issue.id = comment.issue_id")
  778. }
  779. return comments, sess.
  780. Asc("comment.created_unix").
  781. Asc("comment.id").
  782. Find(&comments)
  783. }
  784. // FindComments returns all comments according options
  785. func FindComments(opts FindCommentsOptions) ([]*Comment, error) {
  786. return findComments(x, opts)
  787. }
  788. // UpdateComment updates information of comment.
  789. func UpdateComment(c *Comment, doer *User) error {
  790. sess := x.NewSession()
  791. defer sess.Close()
  792. if err := sess.Begin(); err != nil {
  793. return err
  794. }
  795. if _, err := sess.ID(c.ID).AllCols().Update(c); err != nil {
  796. return err
  797. }
  798. if err := c.loadIssue(sess); err != nil {
  799. return err
  800. }
  801. if err := c.neuterCrossReferences(sess); err != nil {
  802. return err
  803. }
  804. if err := c.addCrossReferences(sess, doer); err != nil {
  805. return err
  806. }
  807. if err := sess.Commit(); err != nil {
  808. return fmt.Errorf("Commit: %v", err)
  809. }
  810. return nil
  811. }
  812. // DeleteComment deletes the comment
  813. func DeleteComment(comment *Comment, doer *User) error {
  814. sess := x.NewSession()
  815. defer sess.Close()
  816. if err := sess.Begin(); err != nil {
  817. return err
  818. }
  819. if _, err := sess.Delete(&Comment{
  820. ID: comment.ID,
  821. }); err != nil {
  822. return err
  823. }
  824. if comment.Type == CommentTypeComment {
  825. if _, err := sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  826. return err
  827. }
  828. }
  829. if _, err := sess.Where("comment_id = ?", comment.ID).Cols("is_deleted").Update(&Action{IsDeleted: true}); err != nil {
  830. return err
  831. }
  832. if err := comment.neuterCrossReferences(sess); err != nil {
  833. return err
  834. }
  835. return sess.Commit()
  836. }
  837. // CodeComments represents comments on code by using this structure: FILENAME -> LINE (+ == proposed; - == previous) -> COMMENTS
  838. type CodeComments map[string]map[int64][]*Comment
  839. func fetchCodeComments(e Engine, issue *Issue, currentUser *User) (CodeComments, error) {
  840. return fetchCodeCommentsByReview(e, issue, currentUser, nil)
  841. }
  842. func fetchCodeCommentsByReview(e Engine, issue *Issue, currentUser *User, review *Review) (CodeComments, error) {
  843. pathToLineToComment := make(CodeComments)
  844. if review == nil {
  845. review = &Review{ID: 0}
  846. }
  847. //Find comments
  848. opts := FindCommentsOptions{
  849. Type: CommentTypeCode,
  850. IssueID: issue.ID,
  851. ReviewID: review.ID,
  852. }
  853. conds := opts.toConds()
  854. if review.ID == 0 {
  855. conds = conds.And(builder.Eq{"invalidated": false})
  856. }
  857. var comments []*Comment
  858. if err := e.Where(conds).
  859. Asc("comment.created_unix").
  860. Asc("comment.id").
  861. Find(&comments); err != nil {
  862. return nil, err
  863. }
  864. if err := CommentList(comments).loadPosters(e); err != nil {
  865. return nil, err
  866. }
  867. if err := issue.loadRepo(e); err != nil {
  868. return nil, err
  869. }
  870. if err := CommentList(comments).loadPosters(e); err != nil {
  871. return nil, err
  872. }
  873. // Find all reviews by ReviewID
  874. reviews := make(map[int64]*Review)
  875. var ids = make([]int64, 0, len(comments))
  876. for _, comment := range comments {
  877. if comment.ReviewID != 0 {
  878. ids = append(ids, comment.ReviewID)
  879. }
  880. }
  881. if err := e.In("id", ids).Find(&reviews); err != nil {
  882. return nil, err
  883. }
  884. for _, comment := range comments {
  885. if re, ok := reviews[comment.ReviewID]; ok && re != nil {
  886. // If the review is pending only the author can see the comments (except the review is set)
  887. if review.ID == 0 {
  888. if re.Type == ReviewTypePending &&
  889. (currentUser == nil || currentUser.ID != re.ReviewerID) {
  890. continue
  891. }
  892. }
  893. comment.Review = re
  894. }
  895. comment.RenderedContent = string(markdown.Render([]byte(comment.Content), issue.Repo.Link(),
  896. issue.Repo.ComposeMetas()))
  897. if pathToLineToComment[comment.TreePath] == nil {
  898. pathToLineToComment[comment.TreePath] = make(map[int64][]*Comment)
  899. }
  900. pathToLineToComment[comment.TreePath][comment.Line] = append(pathToLineToComment[comment.TreePath][comment.Line], comment)
  901. }
  902. return pathToLineToComment, nil
  903. }
  904. // FetchCodeComments will return a 2d-map: ["Path"]["Line"] = Comments at line
  905. func FetchCodeComments(issue *Issue, currentUser *User) (CodeComments, error) {
  906. return fetchCodeComments(x, issue, currentUser)
  907. }
  908. // UpdateCommentsMigrationsByType updates comments' migrations information via given git service type and original id and poster id
  909. func UpdateCommentsMigrationsByType(tp structs.GitServiceType, originalAuthorID string, posterID int64) error {
  910. _, err := x.Table("comment").
  911. Where(builder.In("issue_id",
  912. builder.Select("issue.id").
  913. From("issue").
  914. InnerJoin("repository", "issue.repo_id = repository.id").
  915. Where(builder.Eq{
  916. "repository.original_service_type": tp,
  917. }),
  918. )).
  919. And("comment.original_author_id = ?", originalAuthorID).
  920. Update(map[string]interface{}{
  921. "poster_id": posterID,
  922. "original_author": "",
  923. "original_author_id": 0,
  924. })
  925. return err
  926. }