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 19 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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. if !IsErrUserNotExist(err) {
  217. return err
  218. }
  219. c.OldAssignee = NewGhostUser()
  220. }
  221. }
  222. if c.AssigneeID > 0 {
  223. c.Assignee, err = getUserByID(x, c.AssigneeID)
  224. if err != nil {
  225. if !IsErrUserNotExist(err) {
  226. return err
  227. }
  228. c.Assignee = NewGhostUser()
  229. }
  230. }
  231. return nil
  232. }
  233. // MailParticipants sends new comment emails to repository watchers
  234. // and mentioned people.
  235. func (c *Comment) MailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
  236. mentions := markup.FindAllMentions(c.Content)
  237. if err = UpdateIssueMentions(e, c.IssueID, mentions); err != nil {
  238. return fmt.Errorf("UpdateIssueMentions [%d]: %v", c.IssueID, err)
  239. }
  240. content := c.Content
  241. switch opType {
  242. case ActionCloseIssue:
  243. content = fmt.Sprintf("Closed #%d", issue.Index)
  244. case ActionReopenIssue:
  245. content = fmt.Sprintf("Reopened #%d", issue.Index)
  246. }
  247. if err = mailIssueCommentToParticipants(e, issue, c.Poster, content, c, mentions); err != nil {
  248. log.Error(4, "mailIssueCommentToParticipants: %v", err)
  249. }
  250. return nil
  251. }
  252. func (c *Comment) loadReactions(e Engine) (err error) {
  253. if c.Reactions != nil {
  254. return nil
  255. }
  256. c.Reactions, err = findReactions(e, FindReactionsOptions{
  257. IssueID: c.IssueID,
  258. CommentID: c.ID,
  259. })
  260. if err != nil {
  261. return err
  262. }
  263. // Load reaction user data
  264. if _, err := c.Reactions.LoadUsers(); err != nil {
  265. return err
  266. }
  267. return nil
  268. }
  269. // LoadReactions loads comment reactions
  270. func (c *Comment) LoadReactions() error {
  271. return c.loadReactions(x)
  272. }
  273. func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err error) {
  274. var LabelID int64
  275. if opts.Label != nil {
  276. LabelID = opts.Label.ID
  277. }
  278. comment := &Comment{
  279. Type: opts.Type,
  280. PosterID: opts.Doer.ID,
  281. Poster: opts.Doer,
  282. IssueID: opts.Issue.ID,
  283. LabelID: LabelID,
  284. OldMilestoneID: opts.OldMilestoneID,
  285. MilestoneID: opts.MilestoneID,
  286. OldAssigneeID: opts.OldAssigneeID,
  287. AssigneeID: opts.AssigneeID,
  288. CommitID: opts.CommitID,
  289. CommitSHA: opts.CommitSHA,
  290. Line: opts.LineNum,
  291. Content: opts.Content,
  292. OldTitle: opts.OldTitle,
  293. NewTitle: opts.NewTitle,
  294. }
  295. if _, err = e.Insert(comment); err != nil {
  296. return nil, err
  297. }
  298. if err = opts.Repo.getOwner(e); err != nil {
  299. return nil, err
  300. }
  301. // Compose comment action, could be plain comment, close or reopen issue/pull request.
  302. // This object will be used to notify watchers in the end of function.
  303. act := &Action{
  304. ActUserID: opts.Doer.ID,
  305. ActUser: opts.Doer,
  306. Content: fmt.Sprintf("%d|%s", opts.Issue.Index, strings.Split(opts.Content, "\n")[0]),
  307. RepoID: opts.Repo.ID,
  308. Repo: opts.Repo,
  309. Comment: comment,
  310. CommentID: comment.ID,
  311. IsPrivate: opts.Repo.IsPrivate,
  312. }
  313. // Check comment type.
  314. switch opts.Type {
  315. case CommentTypeComment:
  316. act.OpType = ActionCommentIssue
  317. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
  318. return nil, err
  319. }
  320. // Check attachments
  321. attachments := make([]*Attachment, 0, len(opts.Attachments))
  322. for _, uuid := range opts.Attachments {
  323. attach, err := getAttachmentByUUID(e, uuid)
  324. if err != nil {
  325. if IsErrAttachmentNotExist(err) {
  326. continue
  327. }
  328. return nil, fmt.Errorf("getAttachmentByUUID [%s]: %v", uuid, err)
  329. }
  330. attachments = append(attachments, attach)
  331. }
  332. for i := range attachments {
  333. attachments[i].IssueID = opts.Issue.ID
  334. attachments[i].CommentID = comment.ID
  335. // No assign value could be 0, so ignore AllCols().
  336. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  337. return nil, fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  338. }
  339. }
  340. case CommentTypeReopen:
  341. act.OpType = ActionReopenIssue
  342. if opts.Issue.IsPull {
  343. act.OpType = ActionReopenPullRequest
  344. }
  345. if opts.Issue.IsPull {
  346. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls-1 WHERE id=?", opts.Repo.ID)
  347. } else {
  348. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", opts.Repo.ID)
  349. }
  350. if err != nil {
  351. return nil, err
  352. }
  353. case CommentTypeClose:
  354. act.OpType = ActionCloseIssue
  355. if opts.Issue.IsPull {
  356. act.OpType = ActionClosePullRequest
  357. }
  358. if opts.Issue.IsPull {
  359. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls+1 WHERE id=?", opts.Repo.ID)
  360. } else {
  361. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", opts.Repo.ID)
  362. }
  363. if err != nil {
  364. return nil, err
  365. }
  366. }
  367. // update the issue's updated_unix column
  368. if err = updateIssueCols(e, opts.Issue); err != nil {
  369. return nil, err
  370. }
  371. // Notify watchers for whatever action comes in, ignore if no action type.
  372. if act.OpType > 0 {
  373. if err = notifyWatchers(e, act); err != nil {
  374. log.Error(4, "notifyWatchers: %v", err)
  375. }
  376. if err = comment.MailParticipants(e, act.OpType, opts.Issue); err != nil {
  377. log.Error(4, "MailParticipants: %v", err)
  378. }
  379. }
  380. return comment, nil
  381. }
  382. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  383. cmtType := CommentTypeClose
  384. if !issue.IsClosed {
  385. cmtType = CommentTypeReopen
  386. }
  387. return createComment(e, &CreateCommentOptions{
  388. Type: cmtType,
  389. Doer: doer,
  390. Repo: repo,
  391. Issue: issue,
  392. })
  393. }
  394. func createLabelComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, label *Label, add bool) (*Comment, error) {
  395. var content string
  396. if add {
  397. content = "1"
  398. }
  399. return createComment(e, &CreateCommentOptions{
  400. Type: CommentTypeLabel,
  401. Doer: doer,
  402. Repo: repo,
  403. Issue: issue,
  404. Label: label,
  405. Content: content,
  406. })
  407. }
  408. func createMilestoneComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldMilestoneID, milestoneID int64) (*Comment, error) {
  409. return createComment(e, &CreateCommentOptions{
  410. Type: CommentTypeMilestone,
  411. Doer: doer,
  412. Repo: repo,
  413. Issue: issue,
  414. OldMilestoneID: oldMilestoneID,
  415. MilestoneID: milestoneID,
  416. })
  417. }
  418. func createAssigneeComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldAssigneeID, assigneeID int64) (*Comment, error) {
  419. return createComment(e, &CreateCommentOptions{
  420. Type: CommentTypeAssignees,
  421. Doer: doer,
  422. Repo: repo,
  423. Issue: issue,
  424. OldAssigneeID: oldAssigneeID,
  425. AssigneeID: assigneeID,
  426. })
  427. }
  428. func createChangeTitleComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldTitle, newTitle string) (*Comment, error) {
  429. return createComment(e, &CreateCommentOptions{
  430. Type: CommentTypeChangeTitle,
  431. Doer: doer,
  432. Repo: repo,
  433. Issue: issue,
  434. OldTitle: oldTitle,
  435. NewTitle: newTitle,
  436. })
  437. }
  438. func createDeleteBranchComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, branchName string) (*Comment, error) {
  439. return createComment(e, &CreateCommentOptions{
  440. Type: CommentTypeDeleteBranch,
  441. Doer: doer,
  442. Repo: repo,
  443. Issue: issue,
  444. CommitSHA: branchName,
  445. })
  446. }
  447. // CreateCommentOptions defines options for creating comment
  448. type CreateCommentOptions struct {
  449. Type CommentType
  450. Doer *User
  451. Repo *Repository
  452. Issue *Issue
  453. Label *Label
  454. OldMilestoneID int64
  455. MilestoneID int64
  456. OldAssigneeID int64
  457. AssigneeID int64
  458. OldTitle string
  459. NewTitle string
  460. CommitID int64
  461. CommitSHA string
  462. LineNum int64
  463. Content string
  464. Attachments []string // UUIDs of attachments
  465. }
  466. // CreateComment creates comment of issue or commit.
  467. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
  468. sess := x.NewSession()
  469. defer sess.Close()
  470. if err = sess.Begin(); err != nil {
  471. return nil, err
  472. }
  473. comment, err = createComment(sess, opts)
  474. if err != nil {
  475. return nil, err
  476. }
  477. if err = sess.Commit(); err != nil {
  478. return nil, err
  479. }
  480. if opts.Type == CommentTypeComment {
  481. UpdateIssueIndexer(opts.Issue.ID)
  482. }
  483. return comment, nil
  484. }
  485. // CreateIssueComment creates a plain issue comment.
  486. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  487. return CreateComment(&CreateCommentOptions{
  488. Type: CommentTypeComment,
  489. Doer: doer,
  490. Repo: repo,
  491. Issue: issue,
  492. Content: content,
  493. Attachments: attachments,
  494. })
  495. }
  496. // CreateRefComment creates a commit reference comment to issue.
  497. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  498. if len(commitSHA) == 0 {
  499. return fmt.Errorf("cannot create reference with empty commit SHA")
  500. }
  501. // Check if same reference from same commit has already existed.
  502. has, err := x.Get(&Comment{
  503. Type: CommentTypeCommitRef,
  504. IssueID: issue.ID,
  505. CommitSHA: commitSHA,
  506. })
  507. if err != nil {
  508. return fmt.Errorf("check reference comment: %v", err)
  509. } else if has {
  510. return nil
  511. }
  512. _, err = CreateComment(&CreateCommentOptions{
  513. Type: CommentTypeCommitRef,
  514. Doer: doer,
  515. Repo: repo,
  516. Issue: issue,
  517. CommitSHA: commitSHA,
  518. Content: content,
  519. })
  520. return err
  521. }
  522. // GetCommentByID returns the comment by given ID.
  523. func GetCommentByID(id int64) (*Comment, error) {
  524. c := new(Comment)
  525. has, err := x.ID(id).Get(c)
  526. if err != nil {
  527. return nil, err
  528. } else if !has {
  529. return nil, ErrCommentNotExist{id, 0}
  530. }
  531. return c, nil
  532. }
  533. // FindCommentsOptions describes the conditions to Find comments
  534. type FindCommentsOptions struct {
  535. RepoID int64
  536. IssueID int64
  537. Since int64
  538. Type CommentType
  539. }
  540. func (opts *FindCommentsOptions) toConds() builder.Cond {
  541. var cond = builder.NewCond()
  542. if opts.RepoID > 0 {
  543. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  544. }
  545. if opts.IssueID > 0 {
  546. cond = cond.And(builder.Eq{"comment.issue_id": opts.IssueID})
  547. }
  548. if opts.Since > 0 {
  549. cond = cond.And(builder.Gte{"comment.updated_unix": opts.Since})
  550. }
  551. if opts.Type != CommentTypeUnknown {
  552. cond = cond.And(builder.Eq{"comment.type": opts.Type})
  553. }
  554. return cond
  555. }
  556. func findComments(e Engine, opts FindCommentsOptions) ([]*Comment, error) {
  557. comments := make([]*Comment, 0, 10)
  558. sess := e.Where(opts.toConds())
  559. if opts.RepoID > 0 {
  560. sess.Join("INNER", "issue", "issue.id = comment.issue_id")
  561. }
  562. return comments, sess.
  563. Asc("comment.created_unix").
  564. Asc("comment.id").
  565. Find(&comments)
  566. }
  567. // FindComments returns all comments according options
  568. func FindComments(opts FindCommentsOptions) ([]*Comment, error) {
  569. return findComments(x, opts)
  570. }
  571. // GetCommentsByIssueID returns all comments of an issue.
  572. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  573. return findComments(x, FindCommentsOptions{
  574. IssueID: issueID,
  575. Type: CommentTypeUnknown,
  576. })
  577. }
  578. // GetCommentsByIssueIDSince returns a list of comments of an issue since a given time point.
  579. func GetCommentsByIssueIDSince(issueID, since int64) ([]*Comment, error) {
  580. return findComments(x, FindCommentsOptions{
  581. IssueID: issueID,
  582. Type: CommentTypeUnknown,
  583. Since: since,
  584. })
  585. }
  586. // GetCommentsByRepoIDSince returns a list of comments for all issues in a repo since a given time point.
  587. func GetCommentsByRepoIDSince(repoID, since int64) ([]*Comment, error) {
  588. return findComments(x, FindCommentsOptions{
  589. RepoID: repoID,
  590. Type: CommentTypeUnknown,
  591. Since: since,
  592. })
  593. }
  594. // UpdateComment updates information of comment.
  595. func UpdateComment(c *Comment) error {
  596. if _, err := x.ID(c.ID).AllCols().Update(c); err != nil {
  597. return err
  598. } else if c.Type == CommentTypeComment {
  599. UpdateIssueIndexer(c.IssueID)
  600. }
  601. return nil
  602. }
  603. // DeleteComment deletes the comment
  604. func DeleteComment(comment *Comment) error {
  605. sess := x.NewSession()
  606. defer sess.Close()
  607. if err := sess.Begin(); err != nil {
  608. return err
  609. }
  610. if _, err := sess.Delete(&Comment{
  611. ID: comment.ID,
  612. }); err != nil {
  613. return err
  614. }
  615. if comment.Type == CommentTypeComment {
  616. if _, err := sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  617. return err
  618. }
  619. }
  620. if _, err := sess.Where("comment_id = ?", comment.ID).Cols("is_deleted").Update(&Action{IsDeleted: true}); err != nil {
  621. return err
  622. }
  623. if err := sess.Commit(); err != nil {
  624. return err
  625. } else if comment.Type == CommentTypeComment {
  626. UpdateIssueIndexer(comment.IssueID)
  627. }
  628. return nil
  629. }