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.

688 lines
18 KiB

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
  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "fmt"
  7. "strings"
  8. "time"
  9. "github.com/Unknwon/com"
  10. "github.com/go-xorm/builder"
  11. "github.com/go-xorm/xorm"
  12. api "code.gitea.io/sdk/gitea"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/markup"
  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. Created time.Time `xorm:"-"`
  88. CreatedUnix int64 `xorm:"INDEX created"`
  89. Updated time.Time `xorm:"-"`
  90. UpdatedUnix int64 `xorm:"INDEX updated"`
  91. // Reference issue in commit message
  92. CommitSHA string `xorm:"VARCHAR(40)"`
  93. Attachments []*Attachment `xorm:"-"`
  94. // For view issue page.
  95. ShowTag CommentTag `xorm:"-"`
  96. }
  97. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  98. func (c *Comment) AfterLoad(session *xorm.Session) {
  99. c.Created = time.Unix(c.CreatedUnix, 0).Local()
  100. c.Updated = time.Unix(c.UpdatedUnix, 0).Local()
  101. var err error
  102. c.Attachments, err = getAttachmentsByCommentID(session, c.ID)
  103. if err != nil {
  104. log.Error(3, "getAttachmentsByCommentID[%d]: %v", c.ID, err)
  105. }
  106. c.Poster, err = getUserByID(session, c.PosterID)
  107. if err != nil {
  108. if IsErrUserNotExist(err) {
  109. c.PosterID = -1
  110. c.Poster = NewGhostUser()
  111. } else {
  112. log.Error(3, "getUserByID[%d]: %v", c.ID, err)
  113. }
  114. }
  115. }
  116. // AfterDelete is invoked from XORM after the object is deleted.
  117. func (c *Comment) AfterDelete() {
  118. _, err := DeleteAttachmentsByComment(c.ID, true)
  119. if err != nil {
  120. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  121. }
  122. }
  123. // HTMLURL formats a URL-string to the issue-comment
  124. func (c *Comment) HTMLURL() string {
  125. issue, err := GetIssueByID(c.IssueID)
  126. if err != nil { // Silently dropping errors :unamused:
  127. log.Error(4, "GetIssueByID(%d): %v", c.IssueID, err)
  128. return ""
  129. }
  130. return fmt.Sprintf("%s#%s", issue.HTMLURL(), c.HashTag())
  131. }
  132. // IssueURL formats a URL-string to the issue
  133. func (c *Comment) IssueURL() string {
  134. issue, err := GetIssueByID(c.IssueID)
  135. if err != nil { // Silently dropping errors :unamused:
  136. log.Error(4, "GetIssueByID(%d): %v", c.IssueID, err)
  137. return ""
  138. }
  139. if issue.IsPull {
  140. return ""
  141. }
  142. return issue.HTMLURL()
  143. }
  144. // PRURL formats a URL-string to the pull-request
  145. func (c *Comment) PRURL() string {
  146. issue, err := GetIssueByID(c.IssueID)
  147. if err != nil { // Silently dropping errors :unamused:
  148. log.Error(4, "GetIssueByID(%d): %v", c.IssueID, err)
  149. return ""
  150. }
  151. if !issue.IsPull {
  152. return ""
  153. }
  154. return issue.HTMLURL()
  155. }
  156. // APIFormat converts a Comment to the api.Comment format
  157. func (c *Comment) APIFormat() *api.Comment {
  158. return &api.Comment{
  159. ID: c.ID,
  160. Poster: c.Poster.APIFormat(),
  161. HTMLURL: c.HTMLURL(),
  162. IssueURL: c.IssueURL(),
  163. PRURL: c.PRURL(),
  164. Body: c.Content,
  165. Created: c.Created,
  166. Updated: c.Updated,
  167. }
  168. }
  169. // HashTag returns unique hash tag for comment.
  170. func (c *Comment) HashTag() string {
  171. return "issuecomment-" + com.ToStr(c.ID)
  172. }
  173. // EventTag returns unique event hash tag for comment.
  174. func (c *Comment) EventTag() string {
  175. return "event-" + com.ToStr(c.ID)
  176. }
  177. // LoadLabel if comment.Type is CommentTypeLabel, then load Label
  178. func (c *Comment) LoadLabel() error {
  179. var label Label
  180. has, err := x.ID(c.LabelID).Get(&label)
  181. if err != nil {
  182. return err
  183. } else if has {
  184. c.Label = &label
  185. } else {
  186. // Ignore Label is deleted, but not clear this table
  187. log.Warn("Commit %d cannot load label %d", c.ID, c.LabelID)
  188. }
  189. return nil
  190. }
  191. // LoadMilestone if comment.Type is CommentTypeMilestone, then load milestone
  192. func (c *Comment) LoadMilestone() error {
  193. if c.OldMilestoneID > 0 {
  194. var oldMilestone Milestone
  195. has, err := x.ID(c.OldMilestoneID).Get(&oldMilestone)
  196. if err != nil {
  197. return err
  198. } else if has {
  199. c.OldMilestone = &oldMilestone
  200. }
  201. }
  202. if c.MilestoneID > 0 {
  203. var milestone Milestone
  204. has, err := x.ID(c.MilestoneID).Get(&milestone)
  205. if err != nil {
  206. return err
  207. } else if has {
  208. c.Milestone = &milestone
  209. }
  210. }
  211. return nil
  212. }
  213. // LoadAssignees if comment.Type is CommentTypeAssignees, then load assignees
  214. func (c *Comment) LoadAssignees() error {
  215. var err error
  216. if c.OldAssigneeID > 0 {
  217. c.OldAssignee, err = getUserByID(x, c.OldAssigneeID)
  218. if err != nil {
  219. return err
  220. }
  221. }
  222. if c.AssigneeID > 0 {
  223. c.Assignee, err = getUserByID(x, c.AssigneeID)
  224. if err != nil {
  225. return err
  226. }
  227. }
  228. return nil
  229. }
  230. // MailParticipants sends new comment emails to repository watchers
  231. // and mentioned people.
  232. func (c *Comment) MailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
  233. mentions := markup.FindAllMentions(c.Content)
  234. if err = UpdateIssueMentions(e, c.IssueID, mentions); err != nil {
  235. return fmt.Errorf("UpdateIssueMentions [%d]: %v", c.IssueID, err)
  236. }
  237. content := c.Content
  238. switch opType {
  239. case ActionCloseIssue:
  240. content = fmt.Sprintf("Closed #%d", issue.Index)
  241. case ActionReopenIssue:
  242. content = fmt.Sprintf("Reopened #%d", issue.Index)
  243. }
  244. if err = mailIssueCommentToParticipants(e, issue, c.Poster, content, c, mentions); err != nil {
  245. log.Error(4, "mailIssueCommentToParticipants: %v", err)
  246. }
  247. return nil
  248. }
  249. func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err error) {
  250. var LabelID int64
  251. if opts.Label != nil {
  252. LabelID = opts.Label.ID
  253. }
  254. comment := &Comment{
  255. Type: opts.Type,
  256. PosterID: opts.Doer.ID,
  257. Poster: opts.Doer,
  258. IssueID: opts.Issue.ID,
  259. LabelID: LabelID,
  260. OldMilestoneID: opts.OldMilestoneID,
  261. MilestoneID: opts.MilestoneID,
  262. OldAssigneeID: opts.OldAssigneeID,
  263. AssigneeID: opts.AssigneeID,
  264. CommitID: opts.CommitID,
  265. CommitSHA: opts.CommitSHA,
  266. Line: opts.LineNum,
  267. Content: opts.Content,
  268. OldTitle: opts.OldTitle,
  269. NewTitle: opts.NewTitle,
  270. }
  271. if _, err = e.Insert(comment); err != nil {
  272. return nil, err
  273. }
  274. if err = opts.Repo.getOwner(e); err != nil {
  275. return nil, err
  276. }
  277. // Compose comment action, could be plain comment, close or reopen issue/pull request.
  278. // This object will be used to notify watchers in the end of function.
  279. act := &Action{
  280. ActUserID: opts.Doer.ID,
  281. ActUser: opts.Doer,
  282. Content: fmt.Sprintf("%d|%s", opts.Issue.Index, strings.Split(opts.Content, "\n")[0]),
  283. RepoID: opts.Repo.ID,
  284. Repo: opts.Repo,
  285. Comment: comment,
  286. CommentID: comment.ID,
  287. IsPrivate: opts.Repo.IsPrivate,
  288. }
  289. // Check comment type.
  290. switch opts.Type {
  291. case CommentTypeComment:
  292. act.OpType = ActionCommentIssue
  293. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
  294. return nil, err
  295. }
  296. // Check attachments
  297. attachments := make([]*Attachment, 0, len(opts.Attachments))
  298. for _, uuid := range opts.Attachments {
  299. attach, err := getAttachmentByUUID(e, uuid)
  300. if err != nil {
  301. if IsErrAttachmentNotExist(err) {
  302. continue
  303. }
  304. return nil, fmt.Errorf("getAttachmentByUUID [%s]: %v", uuid, err)
  305. }
  306. attachments = append(attachments, attach)
  307. }
  308. for i := range attachments {
  309. attachments[i].IssueID = opts.Issue.ID
  310. attachments[i].CommentID = comment.ID
  311. // No assign value could be 0, so ignore AllCols().
  312. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  313. return nil, fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  314. }
  315. }
  316. case CommentTypeReopen:
  317. act.OpType = ActionReopenIssue
  318. if opts.Issue.IsPull {
  319. act.OpType = ActionReopenPullRequest
  320. }
  321. if opts.Issue.IsPull {
  322. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls-1 WHERE id=?", opts.Repo.ID)
  323. } else {
  324. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", opts.Repo.ID)
  325. }
  326. if err != nil {
  327. return nil, err
  328. }
  329. case CommentTypeClose:
  330. act.OpType = ActionCloseIssue
  331. if opts.Issue.IsPull {
  332. act.OpType = ActionClosePullRequest
  333. }
  334. if opts.Issue.IsPull {
  335. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls+1 WHERE id=?", opts.Repo.ID)
  336. } else {
  337. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", opts.Repo.ID)
  338. }
  339. if err != nil {
  340. return nil, err
  341. }
  342. }
  343. // update the issue's updated_unix column
  344. if err = updateIssueCols(e, opts.Issue); err != nil {
  345. return nil, err
  346. }
  347. // Notify watchers for whatever action comes in, ignore if no action type.
  348. if act.OpType > 0 {
  349. if err = notifyWatchers(e, act); err != nil {
  350. log.Error(4, "notifyWatchers: %v", err)
  351. }
  352. if err = comment.MailParticipants(e, act.OpType, opts.Issue); err != nil {
  353. log.Error(4, "MailParticipants: %v", err)
  354. }
  355. }
  356. return comment, nil
  357. }
  358. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  359. cmtType := CommentTypeClose
  360. if !issue.IsClosed {
  361. cmtType = CommentTypeReopen
  362. }
  363. return createComment(e, &CreateCommentOptions{
  364. Type: cmtType,
  365. Doer: doer,
  366. Repo: repo,
  367. Issue: issue,
  368. })
  369. }
  370. func createLabelComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, label *Label, add bool) (*Comment, error) {
  371. var content string
  372. if add {
  373. content = "1"
  374. }
  375. return createComment(e, &CreateCommentOptions{
  376. Type: CommentTypeLabel,
  377. Doer: doer,
  378. Repo: repo,
  379. Issue: issue,
  380. Label: label,
  381. Content: content,
  382. })
  383. }
  384. func createMilestoneComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldMilestoneID, milestoneID int64) (*Comment, error) {
  385. return createComment(e, &CreateCommentOptions{
  386. Type: CommentTypeMilestone,
  387. Doer: doer,
  388. Repo: repo,
  389. Issue: issue,
  390. OldMilestoneID: oldMilestoneID,
  391. MilestoneID: milestoneID,
  392. })
  393. }
  394. func createAssigneeComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldAssigneeID, assigneeID int64) (*Comment, error) {
  395. return createComment(e, &CreateCommentOptions{
  396. Type: CommentTypeAssignees,
  397. Doer: doer,
  398. Repo: repo,
  399. Issue: issue,
  400. OldAssigneeID: oldAssigneeID,
  401. AssigneeID: assigneeID,
  402. })
  403. }
  404. func createChangeTitleComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldTitle, newTitle string) (*Comment, error) {
  405. return createComment(e, &CreateCommentOptions{
  406. Type: CommentTypeChangeTitle,
  407. Doer: doer,
  408. Repo: repo,
  409. Issue: issue,
  410. OldTitle: oldTitle,
  411. NewTitle: newTitle,
  412. })
  413. }
  414. func createDeleteBranchComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, branchName string) (*Comment, error) {
  415. return createComment(e, &CreateCommentOptions{
  416. Type: CommentTypeDeleteBranch,
  417. Doer: doer,
  418. Repo: repo,
  419. Issue: issue,
  420. CommitSHA: branchName,
  421. })
  422. }
  423. // CreateCommentOptions defines options for creating comment
  424. type CreateCommentOptions struct {
  425. Type CommentType
  426. Doer *User
  427. Repo *Repository
  428. Issue *Issue
  429. Label *Label
  430. OldMilestoneID int64
  431. MilestoneID int64
  432. OldAssigneeID int64
  433. AssigneeID int64
  434. OldTitle string
  435. NewTitle string
  436. CommitID int64
  437. CommitSHA string
  438. LineNum int64
  439. Content string
  440. Attachments []string // UUIDs of attachments
  441. }
  442. // CreateComment creates comment of issue or commit.
  443. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
  444. sess := x.NewSession()
  445. defer sess.Close()
  446. if err = sess.Begin(); err != nil {
  447. return nil, err
  448. }
  449. comment, err = createComment(sess, opts)
  450. if err != nil {
  451. return nil, err
  452. }
  453. if err = sess.Commit(); err != nil {
  454. return nil, err
  455. }
  456. if opts.Type == CommentTypeComment {
  457. UpdateIssueIndexer(opts.Issue.ID)
  458. }
  459. return comment, nil
  460. }
  461. // CreateIssueComment creates a plain issue comment.
  462. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  463. return CreateComment(&CreateCommentOptions{
  464. Type: CommentTypeComment,
  465. Doer: doer,
  466. Repo: repo,
  467. Issue: issue,
  468. Content: content,
  469. Attachments: attachments,
  470. })
  471. }
  472. // CreateRefComment creates a commit reference comment to issue.
  473. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  474. if len(commitSHA) == 0 {
  475. return fmt.Errorf("cannot create reference with empty commit SHA")
  476. }
  477. // Check if same reference from same commit has already existed.
  478. has, err := x.Get(&Comment{
  479. Type: CommentTypeCommitRef,
  480. IssueID: issue.ID,
  481. CommitSHA: commitSHA,
  482. })
  483. if err != nil {
  484. return fmt.Errorf("check reference comment: %v", err)
  485. } else if has {
  486. return nil
  487. }
  488. _, err = CreateComment(&CreateCommentOptions{
  489. Type: CommentTypeCommitRef,
  490. Doer: doer,
  491. Repo: repo,
  492. Issue: issue,
  493. CommitSHA: commitSHA,
  494. Content: content,
  495. })
  496. return err
  497. }
  498. // GetCommentByID returns the comment by given ID.
  499. func GetCommentByID(id int64) (*Comment, error) {
  500. c := new(Comment)
  501. has, err := x.ID(id).Get(c)
  502. if err != nil {
  503. return nil, err
  504. } else if !has {
  505. return nil, ErrCommentNotExist{id, 0}
  506. }
  507. return c, nil
  508. }
  509. // FindCommentsOptions describes the conditions to Find comments
  510. type FindCommentsOptions struct {
  511. RepoID int64
  512. IssueID int64
  513. Since int64
  514. Type CommentType
  515. }
  516. func (opts *FindCommentsOptions) toConds() builder.Cond {
  517. var cond = builder.NewCond()
  518. if opts.RepoID > 0 {
  519. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  520. }
  521. if opts.IssueID > 0 {
  522. cond = cond.And(builder.Eq{"comment.issue_id": opts.IssueID})
  523. }
  524. if opts.Since > 0 {
  525. cond = cond.And(builder.Gte{"comment.updated_unix": opts.Since})
  526. }
  527. if opts.Type != CommentTypeUnknown {
  528. cond = cond.And(builder.Eq{"comment.type": opts.Type})
  529. }
  530. return cond
  531. }
  532. func findComments(e Engine, opts FindCommentsOptions) ([]*Comment, error) {
  533. comments := make([]*Comment, 0, 10)
  534. sess := e.Where(opts.toConds())
  535. if opts.RepoID > 0 {
  536. sess.Join("INNER", "issue", "issue.id = comment.issue_id")
  537. }
  538. return comments, sess.
  539. Asc("comment.created_unix").
  540. Asc("comment.id").
  541. Find(&comments)
  542. }
  543. // FindComments returns all comments according options
  544. func FindComments(opts FindCommentsOptions) ([]*Comment, error) {
  545. return findComments(x, opts)
  546. }
  547. // GetCommentsByIssueID returns all comments of an issue.
  548. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  549. return findComments(x, FindCommentsOptions{
  550. IssueID: issueID,
  551. Type: CommentTypeUnknown,
  552. })
  553. }
  554. // GetCommentsByIssueIDSince returns a list of comments of an issue since a given time point.
  555. func GetCommentsByIssueIDSince(issueID, since int64) ([]*Comment, error) {
  556. return findComments(x, FindCommentsOptions{
  557. IssueID: issueID,
  558. Type: CommentTypeUnknown,
  559. Since: since,
  560. })
  561. }
  562. // GetCommentsByRepoIDSince returns a list of comments for all issues in a repo since a given time point.
  563. func GetCommentsByRepoIDSince(repoID, since int64) ([]*Comment, error) {
  564. return findComments(x, FindCommentsOptions{
  565. RepoID: repoID,
  566. Type: CommentTypeUnknown,
  567. Since: since,
  568. })
  569. }
  570. // UpdateComment updates information of comment.
  571. func UpdateComment(c *Comment) error {
  572. if _, err := x.ID(c.ID).AllCols().Update(c); err != nil {
  573. return err
  574. } else if c.Type == CommentTypeComment {
  575. UpdateIssueIndexer(c.IssueID)
  576. }
  577. return nil
  578. }
  579. // DeleteComment deletes the comment
  580. func DeleteComment(comment *Comment) error {
  581. sess := x.NewSession()
  582. defer sess.Close()
  583. if err := sess.Begin(); err != nil {
  584. return err
  585. }
  586. if _, err := sess.Delete(&Comment{
  587. ID: comment.ID,
  588. }); err != nil {
  589. return err
  590. }
  591. if comment.Type == CommentTypeComment {
  592. if _, err := sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  593. return err
  594. }
  595. }
  596. if _, err := sess.Where("comment_id = ?", comment.ID).Cols("is_deleted").Update(&Action{IsDeleted: true}); err != nil {
  597. return err
  598. }
  599. if err := sess.Commit(); err != nil {
  600. return err
  601. } else if comment.Type == CommentTypeComment {
  602. UpdateIssueIndexer(comment.IssueID)
  603. }
  604. return nil
  605. }