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