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