You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

issue.go 42KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636
  1. // Copyright 2014 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. "bytes"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "mime/multipart"
  11. "os"
  12. "path"
  13. "strings"
  14. "time"
  15. "github.com/Unknwon/com"
  16. "github.com/go-xorm/xorm"
  17. gouuid "github.com/satori/go.uuid"
  18. "github.com/gogits/gogs/modules/base"
  19. "github.com/gogits/gogs/modules/log"
  20. "github.com/gogits/gogs/modules/setting"
  21. )
  22. var (
  23. ErrWrongIssueCounter = errors.New("Invalid number of issues for this milestone")
  24. ErrAttachmentNotLinked = errors.New("Attachment does not belong to this issue")
  25. ErrMissingIssueNumber = errors.New("No issue number specified")
  26. )
  27. // Issue represents an issue or pull request of repository.
  28. type Issue struct {
  29. ID int64 `xorm:"pk autoincr"`
  30. RepoID int64 `xorm:"INDEX"`
  31. Index int64 // Index in one repository.
  32. Name string
  33. Repo *Repository `xorm:"-"`
  34. PosterID int64
  35. Poster *User `xorm:"-"`
  36. Labels []*Label `xorm:"-"`
  37. MilestoneID int64
  38. Milestone *Milestone `xorm:"-"`
  39. AssigneeID int64
  40. Assignee *User `xorm:"-"`
  41. IsRead bool `xorm:"-"`
  42. IsPull bool // Indicates whether is a pull request or not.
  43. *PullRequest `xorm:"-"`
  44. IsClosed bool
  45. Content string `xorm:"TEXT"`
  46. RenderedContent string `xorm:"-"`
  47. Priority int
  48. NumComments int
  49. Deadline time.Time
  50. Created time.Time `xorm:"CREATED"`
  51. Updated time.Time `xorm:"UPDATED"`
  52. Attachments []*Attachment `xorm:"-"`
  53. Comments []*Comment `xorm:"-"`
  54. }
  55. func (i *Issue) AfterSet(colName string, _ xorm.Cell) {
  56. var err error
  57. switch colName {
  58. case "id":
  59. i.Attachments, err = GetAttachmentsByIssueID(i.ID)
  60. if err != nil {
  61. log.Error(3, "GetAttachmentsByIssueID[%d]: %v", i.ID, err)
  62. }
  63. i.Comments, err = GetCommentsByIssueID(i.ID)
  64. if err != nil {
  65. log.Error(3, "GetCommentsByIssueID[%d]: %v", i.ID, err)
  66. }
  67. case "milestone_id":
  68. if i.MilestoneID == 0 {
  69. return
  70. }
  71. i.Milestone, err = GetMilestoneByID(i.MilestoneID)
  72. if err != nil {
  73. log.Error(3, "GetMilestoneById[%d]: %v", i.ID, err)
  74. }
  75. case "assignee_id":
  76. if i.AssigneeID == 0 {
  77. return
  78. }
  79. i.Assignee, err = GetUserByID(i.AssigneeID)
  80. if err != nil {
  81. log.Error(3, "GetUserByID[%d]: %v", i.ID, err)
  82. }
  83. case "created":
  84. i.Created = regulateTimeZone(i.Created)
  85. }
  86. }
  87. // HashTag returns unique hash tag for issue.
  88. func (i *Issue) HashTag() string {
  89. return "issue-" + com.ToStr(i.ID)
  90. }
  91. // IsPoster returns true if given user by ID is the poster.
  92. func (i *Issue) IsPoster(uid int64) bool {
  93. return i.PosterID == uid
  94. }
  95. func (i *Issue) GetPoster() (err error) {
  96. i.Poster, err = GetUserByID(i.PosterID)
  97. if IsErrUserNotExist(err) {
  98. i.PosterID = -1
  99. i.Poster = NewFakeUser()
  100. return nil
  101. }
  102. return err
  103. }
  104. func (i *Issue) hasLabel(e Engine, labelID int64) bool {
  105. return hasIssueLabel(e, i.ID, labelID)
  106. }
  107. // HasLabel returns true if issue has been labeled by given ID.
  108. func (i *Issue) HasLabel(labelID int64) bool {
  109. return i.hasLabel(x, labelID)
  110. }
  111. func (i *Issue) addLabel(e *xorm.Session, label *Label) error {
  112. return newIssueLabel(e, i, label)
  113. }
  114. // AddLabel adds new label to issue by given ID.
  115. func (i *Issue) AddLabel(label *Label) (err error) {
  116. sess := x.NewSession()
  117. defer sessionRelease(sess)
  118. if err = sess.Begin(); err != nil {
  119. return err
  120. }
  121. if err = i.addLabel(sess, label); err != nil {
  122. return err
  123. }
  124. return sess.Commit()
  125. }
  126. func (i *Issue) getLabels(e Engine) (err error) {
  127. if len(i.Labels) > 0 {
  128. return nil
  129. }
  130. i.Labels, err = getLabelsByIssueID(e, i.ID)
  131. if err != nil {
  132. return fmt.Errorf("getLabelsByIssueID: %v", err)
  133. }
  134. return nil
  135. }
  136. // GetLabels retrieves all labels of issue and assign to corresponding field.
  137. func (i *Issue) GetLabels() error {
  138. return i.getLabels(x)
  139. }
  140. func (i *Issue) removeLabel(e *xorm.Session, label *Label) error {
  141. return deleteIssueLabel(e, i, label)
  142. }
  143. // RemoveLabel removes a label from issue by given ID.
  144. func (i *Issue) RemoveLabel(label *Label) (err error) {
  145. sess := x.NewSession()
  146. defer sessionRelease(sess)
  147. if err = sess.Begin(); err != nil {
  148. return err
  149. }
  150. if err = i.removeLabel(sess, label); err != nil {
  151. return err
  152. }
  153. return sess.Commit()
  154. }
  155. func (i *Issue) ClearLabels() (err error) {
  156. sess := x.NewSession()
  157. defer sessionRelease(sess)
  158. if err = sess.Begin(); err != nil {
  159. return err
  160. }
  161. if err = i.getLabels(sess); err != nil {
  162. return err
  163. }
  164. for idx := range i.Labels {
  165. if err = i.removeLabel(sess, i.Labels[idx]); err != nil {
  166. return err
  167. }
  168. }
  169. return sess.Commit()
  170. }
  171. func (i *Issue) GetAssignee() (err error) {
  172. if i.AssigneeID == 0 || i.Assignee != nil {
  173. return nil
  174. }
  175. i.Assignee, err = GetUserByID(i.AssigneeID)
  176. if IsErrUserNotExist(err) {
  177. return nil
  178. }
  179. return err
  180. }
  181. // ReadBy sets issue to be read by given user.
  182. func (i *Issue) ReadBy(uid int64) error {
  183. return UpdateIssueUserByRead(uid, i.ID)
  184. }
  185. func (i *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
  186. if i.IsClosed == isClosed {
  187. return nil
  188. }
  189. i.IsClosed = isClosed
  190. if err = updateIssueCols(e, i, "is_closed"); err != nil {
  191. return err
  192. } else if err = updateIssueUsersByStatus(e, i.ID, isClosed); err != nil {
  193. return err
  194. }
  195. // Update labels.
  196. if err = i.getLabels(e); err != nil {
  197. return err
  198. }
  199. for idx := range i.Labels {
  200. if i.IsClosed {
  201. i.Labels[idx].NumClosedIssues++
  202. } else {
  203. i.Labels[idx].NumClosedIssues--
  204. }
  205. if err = updateLabel(e, i.Labels[idx]); err != nil {
  206. return err
  207. }
  208. }
  209. // Update milestone.
  210. if err = changeMilestoneIssueStats(e, i); err != nil {
  211. return err
  212. }
  213. // New action comment.
  214. if _, err = createStatusComment(e, doer, repo, i); err != nil {
  215. return err
  216. }
  217. return nil
  218. }
  219. // ChangeStatus changes issue status to open/closed.
  220. func (i *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (err error) {
  221. sess := x.NewSession()
  222. defer sessionRelease(sess)
  223. if err = sess.Begin(); err != nil {
  224. return err
  225. }
  226. if err = i.changeStatus(sess, doer, repo, isClosed); err != nil {
  227. return err
  228. }
  229. return sess.Commit()
  230. }
  231. func (i *Issue) GetPullRequest() (err error) {
  232. if i.PullRequest != nil {
  233. return nil
  234. }
  235. i.PullRequest, err = GetPullRequestByIssueID(i.ID)
  236. return err
  237. }
  238. // It's caller's responsibility to create action.
  239. func newIssue(e *xorm.Session, repo *Repository, issue *Issue, labelIDs []int64, uuids []string, isPull bool) (err error) {
  240. if _, err = e.Insert(issue); err != nil {
  241. return err
  242. }
  243. if isPull {
  244. _, err = e.Exec("UPDATE `repository` SET num_pulls=num_pulls+1 WHERE id=?", issue.RepoID)
  245. } else {
  246. _, err = e.Exec("UPDATE `repository` SET num_issues=num_issues+1 WHERE id=?", issue.RepoID)
  247. }
  248. if err != nil {
  249. return err
  250. }
  251. // During the session, SQLite3 dirver cannot handle retrieve objects after update something.
  252. // So we have to get all needed labels first.
  253. labels := make([]*Label, 0, len(labelIDs))
  254. if err = e.In("id", labelIDs).Find(&labels); err != nil {
  255. return fmt.Errorf("find all labels: %v", err)
  256. }
  257. for _, label := range labels {
  258. if err = issue.addLabel(e, label); err != nil {
  259. return fmt.Errorf("addLabel: %v", err)
  260. }
  261. }
  262. if issue.MilestoneID > 0 {
  263. if err = changeMilestoneAssign(e, 0, issue); err != nil {
  264. return err
  265. }
  266. }
  267. if err = newIssueUsers(e, repo, issue); err != nil {
  268. return err
  269. }
  270. // Check attachments.
  271. attachments := make([]*Attachment, 0, len(uuids))
  272. for _, uuid := range uuids {
  273. attach, err := getAttachmentByUUID(e, uuid)
  274. if err != nil {
  275. if IsErrAttachmentNotExist(err) {
  276. continue
  277. }
  278. return fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  279. }
  280. attachments = append(attachments, attach)
  281. }
  282. for i := range attachments {
  283. attachments[i].IssueID = issue.ID
  284. // No assign value could be 0, so ignore AllCols().
  285. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  286. return fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  287. }
  288. }
  289. return nil
  290. }
  291. // NewIssue creates new issue with labels for repository.
  292. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  293. sess := x.NewSession()
  294. defer sessionRelease(sess)
  295. if err = sess.Begin(); err != nil {
  296. return err
  297. }
  298. if err = newIssue(sess, repo, issue, labelIDs, uuids, false); err != nil {
  299. return fmt.Errorf("newIssue: %v", err)
  300. }
  301. // Notify watchers.
  302. act := &Action{
  303. ActUserID: issue.Poster.Id,
  304. ActUserName: issue.Poster.Name,
  305. ActEmail: issue.Poster.Email,
  306. OpType: ACTION_CREATE_ISSUE,
  307. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Name),
  308. RepoID: repo.ID,
  309. RepoUserName: repo.Owner.Name,
  310. RepoName: repo.Name,
  311. IsPrivate: repo.IsPrivate,
  312. }
  313. if err = notifyWatchers(sess, act); err != nil {
  314. return err
  315. }
  316. return sess.Commit()
  317. }
  318. // GetIssueByRef returns an Issue specified by a GFM reference.
  319. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  320. func GetIssueByRef(ref string) (*Issue, error) {
  321. n := strings.IndexByte(ref, byte('#'))
  322. if n == -1 {
  323. return nil, ErrMissingIssueNumber
  324. }
  325. index, err := com.StrTo(ref[n+1:]).Int64()
  326. if err != nil {
  327. return nil, err
  328. }
  329. repo, err := GetRepositoryByRef(ref[:n])
  330. if err != nil {
  331. return nil, err
  332. }
  333. issue, err := GetIssueByIndex(repo.ID, index)
  334. if err != nil {
  335. return nil, err
  336. }
  337. issue.Repo = repo
  338. return issue, nil
  339. }
  340. // GetIssueByIndex returns issue by given index in repository.
  341. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  342. issue := &Issue{
  343. RepoID: repoID,
  344. Index: index,
  345. }
  346. has, err := x.Get(issue)
  347. if err != nil {
  348. return nil, err
  349. } else if !has {
  350. return nil, ErrIssueNotExist{0, repoID, index}
  351. }
  352. return issue, nil
  353. }
  354. // GetIssueByID returns an issue by given ID.
  355. func GetIssueByID(id int64) (*Issue, error) {
  356. issue := new(Issue)
  357. has, err := x.Id(id).Get(issue)
  358. if err != nil {
  359. return nil, err
  360. } else if !has {
  361. return nil, ErrIssueNotExist{id, 0, 0}
  362. }
  363. return issue, nil
  364. }
  365. type IssuesOptions struct {
  366. UserID int64
  367. AssigneeID int64
  368. RepoID int64
  369. PosterID int64
  370. MilestoneID int64
  371. RepoIDs []int64
  372. Page int
  373. IsClosed bool
  374. IsMention bool
  375. IsPull bool
  376. Labels string
  377. SortType string
  378. }
  379. // Issues returns a list of issues by given conditions.
  380. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  381. sess := x.Limit(setting.IssuePagingNum, (opts.Page-1)*setting.IssuePagingNum)
  382. if opts.RepoID > 0 {
  383. sess.Where("issue.repo_id=?", opts.RepoID).And("issue.is_closed=?", opts.IsClosed)
  384. } else if opts.RepoIDs != nil {
  385. // In case repository IDs are provided but actually no repository has issue.
  386. if len(opts.RepoIDs) == 0 {
  387. return make([]*Issue, 0), nil
  388. }
  389. sess.Where("issue.repo_id IN ("+strings.Join(base.Int64sToStrings(opts.RepoIDs), ",")+")").And("issue.is_closed=?", opts.IsClosed)
  390. } else {
  391. sess.Where("issue.is_closed=?", opts.IsClosed)
  392. }
  393. if opts.AssigneeID > 0 {
  394. sess.And("issue.assignee_id=?", opts.AssigneeID)
  395. } else if opts.PosterID > 0 {
  396. sess.And("issue.poster_id=?", opts.PosterID)
  397. }
  398. if opts.MilestoneID > 0 {
  399. sess.And("issue.milestone_id=?", opts.MilestoneID)
  400. }
  401. sess.And("issue.is_pull=?", opts.IsPull)
  402. switch opts.SortType {
  403. case "oldest":
  404. sess.Asc("created")
  405. case "recentupdate":
  406. sess.Desc("updated")
  407. case "leastupdate":
  408. sess.Asc("updated")
  409. case "mostcomment":
  410. sess.Desc("num_comments")
  411. case "leastcomment":
  412. sess.Asc("num_comments")
  413. case "priority":
  414. sess.Desc("priority")
  415. default:
  416. sess.Desc("created")
  417. }
  418. labelIDs := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  419. if len(labelIDs) > 0 {
  420. validJoin := false
  421. queryStr := "issue.id=issue_label.issue_id"
  422. for _, id := range labelIDs {
  423. if id == 0 {
  424. continue
  425. }
  426. validJoin = true
  427. queryStr += " AND issue_label.label_id=" + com.ToStr(id)
  428. }
  429. if validJoin {
  430. sess.Join("INNER", "issue_label", queryStr)
  431. }
  432. }
  433. if opts.IsMention {
  434. queryStr := "issue.id=issue_user.issue_id AND issue_user.is_mentioned=1"
  435. if opts.UserID > 0 {
  436. queryStr += " AND issue_user.uid=" + com.ToStr(opts.UserID)
  437. }
  438. sess.Join("INNER", "issue_user", queryStr)
  439. }
  440. issues := make([]*Issue, 0, setting.IssuePagingNum)
  441. return issues, sess.Find(&issues)
  442. }
  443. type IssueStatus int
  444. const (
  445. IS_OPEN = iota + 1
  446. IS_CLOSE
  447. )
  448. // GetIssueCountByPoster returns number of issues of repository by poster.
  449. func GetIssueCountByPoster(uid, rid int64, isClosed bool) int64 {
  450. count, _ := x.Where("repo_id=?", rid).And("poster_id=?", uid).And("is_closed=?", isClosed).Count(new(Issue))
  451. return count
  452. }
  453. // .___ ____ ___
  454. // | | ______ ________ __ ____ | | \______ ___________
  455. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  456. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  457. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  458. // \/ \/ \/ \/ \/
  459. // IssueUser represents an issue-user relation.
  460. type IssueUser struct {
  461. ID int64 `xorm:"pk autoincr"`
  462. UID int64 `xorm:"INDEX"` // User ID.
  463. IssueID int64
  464. RepoID int64 `xorm:"INDEX"`
  465. MilestoneID int64
  466. IsRead bool
  467. IsAssigned bool
  468. IsMentioned bool
  469. IsPoster bool
  470. IsClosed bool
  471. }
  472. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  473. users, err := repo.GetAssignees()
  474. if err != nil {
  475. return err
  476. }
  477. iu := &IssueUser{
  478. IssueID: issue.ID,
  479. RepoID: repo.ID,
  480. }
  481. // Poster can be anyone.
  482. isNeedAddPoster := true
  483. for _, u := range users {
  484. iu.ID = 0
  485. iu.UID = u.Id
  486. iu.IsPoster = iu.UID == issue.PosterID
  487. if isNeedAddPoster && iu.IsPoster {
  488. isNeedAddPoster = false
  489. }
  490. iu.IsAssigned = iu.UID == issue.AssigneeID
  491. if _, err = e.Insert(iu); err != nil {
  492. return err
  493. }
  494. }
  495. if isNeedAddPoster {
  496. iu.ID = 0
  497. iu.UID = issue.PosterID
  498. iu.IsPoster = true
  499. if _, err = e.Insert(iu); err != nil {
  500. return err
  501. }
  502. }
  503. return nil
  504. }
  505. // NewIssueUsers adds new issue-user relations for new issue of repository.
  506. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  507. sess := x.NewSession()
  508. defer sessionRelease(sess)
  509. if err = sess.Begin(); err != nil {
  510. return err
  511. }
  512. if err = newIssueUsers(sess, repo, issue); err != nil {
  513. return err
  514. }
  515. return sess.Commit()
  516. }
  517. // PairsContains returns true when pairs list contains given issue.
  518. func PairsContains(ius []*IssueUser, issueId, uid int64) int {
  519. for i := range ius {
  520. if ius[i].IssueID == issueId &&
  521. ius[i].UID == uid {
  522. return i
  523. }
  524. }
  525. return -1
  526. }
  527. // GetIssueUsers returns issue-user pairs by given repository and user.
  528. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  529. ius := make([]*IssueUser, 0, 10)
  530. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  531. return ius, err
  532. }
  533. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  534. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  535. if len(rids) == 0 {
  536. return []*IssueUser{}, nil
  537. }
  538. buf := bytes.NewBufferString("")
  539. for _, rid := range rids {
  540. buf.WriteString("repo_id=")
  541. buf.WriteString(com.ToStr(rid))
  542. buf.WriteString(" OR ")
  543. }
  544. cond := strings.TrimSuffix(buf.String(), " OR ")
  545. ius := make([]*IssueUser, 0, 10)
  546. sess := x.Limit(20, (page-1)*20).Where("is_closed=?", isClosed)
  547. if len(cond) > 0 {
  548. sess.And(cond)
  549. }
  550. err := sess.Find(&ius)
  551. return ius, err
  552. }
  553. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  554. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  555. ius := make([]*IssueUser, 0, 10)
  556. sess := x.Limit(20, (page-1)*20).Where("uid=?", uid).And("is_closed=?", isClosed)
  557. if rid > 0 {
  558. sess.And("repo_id=?", rid)
  559. }
  560. switch filterMode {
  561. case FM_ASSIGN:
  562. sess.And("is_assigned=?", true)
  563. case FM_CREATE:
  564. sess.And("is_poster=?", true)
  565. default:
  566. return ius, nil
  567. }
  568. err := sess.Find(&ius)
  569. return ius, err
  570. }
  571. func UpdateMentions(userNames []string, issueId int64) error {
  572. for i := range userNames {
  573. userNames[i] = strings.ToLower(userNames[i])
  574. }
  575. users := make([]*User, 0, len(userNames))
  576. if err := x.Where("lower_name IN (?)", strings.Join(userNames, "\",\"")).OrderBy("lower_name ASC").Find(&users); err != nil {
  577. return err
  578. }
  579. ids := make([]int64, 0, len(userNames))
  580. for _, user := range users {
  581. ids = append(ids, user.Id)
  582. if !user.IsOrganization() {
  583. continue
  584. }
  585. if user.NumMembers == 0 {
  586. continue
  587. }
  588. tempIds := make([]int64, 0, user.NumMembers)
  589. orgUsers, err := GetOrgUsersByOrgId(user.Id)
  590. if err != nil {
  591. return err
  592. }
  593. for _, orgUser := range orgUsers {
  594. tempIds = append(tempIds, orgUser.ID)
  595. }
  596. ids = append(ids, tempIds...)
  597. }
  598. if err := UpdateIssueUsersByMentions(ids, issueId); err != nil {
  599. return err
  600. }
  601. return nil
  602. }
  603. // IssueStats represents issue statistic information.
  604. type IssueStats struct {
  605. OpenCount, ClosedCount int64
  606. AllCount int64
  607. AssignCount int64
  608. CreateCount int64
  609. MentionCount int64
  610. }
  611. // Filter modes.
  612. const (
  613. FM_ALL = iota
  614. FM_ASSIGN
  615. FM_CREATE
  616. FM_MENTION
  617. )
  618. func parseCountResult(results []map[string][]byte) int64 {
  619. if len(results) == 0 {
  620. return 0
  621. }
  622. for _, result := range results[0] {
  623. return com.StrTo(string(result)).MustInt64()
  624. }
  625. return 0
  626. }
  627. type IssueStatsOptions struct {
  628. RepoID int64
  629. UserID int64
  630. LabelID int64
  631. MilestoneID int64
  632. AssigneeID int64
  633. FilterMode int
  634. IsPull bool
  635. }
  636. // GetIssueStats returns issue statistic information by given conditions.
  637. func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
  638. stats := &IssueStats{}
  639. queryStr := "SELECT COUNT(*) FROM `issue` "
  640. if opts.LabelID > 0 {
  641. queryStr += "INNER JOIN `issue_label` ON `issue`.id=`issue_label`.issue_id AND `issue_label`.label_id=" + com.ToStr(opts.LabelID)
  642. }
  643. baseCond := " WHERE issue.repo_id=" + com.ToStr(opts.RepoID) + " AND issue.is_closed=?"
  644. if opts.MilestoneID > 0 {
  645. baseCond += " AND issue.milestone_id=" + com.ToStr(opts.MilestoneID)
  646. }
  647. if opts.AssigneeID > 0 {
  648. baseCond += " AND assignee_id=" + com.ToStr(opts.AssigneeID)
  649. }
  650. baseCond += " AND issue.is_pull=?"
  651. switch opts.FilterMode {
  652. case FM_ALL, FM_ASSIGN:
  653. results, _ := x.Query(queryStr+baseCond, false, opts.IsPull)
  654. stats.OpenCount = parseCountResult(results)
  655. results, _ = x.Query(queryStr+baseCond, true, opts.IsPull)
  656. stats.ClosedCount = parseCountResult(results)
  657. case FM_CREATE:
  658. baseCond += " AND poster_id=?"
  659. results, _ := x.Query(queryStr+baseCond, false, opts.IsPull, opts.UserID)
  660. stats.OpenCount = parseCountResult(results)
  661. results, _ = x.Query(queryStr+baseCond, true, opts.IsPull, opts.UserID)
  662. stats.ClosedCount = parseCountResult(results)
  663. case FM_MENTION:
  664. queryStr += " INNER JOIN `issue_user` ON `issue`.id=`issue_user`.issue_id"
  665. baseCond += " AND `issue_user`.uid=? AND `issue_user`.is_mentioned=?"
  666. results, _ := x.Query(queryStr+baseCond, false, opts.IsPull, opts.UserID, true)
  667. stats.OpenCount = parseCountResult(results)
  668. results, _ = x.Query(queryStr+baseCond, true, opts.IsPull, opts.UserID, true)
  669. stats.ClosedCount = parseCountResult(results)
  670. }
  671. return stats
  672. }
  673. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  674. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  675. stats := &IssueStats{}
  676. queryStr := "SELECT COUNT(*) FROM `issue` "
  677. baseCond := " WHERE issue.is_closed=?"
  678. if repoID > 0 || len(repoIDs) == 0 {
  679. baseCond += " AND issue.repo_id=" + com.ToStr(repoID)
  680. } else {
  681. baseCond += " AND issue.repo_id IN (" + strings.Join(base.Int64sToStrings(repoIDs), ",") + ")"
  682. }
  683. if isPull {
  684. baseCond += " AND issue.is_pull=1"
  685. } else {
  686. baseCond += " AND issue.is_pull=0"
  687. }
  688. results, _ := x.Query(queryStr+baseCond+" AND assignee_id=?", false, uid)
  689. stats.AssignCount = parseCountResult(results)
  690. results, _ = x.Query(queryStr+baseCond+" AND poster_id=?", false, uid)
  691. stats.CreateCount = parseCountResult(results)
  692. switch filterMode {
  693. case FM_ASSIGN:
  694. baseCond += " AND assignee_id=" + com.ToStr(uid)
  695. case FM_CREATE:
  696. baseCond += " AND poster_id=" + com.ToStr(uid)
  697. }
  698. results, _ = x.Query(queryStr+baseCond, false)
  699. stats.OpenCount = parseCountResult(results)
  700. results, _ = x.Query(queryStr+baseCond, true)
  701. stats.ClosedCount = parseCountResult(results)
  702. return stats
  703. }
  704. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  705. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  706. queryStr := "SELECT COUNT(*) FROM `issue` "
  707. baseCond := " WHERE issue.repo_id=? AND issue.is_closed=?"
  708. if isPull {
  709. baseCond += " AND issue.is_pull=1"
  710. } else {
  711. baseCond += " AND issue.is_pull=0"
  712. }
  713. switch filterMode {
  714. case FM_ASSIGN:
  715. baseCond += " AND assignee_id=" + com.ToStr(uid)
  716. case FM_CREATE:
  717. baseCond += " AND poster_id=" + com.ToStr(uid)
  718. }
  719. results, _ := x.Query(queryStr+baseCond, repoID, false)
  720. numOpen = parseCountResult(results)
  721. results, _ = x.Query(queryStr+baseCond, repoID, true)
  722. numClosed = parseCountResult(results)
  723. return numOpen, numClosed
  724. }
  725. func updateIssue(e Engine, issue *Issue) error {
  726. _, err := e.Id(issue.ID).AllCols().Update(issue)
  727. return err
  728. }
  729. // UpdateIssue updates all fields of given issue.
  730. func UpdateIssue(issue *Issue) error {
  731. return updateIssue(x, issue)
  732. }
  733. // updateIssueCols updates specific fields of given issue.
  734. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  735. _, err := e.Id(issue.ID).Cols(cols...).Update(issue)
  736. return err
  737. }
  738. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  739. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  740. return err
  741. }
  742. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  743. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  744. return updateIssueUsersByStatus(x, issueID, isClosed)
  745. }
  746. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  747. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE issue_id=?", false, issue.ID); err != nil {
  748. return err
  749. }
  750. // Assignee ID equals to 0 means clear assignee.
  751. if issue.AssigneeID > 0 {
  752. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE uid=? AND issue_id=?", true, issue.AssigneeID, issue.ID); err != nil {
  753. return err
  754. }
  755. }
  756. return updateIssue(e, issue)
  757. }
  758. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  759. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  760. sess := x.NewSession()
  761. defer sessionRelease(sess)
  762. if err = sess.Begin(); err != nil {
  763. return err
  764. }
  765. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  766. return err
  767. }
  768. return sess.Commit()
  769. }
  770. // UpdateIssueUserByRead updates issue-user relation for reading.
  771. func UpdateIssueUserByRead(uid, issueID int64) error {
  772. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  773. return err
  774. }
  775. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
  776. func UpdateIssueUsersByMentions(uids []int64, iid int64) error {
  777. for _, uid := range uids {
  778. iu := &IssueUser{UID: uid, IssueID: iid}
  779. has, err := x.Get(iu)
  780. if err != nil {
  781. return err
  782. }
  783. iu.IsMentioned = true
  784. if has {
  785. _, err = x.Id(iu.ID).AllCols().Update(iu)
  786. } else {
  787. _, err = x.Insert(iu)
  788. }
  789. if err != nil {
  790. return err
  791. }
  792. }
  793. return nil
  794. }
  795. // _____ .__.__ __
  796. // / \ |__| | ____ _______/ |_ ____ ____ ____
  797. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  798. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  799. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  800. // \/ \/ \/ \/ \/
  801. // Milestone represents a milestone of repository.
  802. type Milestone struct {
  803. ID int64 `xorm:"pk autoincr"`
  804. RepoID int64 `xorm:"INDEX"`
  805. Name string
  806. Content string `xorm:"TEXT"`
  807. RenderedContent string `xorm:"-"`
  808. IsClosed bool
  809. NumIssues int
  810. NumClosedIssues int
  811. NumOpenIssues int `xorm:"-"`
  812. Completeness int // Percentage(1-100).
  813. Deadline time.Time
  814. DeadlineString string `xorm:"-"`
  815. IsOverDue bool `xorm:"-"`
  816. ClosedDate time.Time
  817. }
  818. func (m *Milestone) BeforeUpdate() {
  819. if m.NumIssues > 0 {
  820. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  821. } else {
  822. m.Completeness = 0
  823. }
  824. }
  825. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  826. if colName == "deadline" {
  827. if m.Deadline.Year() == 9999 {
  828. return
  829. }
  830. m.Deadline = regulateTimeZone(m.Deadline)
  831. m.DeadlineString = m.Deadline.Format("2006-01-02")
  832. if time.Now().After(m.Deadline) {
  833. m.IsOverDue = true
  834. }
  835. }
  836. }
  837. // CalOpenIssues calculates the open issues of milestone.
  838. func (m *Milestone) CalOpenIssues() {
  839. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  840. }
  841. // NewMilestone creates new milestone of repository.
  842. func NewMilestone(m *Milestone) (err error) {
  843. sess := x.NewSession()
  844. defer sessionRelease(sess)
  845. if err = sess.Begin(); err != nil {
  846. return err
  847. }
  848. if _, err = sess.Insert(m); err != nil {
  849. return err
  850. }
  851. if _, err = sess.Exec("UPDATE `repository` SET num_milestones=num_milestones+1 WHERE id=?", m.RepoID); err != nil {
  852. return err
  853. }
  854. return sess.Commit()
  855. }
  856. func getMilestoneByID(e Engine, id int64) (*Milestone, error) {
  857. m := &Milestone{ID: id}
  858. has, err := e.Get(m)
  859. if err != nil {
  860. return nil, err
  861. } else if !has {
  862. return nil, ErrMilestoneNotExist{id, 0}
  863. }
  864. return m, nil
  865. }
  866. // GetMilestoneByID returns the milestone of given ID.
  867. func GetMilestoneByID(id int64) (*Milestone, error) {
  868. return getMilestoneByID(x, id)
  869. }
  870. // GetRepoMilestoneByID returns the milestone of given ID and repository.
  871. func GetRepoMilestoneByID(repoID, milestoneID int64) (*Milestone, error) {
  872. m := &Milestone{ID: milestoneID, RepoID: repoID}
  873. has, err := x.Get(m)
  874. if err != nil {
  875. return nil, err
  876. } else if !has {
  877. return nil, ErrMilestoneNotExist{milestoneID, repoID}
  878. }
  879. return m, nil
  880. }
  881. // GetAllRepoMilestones returns all milestones of given repository.
  882. func GetAllRepoMilestones(repoID int64) ([]*Milestone, error) {
  883. miles := make([]*Milestone, 0, 10)
  884. return miles, x.Where("repo_id=?", repoID).Find(&miles)
  885. }
  886. // GetMilestones returns a list of milestones of given repository and status.
  887. func GetMilestones(repoID int64, page int, isClosed bool) ([]*Milestone, error) {
  888. miles := make([]*Milestone, 0, setting.IssuePagingNum)
  889. sess := x.Where("repo_id=? AND is_closed=?", repoID, isClosed)
  890. if page > 0 {
  891. sess = sess.Limit(setting.IssuePagingNum, (page-1)*setting.IssuePagingNum)
  892. }
  893. return miles, sess.Find(&miles)
  894. }
  895. func updateMilestone(e Engine, m *Milestone) error {
  896. _, err := e.Id(m.ID).AllCols().Update(m)
  897. return err
  898. }
  899. // UpdateMilestone updates information of given milestone.
  900. func UpdateMilestone(m *Milestone) error {
  901. return updateMilestone(x, m)
  902. }
  903. func countRepoMilestones(e Engine, repoID int64) int64 {
  904. count, _ := e.Where("repo_id=?", repoID).Count(new(Milestone))
  905. return count
  906. }
  907. // CountRepoMilestones returns number of milestones in given repository.
  908. func CountRepoMilestones(repoID int64) int64 {
  909. return countRepoMilestones(x, repoID)
  910. }
  911. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  912. closed, _ := e.Where("repo_id=? AND is_closed=?", repoID, true).Count(new(Milestone))
  913. return closed
  914. }
  915. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  916. func CountRepoClosedMilestones(repoID int64) int64 {
  917. return countRepoClosedMilestones(x, repoID)
  918. }
  919. // MilestoneStats returns number of open and closed milestones of given repository.
  920. func MilestoneStats(repoID int64) (open int64, closed int64) {
  921. open, _ = x.Where("repo_id=? AND is_closed=?", repoID, false).Count(new(Milestone))
  922. return open, CountRepoClosedMilestones(repoID)
  923. }
  924. // ChangeMilestoneStatus changes the milestone open/closed status.
  925. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  926. repo, err := GetRepositoryByID(m.RepoID)
  927. if err != nil {
  928. return err
  929. }
  930. sess := x.NewSession()
  931. defer sessionRelease(sess)
  932. if err = sess.Begin(); err != nil {
  933. return err
  934. }
  935. m.IsClosed = isClosed
  936. if err = updateMilestone(sess, m); err != nil {
  937. return err
  938. }
  939. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  940. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  941. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  942. return err
  943. }
  944. return sess.Commit()
  945. }
  946. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  947. if issue.MilestoneID == 0 {
  948. return nil
  949. }
  950. m, err := getMilestoneByID(e, issue.MilestoneID)
  951. if err != nil {
  952. return err
  953. }
  954. if issue.IsClosed {
  955. m.NumOpenIssues--
  956. m.NumClosedIssues++
  957. } else {
  958. m.NumOpenIssues++
  959. m.NumClosedIssues--
  960. }
  961. return updateMilestone(e, m)
  962. }
  963. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  964. // for the milestone associated with the given issue.
  965. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  966. sess := x.NewSession()
  967. defer sessionRelease(sess)
  968. if err = sess.Begin(); err != nil {
  969. return err
  970. }
  971. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  972. return err
  973. }
  974. return sess.Commit()
  975. }
  976. func changeMilestoneAssign(e *xorm.Session, oldMid int64, issue *Issue) error {
  977. if oldMid > 0 {
  978. m, err := getMilestoneByID(e, oldMid)
  979. if err != nil {
  980. return err
  981. }
  982. m.NumIssues--
  983. if issue.IsClosed {
  984. m.NumClosedIssues--
  985. }
  986. if err = updateMilestone(e, m); err != nil {
  987. return err
  988. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE issue_id=?", issue.ID); err != nil {
  989. return err
  990. }
  991. }
  992. if issue.MilestoneID > 0 {
  993. m, err := getMilestoneByID(e, issue.MilestoneID)
  994. if err != nil {
  995. return err
  996. }
  997. m.NumIssues++
  998. if issue.IsClosed {
  999. m.NumClosedIssues++
  1000. }
  1001. if m.NumIssues == 0 {
  1002. return ErrWrongIssueCounter
  1003. }
  1004. if err = updateMilestone(e, m); err != nil {
  1005. return err
  1006. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=? WHERE issue_id=?", m.ID, issue.ID); err != nil {
  1007. return err
  1008. }
  1009. }
  1010. return updateIssue(e, issue)
  1011. }
  1012. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1013. func ChangeMilestoneAssign(oldMid int64, issue *Issue) (err error) {
  1014. sess := x.NewSession()
  1015. defer sess.Close()
  1016. if err = sess.Begin(); err != nil {
  1017. return err
  1018. }
  1019. if err = changeMilestoneAssign(sess, oldMid, issue); err != nil {
  1020. return err
  1021. }
  1022. return sess.Commit()
  1023. }
  1024. // DeleteMilestoneByID deletes a milestone by given ID.
  1025. func DeleteMilestoneByID(id int64) error {
  1026. m, err := GetMilestoneByID(id)
  1027. if err != nil {
  1028. if IsErrMilestoneNotExist(err) {
  1029. return nil
  1030. }
  1031. return err
  1032. }
  1033. repo, err := GetRepositoryByID(m.RepoID)
  1034. if err != nil {
  1035. return err
  1036. }
  1037. sess := x.NewSession()
  1038. defer sessionRelease(sess)
  1039. if err = sess.Begin(); err != nil {
  1040. return err
  1041. }
  1042. if _, err = sess.Id(m.ID).Delete(new(Milestone)); err != nil {
  1043. return err
  1044. }
  1045. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1046. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1047. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1048. return err
  1049. }
  1050. if _, err = sess.Exec("UPDATE `issue` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1051. return err
  1052. } else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1053. return err
  1054. }
  1055. return sess.Commit()
  1056. }
  1057. // _________ __
  1058. // \_ ___ \ ____ _____ _____ ____ _____/ |_
  1059. // / \ \/ / _ \ / \ / \_/ __ \ / \ __\
  1060. // \ \___( <_> ) Y Y \ Y Y \ ___/| | \ |
  1061. // \______ /\____/|__|_| /__|_| /\___ >___| /__|
  1062. // \/ \/ \/ \/ \/
  1063. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  1064. type CommentType int
  1065. const (
  1066. // Plain comment, can be associated with a commit (CommitId > 0) and a line (Line > 0)
  1067. COMMENT_TYPE_COMMENT CommentType = iota
  1068. COMMENT_TYPE_REOPEN
  1069. COMMENT_TYPE_CLOSE
  1070. // References.
  1071. COMMENT_TYPE_ISSUE_REF
  1072. // Reference from a commit (not part of a pull request)
  1073. COMMENT_TYPE_COMMIT_REF
  1074. // Reference from a comment
  1075. COMMENT_TYPE_COMMENT_REF
  1076. // Reference from a pull request
  1077. COMMENT_TYPE_PULL_REF
  1078. )
  1079. type CommentTag int
  1080. const (
  1081. COMMENT_TAG_NONE CommentTag = iota
  1082. COMMENT_TAG_POSTER
  1083. COMMENT_TAG_ADMIN
  1084. COMMENT_TAG_OWNER
  1085. )
  1086. // Comment represents a comment in commit and issue page.
  1087. type Comment struct {
  1088. ID int64 `xorm:"pk autoincr"`
  1089. Type CommentType
  1090. PosterID int64
  1091. Poster *User `xorm:"-"`
  1092. IssueID int64 `xorm:"INDEX"`
  1093. CommitID int64
  1094. Line int64
  1095. Content string `xorm:"TEXT"`
  1096. RenderedContent string `xorm:"-"`
  1097. Created time.Time `xorm:"CREATED"`
  1098. // Reference issue in commit message
  1099. CommitSHA string `xorm:"VARCHAR(40)"`
  1100. Attachments []*Attachment `xorm:"-"`
  1101. // For view issue page.
  1102. ShowTag CommentTag `xorm:"-"`
  1103. }
  1104. func (c *Comment) AfterSet(colName string, _ xorm.Cell) {
  1105. var err error
  1106. switch colName {
  1107. case "id":
  1108. c.Attachments, err = GetAttachmentsByCommentID(c.ID)
  1109. if err != nil {
  1110. log.Error(3, "GetAttachmentsByCommentID[%d]: %v", c.ID, err)
  1111. }
  1112. case "poster_id":
  1113. c.Poster, err = GetUserByID(c.PosterID)
  1114. if err != nil {
  1115. if IsErrUserNotExist(err) {
  1116. c.PosterID = -1
  1117. c.Poster = NewFakeUser()
  1118. } else {
  1119. log.Error(3, "GetUserByID[%d]: %v", c.ID, err)
  1120. }
  1121. }
  1122. case "created":
  1123. c.Created = regulateTimeZone(c.Created)
  1124. }
  1125. }
  1126. func (c *Comment) AfterDelete() {
  1127. _, err := DeleteAttachmentsByComment(c.ID, true)
  1128. if err != nil {
  1129. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  1130. }
  1131. }
  1132. // HashTag returns unique hash tag for comment.
  1133. func (c *Comment) HashTag() string {
  1134. return "issuecomment-" + com.ToStr(c.ID)
  1135. }
  1136. // EventTag returns unique event hash tag for comment.
  1137. func (c *Comment) EventTag() string {
  1138. return "event-" + com.ToStr(c.ID)
  1139. }
  1140. func createComment(e *xorm.Session, u *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content, commitSHA string, uuids []string) (_ *Comment, err error) {
  1141. comment := &Comment{
  1142. PosterID: u.Id,
  1143. Type: cmtType,
  1144. IssueID: issue.ID,
  1145. CommitID: commitID,
  1146. Line: line,
  1147. Content: content,
  1148. CommitSHA: commitSHA,
  1149. }
  1150. if _, err = e.Insert(comment); err != nil {
  1151. return nil, err
  1152. }
  1153. // Compose comment action, could be plain comment, close or reopen issue.
  1154. // This object will be used to notify watchers in the end of function.
  1155. act := &Action{
  1156. ActUserID: u.Id,
  1157. ActUserName: u.Name,
  1158. ActEmail: u.Email,
  1159. Content: fmt.Sprintf("%d|%s", issue.Index, strings.Split(content, "\n")[0]),
  1160. RepoID: repo.ID,
  1161. RepoUserName: repo.Owner.Name,
  1162. RepoName: repo.Name,
  1163. IsPrivate: repo.IsPrivate,
  1164. }
  1165. // Check comment type.
  1166. switch cmtType {
  1167. case COMMENT_TYPE_COMMENT:
  1168. act.OpType = ACTION_COMMENT_ISSUE
  1169. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", issue.ID); err != nil {
  1170. return nil, err
  1171. }
  1172. // Check attachments.
  1173. attachments := make([]*Attachment, 0, len(uuids))
  1174. for _, uuid := range uuids {
  1175. attach, err := getAttachmentByUUID(e, uuid)
  1176. if err != nil {
  1177. if IsErrAttachmentNotExist(err) {
  1178. continue
  1179. }
  1180. return nil, fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  1181. }
  1182. attachments = append(attachments, attach)
  1183. }
  1184. for i := range attachments {
  1185. attachments[i].IssueID = issue.ID
  1186. attachments[i].CommentID = comment.ID
  1187. // No assign value could be 0, so ignore AllCols().
  1188. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  1189. return nil, fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  1190. }
  1191. }
  1192. case COMMENT_TYPE_REOPEN:
  1193. act.OpType = ACTION_REOPEN_ISSUE
  1194. if issue.IsPull {
  1195. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls-1 WHERE id=?", repo.ID)
  1196. } else {
  1197. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", repo.ID)
  1198. }
  1199. if err != nil {
  1200. return nil, err
  1201. }
  1202. case COMMENT_TYPE_CLOSE:
  1203. act.OpType = ACTION_CLOSE_ISSUE
  1204. if issue.IsPull {
  1205. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls+1 WHERE id=?", repo.ID)
  1206. } else {
  1207. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", repo.ID)
  1208. }
  1209. if err != nil {
  1210. return nil, err
  1211. }
  1212. }
  1213. // Notify watchers for whatever action comes in.
  1214. if err = notifyWatchers(e, act); err != nil {
  1215. return nil, fmt.Errorf("notifyWatchers: %v", err)
  1216. }
  1217. return comment, nil
  1218. }
  1219. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  1220. cmtType := COMMENT_TYPE_CLOSE
  1221. if !issue.IsClosed {
  1222. cmtType = COMMENT_TYPE_REOPEN
  1223. }
  1224. return createComment(e, doer, repo, issue, 0, 0, cmtType, "", "", nil)
  1225. }
  1226. // CreateComment creates comment of issue or commit.
  1227. func CreateComment(doer *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content, commitSHA string, attachments []string) (comment *Comment, err error) {
  1228. sess := x.NewSession()
  1229. defer sessionRelease(sess)
  1230. if err = sess.Begin(); err != nil {
  1231. return nil, err
  1232. }
  1233. comment, err = createComment(sess, doer, repo, issue, commitID, line, cmtType, content, commitSHA, attachments)
  1234. if err != nil {
  1235. return nil, err
  1236. }
  1237. return comment, sess.Commit()
  1238. }
  1239. // CreateIssueComment creates a plain issue comment.
  1240. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  1241. return CreateComment(doer, repo, issue, 0, 0, COMMENT_TYPE_COMMENT, content, "", attachments)
  1242. }
  1243. // CreateRefComment creates a commit reference comment to issue.
  1244. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  1245. if len(commitSHA) == 0 {
  1246. return fmt.Errorf("cannot create reference with empty commit SHA")
  1247. }
  1248. // Check if same reference from same commit has already existed.
  1249. has, err := x.Get(&Comment{
  1250. Type: COMMENT_TYPE_COMMIT_REF,
  1251. IssueID: issue.ID,
  1252. CommitSHA: commitSHA,
  1253. })
  1254. if err != nil {
  1255. return fmt.Errorf("check reference comment: %v", err)
  1256. } else if has {
  1257. return nil
  1258. }
  1259. _, err = CreateComment(doer, repo, issue, 0, 0, COMMENT_TYPE_COMMIT_REF, content, commitSHA, nil)
  1260. return err
  1261. }
  1262. // GetCommentByID returns the comment by given ID.
  1263. func GetCommentByID(id int64) (*Comment, error) {
  1264. c := new(Comment)
  1265. has, err := x.Id(id).Get(c)
  1266. if err != nil {
  1267. return nil, err
  1268. } else if !has {
  1269. return nil, ErrCommentNotExist{id}
  1270. }
  1271. return c, nil
  1272. }
  1273. // GetCommentsByIssueID returns all comments of issue by given ID.
  1274. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  1275. comments := make([]*Comment, 0, 10)
  1276. return comments, x.Where("issue_id=?", issueID).Asc("created").Find(&comments)
  1277. }
  1278. // UpdateComment updates information of comment.
  1279. func UpdateComment(c *Comment) error {
  1280. _, err := x.Id(c.ID).AllCols().Update(c)
  1281. return err
  1282. }
  1283. // Attachment represent a attachment of issue/comment/release.
  1284. type Attachment struct {
  1285. ID int64 `xorm:"pk autoincr"`
  1286. UUID string `xorm:"uuid UNIQUE"`
  1287. IssueID int64 `xorm:"INDEX"`
  1288. CommentID int64
  1289. ReleaseID int64 `xorm:"INDEX"`
  1290. Name string
  1291. Created time.Time `xorm:"CREATED"`
  1292. }
  1293. // AttachmentLocalPath returns where attachment is stored in local file system based on given UUID.
  1294. func AttachmentLocalPath(uuid string) string {
  1295. return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid)
  1296. }
  1297. // LocalPath returns where attachment is stored in local file system.
  1298. func (attach *Attachment) LocalPath() string {
  1299. return AttachmentLocalPath(attach.UUID)
  1300. }
  1301. // NewAttachment creates a new attachment object.
  1302. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) {
  1303. attach := &Attachment{
  1304. UUID: gouuid.NewV4().String(),
  1305. Name: name,
  1306. }
  1307. if err = os.MkdirAll(path.Dir(attach.LocalPath()), os.ModePerm); err != nil {
  1308. return nil, fmt.Errorf("MkdirAll: %v", err)
  1309. }
  1310. fw, err := os.Create(attach.LocalPath())
  1311. if err != nil {
  1312. return nil, fmt.Errorf("Create: %v", err)
  1313. }
  1314. defer fw.Close()
  1315. if _, err = fw.Write(buf); err != nil {
  1316. return nil, fmt.Errorf("Write: %v", err)
  1317. } else if _, err = io.Copy(fw, file); err != nil {
  1318. return nil, fmt.Errorf("Copy: %v", err)
  1319. }
  1320. sess := x.NewSession()
  1321. defer sessionRelease(sess)
  1322. if err := sess.Begin(); err != nil {
  1323. return nil, err
  1324. }
  1325. if _, err := sess.Insert(attach); err != nil {
  1326. return nil, err
  1327. }
  1328. return attach, sess.Commit()
  1329. }
  1330. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  1331. attach := &Attachment{UUID: uuid}
  1332. has, err := x.Get(attach)
  1333. if err != nil {
  1334. return nil, err
  1335. } else if !has {
  1336. return nil, ErrAttachmentNotExist{0, uuid}
  1337. }
  1338. return attach, nil
  1339. }
  1340. // GetAttachmentByUUID returns attachment by given UUID.
  1341. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  1342. return getAttachmentByUUID(x, uuid)
  1343. }
  1344. // GetAttachmentsByIssueID returns all attachments for given issue by ID.
  1345. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  1346. attachments := make([]*Attachment, 0, 10)
  1347. return attachments, x.Where("issue_id=? AND comment_id=0", issueID).Find(&attachments)
  1348. }
  1349. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  1350. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  1351. attachments := make([]*Attachment, 0, 10)
  1352. return attachments, x.Where("comment_id=?", commentID).Find(&attachments)
  1353. }
  1354. // DeleteAttachment deletes the given attachment and optionally the associated file.
  1355. func DeleteAttachment(a *Attachment, remove bool) error {
  1356. _, err := DeleteAttachments([]*Attachment{a}, remove)
  1357. return err
  1358. }
  1359. // DeleteAttachments deletes the given attachments and optionally the associated files.
  1360. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  1361. for i, a := range attachments {
  1362. if remove {
  1363. if err := os.Remove(a.LocalPath()); err != nil {
  1364. return i, err
  1365. }
  1366. }
  1367. if _, err := x.Delete(a.ID); err != nil {
  1368. return i, err
  1369. }
  1370. }
  1371. return len(attachments), nil
  1372. }
  1373. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  1374. func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
  1375. attachments, err := GetAttachmentsByIssueID(issueId)
  1376. if err != nil {
  1377. return 0, err
  1378. }
  1379. return DeleteAttachments(attachments, remove)
  1380. }
  1381. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  1382. func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
  1383. attachments, err := GetAttachmentsByCommentID(commentId)
  1384. if err != nil {
  1385. return 0, err
  1386. }
  1387. return DeleteAttachments(attachments, remove)
  1388. }