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

issue_comment.go 18 kB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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. )
  55. // CommentTag defines comment tag type
  56. type CommentTag int
  57. // Enumerate all the comment tag types
  58. const (
  59. CommentTagNone CommentTag = iota
  60. CommentTagPoster
  61. CommentTagWriter
  62. CommentTagOwner
  63. )
  64. // Comment represents a comment in commit and issue page.
  65. type Comment struct {
  66. ID int64 `xorm:"pk autoincr"`
  67. Type CommentType
  68. PosterID int64 `xorm:"INDEX"`
  69. Poster *User `xorm:"-"`
  70. IssueID int64 `xorm:"INDEX"`
  71. LabelID int64
  72. Label *Label `xorm:"-"`
  73. OldMilestoneID int64
  74. MilestoneID int64
  75. OldMilestone *Milestone `xorm:"-"`
  76. Milestone *Milestone `xorm:"-"`
  77. OldAssigneeID int64
  78. AssigneeID int64
  79. Assignee *User `xorm:"-"`
  80. OldAssignee *User `xorm:"-"`
  81. OldTitle string
  82. NewTitle string
  83. CommitID int64
  84. Line int64
  85. Content string `xorm:"TEXT"`
  86. RenderedContent string `xorm:"-"`
  87. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  88. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  89. // Reference issue in commit message
  90. CommitSHA string `xorm:"VARCHAR(40)"`
  91. Attachments []*Attachment `xorm:"-"`
  92. Reactions ReactionList `xorm:"-"`
  93. // For view issue page.
  94. ShowTag CommentTag `xorm:"-"`
  95. }
  96. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  97. func (c *Comment) AfterLoad(session *xorm.Session) {
  98. var err error
  99. c.Attachments, err = getAttachmentsByCommentID(session, c.ID)
  100. if err != nil {
  101. log.Error(3, "getAttachmentsByCommentID[%d]: %v", c.ID, err)
  102. }
  103. c.Poster, err = getUserByID(session, c.PosterID)
  104. if err != nil {
  105. if IsErrUserNotExist(err) {
  106. c.PosterID = -1
  107. c.Poster = NewGhostUser()
  108. } else {
  109. log.Error(3, "getUserByID[%d]: %v", c.ID, err)
  110. }
  111. }
  112. }
  113. // AfterDelete is invoked from XORM after the object is deleted.
  114. func (c *Comment) AfterDelete() {
  115. _, err := DeleteAttachmentsByComment(c.ID, true)
  116. if err != nil {
  117. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  118. }
  119. }
  120. // HTMLURL formats a URL-string to the issue-comment
  121. func (c *Comment) HTMLURL() string {
  122. issue, err := GetIssueByID(c.IssueID)
  123. if err != nil { // Silently dropping errors :unamused:
  124. log.Error(4, "GetIssueByID(%d): %v", c.IssueID, err)
  125. return ""
  126. }
  127. return fmt.Sprintf("%s#%s", issue.HTMLURL(), c.HashTag())
  128. }
  129. // IssueURL formats a URL-string to the issue
  130. func (c *Comment) IssueURL() string {
  131. issue, err := GetIssueByID(c.IssueID)
  132. if err != nil { // Silently dropping errors :unamused:
  133. log.Error(4, "GetIssueByID(%d): %v", c.IssueID, err)
  134. return ""
  135. }
  136. if issue.IsPull {
  137. return ""
  138. }
  139. return issue.HTMLURL()
  140. }
  141. // PRURL formats a URL-string to the pull-request
  142. func (c *Comment) PRURL() string {
  143. issue, err := GetIssueByID(c.IssueID)
  144. if err != nil { // Silently dropping errors :unamused:
  145. log.Error(4, "GetIssueByID(%d): %v", c.IssueID, err)
  146. return ""
  147. }
  148. if !issue.IsPull {
  149. return ""
  150. }
  151. return issue.HTMLURL()
  152. }
  153. // APIFormat converts a Comment to the api.Comment format
  154. func (c *Comment) APIFormat() *api.Comment {
  155. return &api.Comment{
  156. ID: c.ID,
  157. Poster: c.Poster.APIFormat(),
  158. HTMLURL: c.HTMLURL(),
  159. IssueURL: c.IssueURL(),
  160. PRURL: c.PRURL(),
  161. Body: c.Content,
  162. Created: c.CreatedUnix.AsTime(),
  163. Updated: c.UpdatedUnix.AsTime(),
  164. }
  165. }
  166. // HashTag returns unique hash tag for comment.
  167. func (c *Comment) HashTag() string {
  168. return "issuecomment-" + com.ToStr(c.ID)
  169. }
  170. // EventTag returns unique event hash tag for comment.
  171. func (c *Comment) EventTag() string {
  172. return "event-" + com.ToStr(c.ID)
  173. }
  174. // LoadLabel if comment.Type is CommentTypeLabel, then load Label
  175. func (c *Comment) LoadLabel() error {
  176. var label Label
  177. has, err := x.ID(c.LabelID).Get(&label)
  178. if err != nil {
  179. return err
  180. } else if has {
  181. c.Label = &label
  182. } else {
  183. // Ignore Label is deleted, but not clear this table
  184. log.Warn("Commit %d cannot load label %d", c.ID, c.LabelID)
  185. }
  186. return nil
  187. }
  188. // LoadMilestone if comment.Type is CommentTypeMilestone, then load milestone
  189. func (c *Comment) LoadMilestone() error {
  190. if c.OldMilestoneID > 0 {
  191. var oldMilestone Milestone
  192. has, err := x.ID(c.OldMilestoneID).Get(&oldMilestone)
  193. if err != nil {
  194. return err
  195. } else if has {
  196. c.OldMilestone = &oldMilestone
  197. }
  198. }
  199. if c.MilestoneID > 0 {
  200. var milestone Milestone
  201. has, err := x.ID(c.MilestoneID).Get(&milestone)
  202. if err != nil {
  203. return err
  204. } else if has {
  205. c.Milestone = &milestone
  206. }
  207. }
  208. return nil
  209. }
  210. // LoadAssignees if comment.Type is CommentTypeAssignees, then load assignees
  211. func (c *Comment) LoadAssignees() error {
  212. var err error
  213. if c.OldAssigneeID > 0 {
  214. c.OldAssignee, err = getUserByID(x, c.OldAssigneeID)
  215. if err != nil {
  216. return err
  217. }
  218. }
  219. if c.AssigneeID > 0 {
  220. c.Assignee, err = getUserByID(x, c.AssigneeID)
  221. if err != nil {
  222. return err
  223. }
  224. }
  225. return nil
  226. }
  227. // MailParticipants sends new comment emails to repository watchers
  228. // and mentioned people.
  229. func (c *Comment) MailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
  230. mentions := markup.FindAllMentions(c.Content)
  231. if err = UpdateIssueMentions(e, c.IssueID, mentions); err != nil {
  232. return fmt.Errorf("UpdateIssueMentions [%d]: %v", c.IssueID, err)
  233. }
  234. content := c.Content
  235. switch opType {
  236. case ActionCloseIssue:
  237. content = fmt.Sprintf("Closed #%d", issue.Index)
  238. case ActionReopenIssue:
  239. content = fmt.Sprintf("Reopened #%d", issue.Index)
  240. }
  241. if err = mailIssueCommentToParticipants(e, issue, c.Poster, content, c, mentions); err != nil {
  242. log.Error(4, "mailIssueCommentToParticipants: %v", err)
  243. }
  244. return nil
  245. }
  246. func (c *Comment) loadReactions(e Engine) (err error) {
  247. if c.Reactions != nil {
  248. return nil
  249. }
  250. c.Reactions, err = findReactions(e, FindReactionsOptions{
  251. IssueID: c.IssueID,
  252. CommentID: c.ID,
  253. })
  254. if err != nil {
  255. return err
  256. }
  257. // Load reaction user data
  258. if _, err := c.Reactions.LoadUsers(); err != nil {
  259. return err
  260. }
  261. return nil
  262. }
  263. // LoadReactions loads comment reactions
  264. func (c *Comment) LoadReactions() error {
  265. return c.loadReactions(x)
  266. }
  267. func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err error) {
  268. var LabelID int64
  269. if opts.Label != nil {
  270. LabelID = opts.Label.ID
  271. }
  272. comment := &Comment{
  273. Type: opts.Type,
  274. PosterID: opts.Doer.ID,
  275. Poster: opts.Doer,
  276. IssueID: opts.Issue.ID,
  277. LabelID: LabelID,
  278. OldMilestoneID: opts.OldMilestoneID,
  279. MilestoneID: opts.MilestoneID,
  280. OldAssigneeID: opts.OldAssigneeID,
  281. AssigneeID: opts.AssigneeID,
  282. CommitID: opts.CommitID,
  283. CommitSHA: opts.CommitSHA,
  284. Line: opts.LineNum,
  285. Content: opts.Content,
  286. OldTitle: opts.OldTitle,
  287. NewTitle: opts.NewTitle,
  288. }
  289. if _, err = e.Insert(comment); err != nil {
  290. return nil, err
  291. }
  292. if err = opts.Repo.getOwner(e); err != nil {
  293. return nil, err
  294. }
  295. // Compose comment action, could be plain comment, close or reopen issue/pull request.
  296. // This object will be used to notify watchers in the end of function.
  297. act := &Action{
  298. ActUserID: opts.Doer.ID,
  299. ActUser: opts.Doer,
  300. Content: fmt.Sprintf("%d|%s", opts.Issue.Index, strings.Split(opts.Content, "\n")[0]),
  301. RepoID: opts.Repo.ID,
  302. Repo: opts.Repo,
  303. Comment: comment,
  304. CommentID: comment.ID,
  305. IsPrivate: opts.Repo.IsPrivate,
  306. }
  307. // Check comment type.
  308. switch opts.Type {
  309. case CommentTypeComment:
  310. act.OpType = ActionCommentIssue
  311. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
  312. return nil, err
  313. }
  314. // Check attachments
  315. attachments := make([]*Attachment, 0, len(opts.Attachments))
  316. for _, uuid := range opts.Attachments {
  317. attach, err := getAttachmentByUUID(e, uuid)
  318. if err != nil {
  319. if IsErrAttachmentNotExist(err) {
  320. continue
  321. }
  322. return nil, fmt.Errorf("getAttachmentByUUID [%s]: %v", uuid, err)
  323. }
  324. attachments = append(attachments, attach)
  325. }
  326. for i := range attachments {
  327. attachments[i].IssueID = opts.Issue.ID
  328. attachments[i].CommentID = comment.ID
  329. // No assign value could be 0, so ignore AllCols().
  330. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  331. return nil, fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  332. }
  333. }
  334. case CommentTypeReopen:
  335. act.OpType = ActionReopenIssue
  336. if opts.Issue.IsPull {
  337. act.OpType = ActionReopenPullRequest
  338. }
  339. if opts.Issue.IsPull {
  340. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls-1 WHERE id=?", opts.Repo.ID)
  341. } else {
  342. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", opts.Repo.ID)
  343. }
  344. if err != nil {
  345. return nil, err
  346. }
  347. case CommentTypeClose:
  348. act.OpType = ActionCloseIssue
  349. if opts.Issue.IsPull {
  350. act.OpType = ActionClosePullRequest
  351. }
  352. if opts.Issue.IsPull {
  353. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls+1 WHERE id=?", opts.Repo.ID)
  354. } else {
  355. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", opts.Repo.ID)
  356. }
  357. if err != nil {
  358. return nil, err
  359. }
  360. }
  361. // update the issue's updated_unix column
  362. if err = updateIssueCols(e, opts.Issue); err != nil {
  363. return nil, err
  364. }
  365. // Notify watchers for whatever action comes in, ignore if no action type.
  366. if act.OpType > 0 {
  367. if err = notifyWatchers(e, act); err != nil {
  368. log.Error(4, "notifyWatchers: %v", err)
  369. }
  370. if err = comment.MailParticipants(e, act.OpType, opts.Issue); err != nil {
  371. log.Error(4, "MailParticipants: %v", err)
  372. }
  373. }
  374. return comment, nil
  375. }
  376. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  377. cmtType := CommentTypeClose
  378. if !issue.IsClosed {
  379. cmtType = CommentTypeReopen
  380. }
  381. return createComment(e, &CreateCommentOptions{
  382. Type: cmtType,
  383. Doer: doer,
  384. Repo: repo,
  385. Issue: issue,
  386. })
  387. }
  388. func createLabelComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, label *Label, add bool) (*Comment, error) {
  389. var content string
  390. if add {
  391. content = "1"
  392. }
  393. return createComment(e, &CreateCommentOptions{
  394. Type: CommentTypeLabel,
  395. Doer: doer,
  396. Repo: repo,
  397. Issue: issue,
  398. Label: label,
  399. Content: content,
  400. })
  401. }
  402. func createMilestoneComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldMilestoneID, milestoneID int64) (*Comment, error) {
  403. return createComment(e, &CreateCommentOptions{
  404. Type: CommentTypeMilestone,
  405. Doer: doer,
  406. Repo: repo,
  407. Issue: issue,
  408. OldMilestoneID: oldMilestoneID,
  409. MilestoneID: milestoneID,
  410. })
  411. }
  412. func createAssigneeComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldAssigneeID, assigneeID int64) (*Comment, error) {
  413. return createComment(e, &CreateCommentOptions{
  414. Type: CommentTypeAssignees,
  415. Doer: doer,
  416. Repo: repo,
  417. Issue: issue,
  418. OldAssigneeID: oldAssigneeID,
  419. AssigneeID: assigneeID,
  420. })
  421. }
  422. func createChangeTitleComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldTitle, newTitle string) (*Comment, error) {
  423. return createComment(e, &CreateCommentOptions{
  424. Type: CommentTypeChangeTitle,
  425. Doer: doer,
  426. Repo: repo,
  427. Issue: issue,
  428. OldTitle: oldTitle,
  429. NewTitle: newTitle,
  430. })
  431. }
  432. func createDeleteBranchComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, branchName string) (*Comment, error) {
  433. return createComment(e, &CreateCommentOptions{
  434. Type: CommentTypeDeleteBranch,
  435. Doer: doer,
  436. Repo: repo,
  437. Issue: issue,
  438. CommitSHA: branchName,
  439. })
  440. }
  441. // CreateCommentOptions defines options for creating comment
  442. type CreateCommentOptions struct {
  443. Type CommentType
  444. Doer *User
  445. Repo *Repository
  446. Issue *Issue
  447. Label *Label
  448. OldMilestoneID int64
  449. MilestoneID int64
  450. OldAssigneeID int64
  451. AssigneeID int64
  452. OldTitle string
  453. NewTitle string
  454. CommitID int64
  455. CommitSHA string
  456. LineNum int64
  457. Content string
  458. Attachments []string // UUIDs of attachments
  459. }
  460. // CreateComment creates comment of issue or commit.
  461. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
  462. sess := x.NewSession()
  463. defer sess.Close()
  464. if err = sess.Begin(); err != nil {
  465. return nil, err
  466. }
  467. comment, err = createComment(sess, opts)
  468. if err != nil {
  469. return nil, err
  470. }
  471. if err = sess.Commit(); err != nil {
  472. return nil, err
  473. }
  474. if opts.Type == CommentTypeComment {
  475. UpdateIssueIndexer(opts.Issue.ID)
  476. }
  477. return comment, nil
  478. }
  479. // CreateIssueComment creates a plain issue comment.
  480. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  481. return CreateComment(&CreateCommentOptions{
  482. Type: CommentTypeComment,
  483. Doer: doer,
  484. Repo: repo,
  485. Issue: issue,
  486. Content: content,
  487. Attachments: attachments,
  488. })
  489. }
  490. // CreateRefComment creates a commit reference comment to issue.
  491. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  492. if len(commitSHA) == 0 {
  493. return fmt.Errorf("cannot create reference with empty commit SHA")
  494. }
  495. // Check if same reference from same commit has already existed.
  496. has, err := x.Get(&Comment{
  497. Type: CommentTypeCommitRef,
  498. IssueID: issue.ID,
  499. CommitSHA: commitSHA,
  500. })
  501. if err != nil {
  502. return fmt.Errorf("check reference comment: %v", err)
  503. } else if has {
  504. return nil
  505. }
  506. _, err = CreateComment(&CreateCommentOptions{
  507. Type: CommentTypeCommitRef,
  508. Doer: doer,
  509. Repo: repo,
  510. Issue: issue,
  511. CommitSHA: commitSHA,
  512. Content: content,
  513. })
  514. return err
  515. }
  516. // GetCommentByID returns the comment by given ID.
  517. func GetCommentByID(id int64) (*Comment, error) {
  518. c := new(Comment)
  519. has, err := x.ID(id).Get(c)
  520. if err != nil {
  521. return nil, err
  522. } else if !has {
  523. return nil, ErrCommentNotExist{id, 0}
  524. }
  525. return c, nil
  526. }
  527. // FindCommentsOptions describes the conditions to Find comments
  528. type FindCommentsOptions struct {
  529. RepoID int64
  530. IssueID int64
  531. Since int64
  532. Type CommentType
  533. }
  534. func (opts *FindCommentsOptions) toConds() builder.Cond {
  535. var cond = builder.NewCond()
  536. if opts.RepoID > 0 {
  537. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  538. }
  539. if opts.IssueID > 0 {
  540. cond = cond.And(builder.Eq{"comment.issue_id": opts.IssueID})
  541. }
  542. if opts.Since > 0 {
  543. cond = cond.And(builder.Gte{"comment.updated_unix": opts.Since})
  544. }
  545. if opts.Type != CommentTypeUnknown {
  546. cond = cond.And(builder.Eq{"comment.type": opts.Type})
  547. }
  548. return cond
  549. }
  550. func findComments(e Engine, opts FindCommentsOptions) ([]*Comment, error) {
  551. comments := make([]*Comment, 0, 10)
  552. sess := e.Where(opts.toConds())
  553. if opts.RepoID > 0 {
  554. sess.Join("INNER", "issue", "issue.id = comment.issue_id")
  555. }
  556. return comments, sess.
  557. Asc("comment.created_unix").
  558. Asc("comment.id").
  559. Find(&comments)
  560. }
  561. // FindComments returns all comments according options
  562. func FindComments(opts FindCommentsOptions) ([]*Comment, error) {
  563. return findComments(x, opts)
  564. }
  565. // GetCommentsByIssueID returns all comments of an issue.
  566. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  567. return findComments(x, FindCommentsOptions{
  568. IssueID: issueID,
  569. Type: CommentTypeUnknown,
  570. })
  571. }
  572. // GetCommentsByIssueIDSince returns a list of comments of an issue since a given time point.
  573. func GetCommentsByIssueIDSince(issueID, since int64) ([]*Comment, error) {
  574. return findComments(x, FindCommentsOptions{
  575. IssueID: issueID,
  576. Type: CommentTypeUnknown,
  577. Since: since,
  578. })
  579. }
  580. // GetCommentsByRepoIDSince returns a list of comments for all issues in a repo since a given time point.
  581. func GetCommentsByRepoIDSince(repoID, since int64) ([]*Comment, error) {
  582. return findComments(x, FindCommentsOptions{
  583. RepoID: repoID,
  584. Type: CommentTypeUnknown,
  585. Since: since,
  586. })
  587. }
  588. // UpdateComment updates information of comment.
  589. func UpdateComment(c *Comment) error {
  590. if _, err := x.ID(c.ID).AllCols().Update(c); err != nil {
  591. return err
  592. } else if c.Type == CommentTypeComment {
  593. UpdateIssueIndexer(c.IssueID)
  594. }
  595. return nil
  596. }
  597. // DeleteComment deletes the comment
  598. func DeleteComment(comment *Comment) error {
  599. sess := x.NewSession()
  600. defer sess.Close()
  601. if err := sess.Begin(); err != nil {
  602. return err
  603. }
  604. if _, err := sess.Delete(&Comment{
  605. ID: comment.ID,
  606. }); err != nil {
  607. return err
  608. }
  609. if comment.Type == CommentTypeComment {
  610. if _, err := sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  611. return err
  612. }
  613. }
  614. if _, err := sess.Where("comment_id = ?", comment.ID).Cols("is_deleted").Update(&Action{IsDeleted: true}); err != nil {
  615. return err
  616. }
  617. if err := sess.Commit(); err != nil {
  618. return err
  619. } else if comment.Type == CommentTypeComment {
  620. UpdateIssueIndexer(comment.IssueID)
  621. }
  622. return nil
  623. }