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 20 kB

9 years ago
9 years ago
9 years ago
9 years ago
9 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>
8 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. // Added a due date
  55. CommentTypeAddedDeadline
  56. // Modified the due date
  57. CommentTypeModifiedDeadline
  58. // Removed a due date
  59. CommentTypeRemovedDeadline
  60. )
  61. // CommentTag defines comment tag type
  62. type CommentTag int
  63. // Enumerate all the comment tag types
  64. const (
  65. CommentTagNone CommentTag = iota
  66. CommentTagPoster
  67. CommentTagWriter
  68. CommentTagOwner
  69. )
  70. // Comment represents a comment in commit and issue page.
  71. type Comment struct {
  72. ID int64 `xorm:"pk autoincr"`
  73. Type CommentType
  74. PosterID int64 `xorm:"INDEX"`
  75. Poster *User `xorm:"-"`
  76. IssueID int64 `xorm:"INDEX"`
  77. LabelID int64
  78. Label *Label `xorm:"-"`
  79. OldMilestoneID int64
  80. MilestoneID int64
  81. OldMilestone *Milestone `xorm:"-"`
  82. Milestone *Milestone `xorm:"-"`
  83. AssigneeID int64
  84. RemovedAssignee bool
  85. Assignee *User `xorm:"-"`
  86. OldTitle string
  87. NewTitle string
  88. CommitID int64
  89. Line int64
  90. Content string `xorm:"TEXT"`
  91. RenderedContent string `xorm:"-"`
  92. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  93. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  94. // Reference issue in commit message
  95. CommitSHA string `xorm:"VARCHAR(40)"`
  96. Attachments []*Attachment `xorm:"-"`
  97. Reactions ReactionList `xorm:"-"`
  98. // For view issue page.
  99. ShowTag CommentTag `xorm:"-"`
  100. }
  101. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  102. func (c *Comment) AfterLoad(session *xorm.Session) {
  103. var err error
  104. c.Attachments, err = getAttachmentsByCommentID(session, c.ID)
  105. if err != nil {
  106. log.Error(3, "getAttachmentsByCommentID[%d]: %v", c.ID, err)
  107. }
  108. c.Poster, err = getUserByID(session, c.PosterID)
  109. if err != nil {
  110. if IsErrUserNotExist(err) {
  111. c.PosterID = -1
  112. c.Poster = NewGhostUser()
  113. } else {
  114. log.Error(3, "getUserByID[%d]: %v", c.ID, err)
  115. }
  116. }
  117. }
  118. // AfterDelete is invoked from XORM after the object is deleted.
  119. func (c *Comment) AfterDelete() {
  120. _, err := DeleteAttachmentsByComment(c.ID, true)
  121. if err != nil {
  122. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  123. }
  124. }
  125. // HTMLURL formats a URL-string to the issue-comment
  126. func (c *Comment) HTMLURL() string {
  127. issue, err := GetIssueByID(c.IssueID)
  128. if err != nil { // Silently dropping errors :unamused:
  129. log.Error(4, "GetIssueByID(%d): %v", c.IssueID, err)
  130. return ""
  131. }
  132. return fmt.Sprintf("%s#%s", issue.HTMLURL(), c.HashTag())
  133. }
  134. // IssueURL formats a URL-string to the issue
  135. func (c *Comment) IssueURL() string {
  136. issue, err := GetIssueByID(c.IssueID)
  137. if err != nil { // Silently dropping errors :unamused:
  138. log.Error(4, "GetIssueByID(%d): %v", c.IssueID, err)
  139. return ""
  140. }
  141. if issue.IsPull {
  142. return ""
  143. }
  144. return issue.HTMLURL()
  145. }
  146. // PRURL formats a URL-string to the pull-request
  147. func (c *Comment) PRURL() string {
  148. issue, err := GetIssueByID(c.IssueID)
  149. if err != nil { // Silently dropping errors :unamused:
  150. log.Error(4, "GetIssueByID(%d): %v", c.IssueID, err)
  151. return ""
  152. }
  153. if !issue.IsPull {
  154. return ""
  155. }
  156. return issue.HTMLURL()
  157. }
  158. // APIFormat converts a Comment to the api.Comment format
  159. func (c *Comment) APIFormat() *api.Comment {
  160. return &api.Comment{
  161. ID: c.ID,
  162. Poster: c.Poster.APIFormat(),
  163. HTMLURL: c.HTMLURL(),
  164. IssueURL: c.IssueURL(),
  165. PRURL: c.PRURL(),
  166. Body: c.Content,
  167. Created: c.CreatedUnix.AsTime(),
  168. Updated: c.UpdatedUnix.AsTime(),
  169. }
  170. }
  171. // HashTag returns unique hash tag for comment.
  172. func (c *Comment) HashTag() string {
  173. return "issuecomment-" + com.ToStr(c.ID)
  174. }
  175. // EventTag returns unique event hash tag for comment.
  176. func (c *Comment) EventTag() string {
  177. return "event-" + com.ToStr(c.ID)
  178. }
  179. // LoadLabel if comment.Type is CommentTypeLabel, then load Label
  180. func (c *Comment) LoadLabel() error {
  181. var label Label
  182. has, err := x.ID(c.LabelID).Get(&label)
  183. if err != nil {
  184. return err
  185. } else if has {
  186. c.Label = &label
  187. } else {
  188. // Ignore Label is deleted, but not clear this table
  189. log.Warn("Commit %d cannot load label %d", c.ID, c.LabelID)
  190. }
  191. return nil
  192. }
  193. // LoadMilestone if comment.Type is CommentTypeMilestone, then load milestone
  194. func (c *Comment) LoadMilestone() error {
  195. if c.OldMilestoneID > 0 {
  196. var oldMilestone Milestone
  197. has, err := x.ID(c.OldMilestoneID).Get(&oldMilestone)
  198. if err != nil {
  199. return err
  200. } else if has {
  201. c.OldMilestone = &oldMilestone
  202. }
  203. }
  204. if c.MilestoneID > 0 {
  205. var milestone Milestone
  206. has, err := x.ID(c.MilestoneID).Get(&milestone)
  207. if err != nil {
  208. return err
  209. } else if has {
  210. c.Milestone = &milestone
  211. }
  212. }
  213. return nil
  214. }
  215. // LoadAssigneeUser if comment.Type is CommentTypeAssignees, then load assignees
  216. func (c *Comment) LoadAssigneeUser() error {
  217. var err error
  218. if c.AssigneeID > 0 {
  219. c.Assignee, err = getUserByID(x, c.AssigneeID)
  220. if err != nil {
  221. if !IsErrUserNotExist(err) {
  222. return err
  223. }
  224. c.Assignee = NewGhostUser()
  225. }
  226. }
  227. return nil
  228. }
  229. // MailParticipants sends new comment emails to repository watchers
  230. // and mentioned people.
  231. func (c *Comment) MailParticipants(e Engine, opType ActionType, issue *Issue) (err error) {
  232. mentions := markup.FindAllMentions(c.Content)
  233. if err = UpdateIssueMentions(e, c.IssueID, mentions); err != nil {
  234. return fmt.Errorf("UpdateIssueMentions [%d]: %v", c.IssueID, err)
  235. }
  236. content := c.Content
  237. switch opType {
  238. case ActionCloseIssue:
  239. content = fmt.Sprintf("Closed #%d", issue.Index)
  240. case ActionReopenIssue:
  241. content = fmt.Sprintf("Reopened #%d", issue.Index)
  242. }
  243. if err = mailIssueCommentToParticipants(e, issue, c.Poster, content, c, mentions); err != nil {
  244. log.Error(4, "mailIssueCommentToParticipants: %v", err)
  245. }
  246. return nil
  247. }
  248. func (c *Comment) loadReactions(e Engine) (err error) {
  249. if c.Reactions != nil {
  250. return nil
  251. }
  252. c.Reactions, err = findReactions(e, FindReactionsOptions{
  253. IssueID: c.IssueID,
  254. CommentID: c.ID,
  255. })
  256. if err != nil {
  257. return err
  258. }
  259. // Load reaction user data
  260. if _, err := c.Reactions.LoadUsers(); err != nil {
  261. return err
  262. }
  263. return nil
  264. }
  265. // LoadReactions loads comment reactions
  266. func (c *Comment) LoadReactions() error {
  267. return c.loadReactions(x)
  268. }
  269. func createComment(e *xorm.Session, opts *CreateCommentOptions) (_ *Comment, err error) {
  270. var LabelID int64
  271. if opts.Label != nil {
  272. LabelID = opts.Label.ID
  273. }
  274. comment := &Comment{
  275. Type: opts.Type,
  276. PosterID: opts.Doer.ID,
  277. Poster: opts.Doer,
  278. IssueID: opts.Issue.ID,
  279. LabelID: LabelID,
  280. OldMilestoneID: opts.OldMilestoneID,
  281. MilestoneID: opts.MilestoneID,
  282. RemovedAssignee: opts.RemovedAssignee,
  283. AssigneeID: opts.AssigneeID,
  284. CommitID: opts.CommitID,
  285. CommitSHA: opts.CommitSHA,
  286. Line: opts.LineNum,
  287. Content: opts.Content,
  288. OldTitle: opts.OldTitle,
  289. NewTitle: opts.NewTitle,
  290. }
  291. if _, err = e.Insert(comment); err != nil {
  292. return nil, err
  293. }
  294. if err = opts.Repo.getOwner(e); err != nil {
  295. return nil, err
  296. }
  297. // Compose comment action, could be plain comment, close or reopen issue/pull request.
  298. // This object will be used to notify watchers in the end of function.
  299. act := &Action{
  300. ActUserID: opts.Doer.ID,
  301. ActUser: opts.Doer,
  302. Content: fmt.Sprintf("%d|%s", opts.Issue.Index, strings.Split(opts.Content, "\n")[0]),
  303. RepoID: opts.Repo.ID,
  304. Repo: opts.Repo,
  305. Comment: comment,
  306. CommentID: comment.ID,
  307. IsPrivate: opts.Repo.IsPrivate,
  308. }
  309. // Check comment type.
  310. switch opts.Type {
  311. case CommentTypeComment:
  312. act.OpType = ActionCommentIssue
  313. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", opts.Issue.ID); err != nil {
  314. return nil, err
  315. }
  316. // Check attachments
  317. attachments := make([]*Attachment, 0, len(opts.Attachments))
  318. for _, uuid := range opts.Attachments {
  319. attach, err := getAttachmentByUUID(e, uuid)
  320. if err != nil {
  321. if IsErrAttachmentNotExist(err) {
  322. continue
  323. }
  324. return nil, fmt.Errorf("getAttachmentByUUID [%s]: %v", uuid, err)
  325. }
  326. attachments = append(attachments, attach)
  327. }
  328. for i := range attachments {
  329. attachments[i].IssueID = opts.Issue.ID
  330. attachments[i].CommentID = comment.ID
  331. // No assign value could be 0, so ignore AllCols().
  332. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  333. return nil, fmt.Errorf("update attachment [%d]: %v", attachments[i].ID, err)
  334. }
  335. }
  336. case CommentTypeReopen:
  337. act.OpType = ActionReopenIssue
  338. if opts.Issue.IsPull {
  339. act.OpType = ActionReopenPullRequest
  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. case CommentTypeClose:
  350. act.OpType = ActionCloseIssue
  351. if opts.Issue.IsPull {
  352. act.OpType = ActionClosePullRequest
  353. }
  354. if opts.Issue.IsPull {
  355. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls+1 WHERE id=?", opts.Repo.ID)
  356. } else {
  357. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", opts.Repo.ID)
  358. }
  359. if err != nil {
  360. return nil, err
  361. }
  362. }
  363. // update the issue's updated_unix column
  364. if err = updateIssueCols(e, opts.Issue, "updated_unix"); err != nil {
  365. return nil, err
  366. }
  367. // Notify watchers for whatever action comes in, ignore if no action type.
  368. if act.OpType > 0 {
  369. if err = notifyWatchers(e, act); err != nil {
  370. log.Error(4, "notifyWatchers: %v", err)
  371. }
  372. if err = comment.MailParticipants(e, act.OpType, opts.Issue); err != nil {
  373. log.Error(4, "MailParticipants: %v", err)
  374. }
  375. }
  376. return comment, nil
  377. }
  378. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  379. cmtType := CommentTypeClose
  380. if !issue.IsClosed {
  381. cmtType = CommentTypeReopen
  382. }
  383. return createComment(e, &CreateCommentOptions{
  384. Type: cmtType,
  385. Doer: doer,
  386. Repo: repo,
  387. Issue: issue,
  388. })
  389. }
  390. func createLabelComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, label *Label, add bool) (*Comment, error) {
  391. var content string
  392. if add {
  393. content = "1"
  394. }
  395. return createComment(e, &CreateCommentOptions{
  396. Type: CommentTypeLabel,
  397. Doer: doer,
  398. Repo: repo,
  399. Issue: issue,
  400. Label: label,
  401. Content: content,
  402. })
  403. }
  404. func createMilestoneComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldMilestoneID, milestoneID int64) (*Comment, error) {
  405. return createComment(e, &CreateCommentOptions{
  406. Type: CommentTypeMilestone,
  407. Doer: doer,
  408. Repo: repo,
  409. Issue: issue,
  410. OldMilestoneID: oldMilestoneID,
  411. MilestoneID: milestoneID,
  412. })
  413. }
  414. func createAssigneeComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, assigneeID int64, removedAssignee bool) (*Comment, error) {
  415. return createComment(e, &CreateCommentOptions{
  416. Type: CommentTypeAssignees,
  417. Doer: doer,
  418. Repo: repo,
  419. Issue: issue,
  420. RemovedAssignee: removedAssignee,
  421. AssigneeID: assigneeID,
  422. })
  423. }
  424. func createDeadlineComment(e *xorm.Session, doer *User, issue *Issue, newDeadlineUnix util.TimeStamp) (*Comment, error) {
  425. var content string
  426. var commentType CommentType
  427. // newDeadline = 0 means deleting
  428. if newDeadlineUnix == 0 {
  429. commentType = CommentTypeRemovedDeadline
  430. content = issue.DeadlineUnix.Format("2006-01-02")
  431. } else if issue.DeadlineUnix == 0 {
  432. // Check if the new date was added or modified
  433. // If the actual deadline is 0 => deadline added
  434. commentType = CommentTypeAddedDeadline
  435. content = newDeadlineUnix.Format("2006-01-02")
  436. } else { // Otherwise modified
  437. commentType = CommentTypeModifiedDeadline
  438. content = newDeadlineUnix.Format("2006-01-02") + "|" + issue.DeadlineUnix.Format("2006-01-02")
  439. }
  440. return createComment(e, &CreateCommentOptions{
  441. Type: commentType,
  442. Doer: doer,
  443. Repo: issue.Repo,
  444. Issue: issue,
  445. Content: content,
  446. })
  447. }
  448. func createChangeTitleComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, oldTitle, newTitle string) (*Comment, error) {
  449. return createComment(e, &CreateCommentOptions{
  450. Type: CommentTypeChangeTitle,
  451. Doer: doer,
  452. Repo: repo,
  453. Issue: issue,
  454. OldTitle: oldTitle,
  455. NewTitle: newTitle,
  456. })
  457. }
  458. func createDeleteBranchComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue, branchName string) (*Comment, error) {
  459. return createComment(e, &CreateCommentOptions{
  460. Type: CommentTypeDeleteBranch,
  461. Doer: doer,
  462. Repo: repo,
  463. Issue: issue,
  464. CommitSHA: branchName,
  465. })
  466. }
  467. // CreateCommentOptions defines options for creating comment
  468. type CreateCommentOptions struct {
  469. Type CommentType
  470. Doer *User
  471. Repo *Repository
  472. Issue *Issue
  473. Label *Label
  474. OldMilestoneID int64
  475. MilestoneID int64
  476. AssigneeID int64
  477. RemovedAssignee bool
  478. OldTitle string
  479. NewTitle string
  480. CommitID int64
  481. CommitSHA string
  482. LineNum int64
  483. Content string
  484. Attachments []string // UUIDs of attachments
  485. }
  486. // CreateComment creates comment of issue or commit.
  487. func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) {
  488. sess := x.NewSession()
  489. defer sess.Close()
  490. if err = sess.Begin(); err != nil {
  491. return nil, err
  492. }
  493. comment, err = createComment(sess, opts)
  494. if err != nil {
  495. return nil, err
  496. }
  497. if err = sess.Commit(); err != nil {
  498. return nil, err
  499. }
  500. if opts.Type == CommentTypeComment {
  501. UpdateIssueIndexer(opts.Issue.ID)
  502. }
  503. return comment, nil
  504. }
  505. // CreateIssueComment creates a plain issue comment.
  506. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  507. return CreateComment(&CreateCommentOptions{
  508. Type: CommentTypeComment,
  509. Doer: doer,
  510. Repo: repo,
  511. Issue: issue,
  512. Content: content,
  513. Attachments: attachments,
  514. })
  515. }
  516. // CreateRefComment creates a commit reference comment to issue.
  517. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  518. if len(commitSHA) == 0 {
  519. return fmt.Errorf("cannot create reference with empty commit SHA")
  520. }
  521. // Check if same reference from same commit has already existed.
  522. has, err := x.Get(&Comment{
  523. Type: CommentTypeCommitRef,
  524. IssueID: issue.ID,
  525. CommitSHA: commitSHA,
  526. })
  527. if err != nil {
  528. return fmt.Errorf("check reference comment: %v", err)
  529. } else if has {
  530. return nil
  531. }
  532. _, err = CreateComment(&CreateCommentOptions{
  533. Type: CommentTypeCommitRef,
  534. Doer: doer,
  535. Repo: repo,
  536. Issue: issue,
  537. CommitSHA: commitSHA,
  538. Content: content,
  539. })
  540. return err
  541. }
  542. // GetCommentByID returns the comment by given ID.
  543. func GetCommentByID(id int64) (*Comment, error) {
  544. c := new(Comment)
  545. has, err := x.ID(id).Get(c)
  546. if err != nil {
  547. return nil, err
  548. } else if !has {
  549. return nil, ErrCommentNotExist{id, 0}
  550. }
  551. return c, nil
  552. }
  553. // FindCommentsOptions describes the conditions to Find comments
  554. type FindCommentsOptions struct {
  555. RepoID int64
  556. IssueID int64
  557. Since int64
  558. Type CommentType
  559. }
  560. func (opts *FindCommentsOptions) toConds() builder.Cond {
  561. var cond = builder.NewCond()
  562. if opts.RepoID > 0 {
  563. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  564. }
  565. if opts.IssueID > 0 {
  566. cond = cond.And(builder.Eq{"comment.issue_id": opts.IssueID})
  567. }
  568. if opts.Since > 0 {
  569. cond = cond.And(builder.Gte{"comment.updated_unix": opts.Since})
  570. }
  571. if opts.Type != CommentTypeUnknown {
  572. cond = cond.And(builder.Eq{"comment.type": opts.Type})
  573. }
  574. return cond
  575. }
  576. func findComments(e Engine, opts FindCommentsOptions) ([]*Comment, error) {
  577. comments := make([]*Comment, 0, 10)
  578. sess := e.Where(opts.toConds())
  579. if opts.RepoID > 0 {
  580. sess.Join("INNER", "issue", "issue.id = comment.issue_id")
  581. }
  582. return comments, sess.
  583. Asc("comment.created_unix").
  584. Asc("comment.id").
  585. Find(&comments)
  586. }
  587. // FindComments returns all comments according options
  588. func FindComments(opts FindCommentsOptions) ([]*Comment, error) {
  589. return findComments(x, opts)
  590. }
  591. // GetCommentsByIssueID returns all comments of an issue.
  592. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  593. return findComments(x, FindCommentsOptions{
  594. IssueID: issueID,
  595. Type: CommentTypeUnknown,
  596. })
  597. }
  598. // GetCommentsByIssueIDSince returns a list of comments of an issue since a given time point.
  599. func GetCommentsByIssueIDSince(issueID, since int64) ([]*Comment, error) {
  600. return findComments(x, FindCommentsOptions{
  601. IssueID: issueID,
  602. Type: CommentTypeUnknown,
  603. Since: since,
  604. })
  605. }
  606. // GetCommentsByRepoIDSince returns a list of comments for all issues in a repo since a given time point.
  607. func GetCommentsByRepoIDSince(repoID, since int64) ([]*Comment, error) {
  608. return findComments(x, FindCommentsOptions{
  609. RepoID: repoID,
  610. Type: CommentTypeUnknown,
  611. Since: since,
  612. })
  613. }
  614. // UpdateComment updates information of comment.
  615. func UpdateComment(c *Comment) error {
  616. if _, err := x.ID(c.ID).AllCols().Update(c); err != nil {
  617. return err
  618. } else if c.Type == CommentTypeComment {
  619. UpdateIssueIndexer(c.IssueID)
  620. }
  621. return nil
  622. }
  623. // DeleteComment deletes the comment
  624. func DeleteComment(comment *Comment) error {
  625. sess := x.NewSession()
  626. defer sess.Close()
  627. if err := sess.Begin(); err != nil {
  628. return err
  629. }
  630. if _, err := sess.Delete(&Comment{
  631. ID: comment.ID,
  632. }); err != nil {
  633. return err
  634. }
  635. if comment.Type == CommentTypeComment {
  636. if _, err := sess.Exec("UPDATE `issue` SET num_comments = num_comments - 1 WHERE id = ?", comment.IssueID); err != nil {
  637. return err
  638. }
  639. }
  640. if _, err := sess.Where("comment_id = ?", comment.ID).Cols("is_deleted").Update(&Action{IsDeleted: true}); err != nil {
  641. return err
  642. }
  643. if err := sess.Commit(); err != nil {
  644. return err
  645. } else if comment.Type == CommentTypeComment {
  646. UpdateIssueIndexer(comment.IssueID)
  647. }
  648. return nil
  649. }