issue.go 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837
  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. "github.com/gogits/gogs/modules/base"
  18. "github.com/gogits/gogs/modules/log"
  19. "github.com/gogits/gogs/modules/setting"
  20. gouuid "github.com/gogits/gogs/modules/uuid"
  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, 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, i.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, 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, 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. var label *Label
  252. for _, id := range labelIDs {
  253. if id == 0 {
  254. continue
  255. }
  256. label, err = getLabelByID(e, id)
  257. if err != nil {
  258. return err
  259. }
  260. if err = issue.addLabel(e, label); err != nil {
  261. return fmt.Errorf("addLabel: %v", err)
  262. }
  263. }
  264. if issue.MilestoneID > 0 {
  265. if err = changeMilestoneAssign(e, 0, issue); err != nil {
  266. return err
  267. }
  268. }
  269. if err = newIssueUsers(e, repo, issue); err != nil {
  270. return err
  271. }
  272. // Check attachments.
  273. attachments := make([]*Attachment, 0, len(uuids))
  274. for _, uuid := range uuids {
  275. attach, err := getAttachmentByUUID(e, uuid)
  276. if err != nil {
  277. if IsErrAttachmentNotExist(err) {
  278. continue
  279. }
  280. return fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  281. }
  282. attachments = append(attachments, attach)
  283. }
  284. for i := range attachments {
  285. attachments[i].IssueID = issue.ID
  286. // No assign value could be 0, so ignore AllCols().
  287. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  288. return fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  289. }
  290. }
  291. return nil
  292. }
  293. // NewIssue creates new issue with labels for repository.
  294. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  295. sess := x.NewSession()
  296. defer sessionRelease(sess)
  297. if err = sess.Begin(); err != nil {
  298. return err
  299. }
  300. if err = newIssue(sess, repo, issue, labelIDs, uuids, false); err != nil {
  301. return fmt.Errorf("newIssue: %v", err)
  302. }
  303. // Notify watchers.
  304. act := &Action{
  305. ActUserID: issue.Poster.Id,
  306. ActUserName: issue.Poster.Name,
  307. ActEmail: issue.Poster.Email,
  308. OpType: CREATE_ISSUE,
  309. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Name),
  310. RepoID: repo.ID,
  311. RepoUserName: repo.Owner.Name,
  312. RepoName: repo.Name,
  313. IsPrivate: repo.IsPrivate,
  314. }
  315. if err = notifyWatchers(sess, act); err != nil {
  316. return err
  317. }
  318. return sess.Commit()
  319. }
  320. // GetIssueByRef returns an Issue specified by a GFM reference.
  321. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  322. func GetIssueByRef(ref string) (*Issue, error) {
  323. n := strings.IndexByte(ref, byte('#'))
  324. if n == -1 {
  325. return nil, ErrMissingIssueNumber
  326. }
  327. index, err := com.StrTo(ref[n+1:]).Int64()
  328. if err != nil {
  329. return nil, err
  330. }
  331. repo, err := GetRepositoryByRef(ref[:n])
  332. if err != nil {
  333. return nil, err
  334. }
  335. issue, err := GetIssueByIndex(repo.ID, index)
  336. if err != nil {
  337. return nil, err
  338. }
  339. issue.Repo = repo
  340. return issue, nil
  341. }
  342. // GetIssueByIndex returns issue by given index in repository.
  343. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  344. issue := &Issue{
  345. RepoID: repoID,
  346. Index: index,
  347. }
  348. has, err := x.Get(issue)
  349. if err != nil {
  350. return nil, err
  351. } else if !has {
  352. return nil, ErrIssueNotExist{0, repoID, index}
  353. }
  354. return issue, nil
  355. }
  356. // GetIssueByID returns an issue by given ID.
  357. func GetIssueByID(id int64) (*Issue, error) {
  358. issue := new(Issue)
  359. has, err := x.Id(id).Get(issue)
  360. if err != nil {
  361. return nil, err
  362. } else if !has {
  363. return nil, ErrIssueNotExist{id, 0, 0}
  364. }
  365. return issue, nil
  366. }
  367. type IssuesOptions struct {
  368. UserID int64
  369. AssigneeID int64
  370. RepoID int64
  371. PosterID int64
  372. MilestoneID int64
  373. RepoIDs []int64
  374. Page int
  375. IsClosed bool
  376. IsMention bool
  377. IsPull bool
  378. Labels string
  379. SortType string
  380. }
  381. // Issues returns a list of issues by given conditions.
  382. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  383. sess := x.Limit(setting.IssuePagingNum, (opts.Page-1)*setting.IssuePagingNum)
  384. if opts.RepoID > 0 {
  385. sess.Where("issue.repo_id=?", opts.RepoID).And("issue.is_closed=?", opts.IsClosed)
  386. } else if opts.RepoIDs != nil {
  387. // In case repository IDs are provided but actually no repository has issue.
  388. if len(opts.RepoIDs) == 0 {
  389. return make([]*Issue, 0), nil
  390. }
  391. sess.Where("issue.repo_id IN ("+strings.Join(base.Int64sToStrings(opts.RepoIDs), ",")+")").And("issue.is_closed=?", opts.IsClosed)
  392. } else {
  393. sess.Where("issue.is_closed=?", opts.IsClosed)
  394. }
  395. if opts.AssigneeID > 0 {
  396. sess.And("issue.assignee_id=?", opts.AssigneeID)
  397. } else if opts.PosterID > 0 {
  398. sess.And("issue.poster_id=?", opts.PosterID)
  399. }
  400. if opts.MilestoneID > 0 {
  401. sess.And("issue.milestone_id=?", opts.MilestoneID)
  402. }
  403. sess.And("issue.is_pull=?", opts.IsPull)
  404. switch opts.SortType {
  405. case "oldest":
  406. sess.Asc("created")
  407. case "recentupdate":
  408. sess.Desc("updated")
  409. case "leastupdate":
  410. sess.Asc("updated")
  411. case "mostcomment":
  412. sess.Desc("num_comments")
  413. case "leastcomment":
  414. sess.Asc("num_comments")
  415. case "priority":
  416. sess.Desc("priority")
  417. default:
  418. sess.Desc("created")
  419. }
  420. labelIDs := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  421. if len(labelIDs) > 0 {
  422. validJoin := false
  423. queryStr := "issue.id=issue_label.issue_id"
  424. for _, id := range labelIDs {
  425. if id == 0 {
  426. continue
  427. }
  428. validJoin = true
  429. queryStr += " AND issue_label.label_id=" + com.ToStr(id)
  430. }
  431. if validJoin {
  432. sess.Join("INNER", "issue_label", queryStr)
  433. }
  434. }
  435. if opts.IsMention {
  436. queryStr := "issue.id=issue_user.issue_id AND issue_user.is_mentioned=1"
  437. if opts.UserID > 0 {
  438. queryStr += " AND issue_user.uid=" + com.ToStr(opts.UserID)
  439. }
  440. sess.Join("INNER", "issue_user", queryStr)
  441. }
  442. issues := make([]*Issue, 0, setting.IssuePagingNum)
  443. return issues, sess.Find(&issues)
  444. }
  445. type IssueStatus int
  446. const (
  447. IS_OPEN = iota + 1
  448. IS_CLOSE
  449. )
  450. // GetIssueCountByPoster returns number of issues of repository by poster.
  451. func GetIssueCountByPoster(uid, rid int64, isClosed bool) int64 {
  452. count, _ := x.Where("repo_id=?", rid).And("poster_id=?", uid).And("is_closed=?", isClosed).Count(new(Issue))
  453. return count
  454. }
  455. // .___ ____ ___
  456. // | | ______ ________ __ ____ | | \______ ___________
  457. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  458. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  459. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  460. // \/ \/ \/ \/ \/
  461. // IssueUser represents an issue-user relation.
  462. type IssueUser struct {
  463. ID int64 `xorm:"pk autoincr"`
  464. UID int64 `xorm:"INDEX"` // User ID.
  465. IssueID int64
  466. RepoID int64 `xorm:"INDEX"`
  467. MilestoneID int64
  468. IsRead bool
  469. IsAssigned bool
  470. IsMentioned bool
  471. IsPoster bool
  472. IsClosed bool
  473. }
  474. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  475. users, err := repo.GetAssignees()
  476. if err != nil {
  477. return err
  478. }
  479. iu := &IssueUser{
  480. IssueID: issue.ID,
  481. RepoID: repo.ID,
  482. }
  483. // Poster can be anyone.
  484. isNeedAddPoster := true
  485. for _, u := range users {
  486. iu.ID = 0
  487. iu.UID = u.Id
  488. iu.IsPoster = iu.UID == issue.PosterID
  489. if isNeedAddPoster && iu.IsPoster {
  490. isNeedAddPoster = false
  491. }
  492. iu.IsAssigned = iu.UID == issue.AssigneeID
  493. if _, err = e.Insert(iu); err != nil {
  494. return err
  495. }
  496. }
  497. if isNeedAddPoster {
  498. iu.ID = 0
  499. iu.UID = issue.PosterID
  500. iu.IsPoster = true
  501. if _, err = e.Insert(iu); err != nil {
  502. return err
  503. }
  504. }
  505. return nil
  506. }
  507. // NewIssueUsers adds new issue-user relations for new issue of repository.
  508. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  509. sess := x.NewSession()
  510. defer sessionRelease(sess)
  511. if err = sess.Begin(); err != nil {
  512. return err
  513. }
  514. if err = newIssueUsers(sess, repo, issue); err != nil {
  515. return err
  516. }
  517. return sess.Commit()
  518. }
  519. // PairsContains returns true when pairs list contains given issue.
  520. func PairsContains(ius []*IssueUser, issueId, uid int64) int {
  521. for i := range ius {
  522. if ius[i].IssueID == issueId &&
  523. ius[i].UID == uid {
  524. return i
  525. }
  526. }
  527. return -1
  528. }
  529. // GetIssueUsers returns issue-user pairs by given repository and user.
  530. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  531. ius := make([]*IssueUser, 0, 10)
  532. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  533. return ius, err
  534. }
  535. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  536. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  537. if len(rids) == 0 {
  538. return []*IssueUser{}, nil
  539. }
  540. buf := bytes.NewBufferString("")
  541. for _, rid := range rids {
  542. buf.WriteString("repo_id=")
  543. buf.WriteString(com.ToStr(rid))
  544. buf.WriteString(" OR ")
  545. }
  546. cond := strings.TrimSuffix(buf.String(), " OR ")
  547. ius := make([]*IssueUser, 0, 10)
  548. sess := x.Limit(20, (page-1)*20).Where("is_closed=?", isClosed)
  549. if len(cond) > 0 {
  550. sess.And(cond)
  551. }
  552. err := sess.Find(&ius)
  553. return ius, err
  554. }
  555. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  556. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  557. ius := make([]*IssueUser, 0, 10)
  558. sess := x.Limit(20, (page-1)*20).Where("uid=?", uid).And("is_closed=?", isClosed)
  559. if rid > 0 {
  560. sess.And("repo_id=?", rid)
  561. }
  562. switch filterMode {
  563. case FM_ASSIGN:
  564. sess.And("is_assigned=?", true)
  565. case FM_CREATE:
  566. sess.And("is_poster=?", true)
  567. default:
  568. return ius, nil
  569. }
  570. err := sess.Find(&ius)
  571. return ius, err
  572. }
  573. func UpdateMentions(userNames []string, issueId int64) error {
  574. for i := range userNames {
  575. userNames[i] = strings.ToLower(userNames[i])
  576. }
  577. users := make([]*User, 0, len(userNames))
  578. if err := x.Where("lower_name IN (?)", strings.Join(userNames, "\",\"")).OrderBy("lower_name ASC").Find(&users); err != nil {
  579. return err
  580. }
  581. ids := make([]int64, 0, len(userNames))
  582. for _, user := range users {
  583. ids = append(ids, user.Id)
  584. if !user.IsOrganization() {
  585. continue
  586. }
  587. if user.NumMembers == 0 {
  588. continue
  589. }
  590. tempIds := make([]int64, 0, user.NumMembers)
  591. orgUsers, err := GetOrgUsersByOrgId(user.Id)
  592. if err != nil {
  593. return err
  594. }
  595. for _, orgUser := range orgUsers {
  596. tempIds = append(tempIds, orgUser.ID)
  597. }
  598. ids = append(ids, tempIds...)
  599. }
  600. if err := UpdateIssueUsersByMentions(ids, issueId); err != nil {
  601. return err
  602. }
  603. return nil
  604. }
  605. // IssueStats represents issue statistic information.
  606. type IssueStats struct {
  607. OpenCount, ClosedCount int64
  608. AllCount int64
  609. AssignCount int64
  610. CreateCount int64
  611. MentionCount int64
  612. }
  613. // Filter modes.
  614. const (
  615. FM_ALL = iota
  616. FM_ASSIGN
  617. FM_CREATE
  618. FM_MENTION
  619. )
  620. func parseCountResult(results []map[string][]byte) int64 {
  621. if len(results) == 0 {
  622. return 0
  623. }
  624. for _, result := range results[0] {
  625. return com.StrTo(string(result)).MustInt64()
  626. }
  627. return 0
  628. }
  629. type IssueStatsOptions struct {
  630. RepoID int64
  631. UserID int64
  632. LabelID int64
  633. MilestoneID int64
  634. AssigneeID int64
  635. FilterMode int
  636. IsPull bool
  637. }
  638. // GetIssueStats returns issue statistic information by given conditions.
  639. func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
  640. stats := &IssueStats{}
  641. queryStr := "SELECT COUNT(*) FROM `issue` "
  642. if opts.LabelID > 0 {
  643. queryStr += "INNER JOIN `issue_label` ON `issue`.id=`issue_label`.issue_id AND `issue_label`.label_id=" + com.ToStr(opts.LabelID)
  644. }
  645. baseCond := " WHERE issue.repo_id=" + com.ToStr(opts.RepoID) + " AND issue.is_closed=?"
  646. if opts.MilestoneID > 0 {
  647. baseCond += " AND issue.milestone_id=" + com.ToStr(opts.MilestoneID)
  648. }
  649. if opts.AssigneeID > 0 {
  650. baseCond += " AND assignee_id=" + com.ToStr(opts.AssigneeID)
  651. }
  652. baseCond += " AND issue.is_pull=?"
  653. switch opts.FilterMode {
  654. case FM_ALL, FM_ASSIGN:
  655. results, _ := x.Query(queryStr+baseCond, false, opts.IsPull)
  656. stats.OpenCount = parseCountResult(results)
  657. results, _ = x.Query(queryStr+baseCond, true, opts.IsPull)
  658. stats.ClosedCount = parseCountResult(results)
  659. case FM_CREATE:
  660. baseCond += " AND poster_id=?"
  661. results, _ := x.Query(queryStr+baseCond, false, opts.IsPull, opts.UserID)
  662. stats.OpenCount = parseCountResult(results)
  663. results, _ = x.Query(queryStr+baseCond, true, opts.IsPull, opts.UserID)
  664. stats.ClosedCount = parseCountResult(results)
  665. case FM_MENTION:
  666. queryStr += " INNER JOIN `issue_user` ON `issue`.id=`issue_user`.issue_id"
  667. baseCond += " AND `issue_user`.uid=? AND `issue_user`.is_mentioned=?"
  668. results, _ := x.Query(queryStr+baseCond, false, opts.IsPull, opts.UserID, true)
  669. stats.OpenCount = parseCountResult(results)
  670. results, _ = x.Query(queryStr+baseCond, true, opts.IsPull, opts.UserID, true)
  671. stats.ClosedCount = parseCountResult(results)
  672. }
  673. return stats
  674. }
  675. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  676. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  677. stats := &IssueStats{}
  678. queryStr := "SELECT COUNT(*) FROM `issue` "
  679. baseCond := " WHERE issue.is_closed=?"
  680. if repoID > 0 || len(repoIDs) == 0 {
  681. baseCond += " AND issue.repo_id=" + com.ToStr(repoID)
  682. } else {
  683. baseCond += " AND issue.repo_id IN (" + strings.Join(base.Int64sToStrings(repoIDs), ",") + ")"
  684. }
  685. if isPull {
  686. baseCond += " AND issue.is_pull=1"
  687. } else {
  688. baseCond += " AND issue.is_pull=0"
  689. }
  690. results, _ := x.Query(queryStr+baseCond+" AND assignee_id=?", false, uid)
  691. stats.AssignCount = parseCountResult(results)
  692. results, _ = x.Query(queryStr+baseCond+" AND poster_id=?", false, uid)
  693. stats.CreateCount = parseCountResult(results)
  694. switch filterMode {
  695. case FM_ASSIGN:
  696. baseCond += " AND assignee_id=" + com.ToStr(uid)
  697. case FM_CREATE:
  698. baseCond += " AND poster_id=" + com.ToStr(uid)
  699. }
  700. results, _ = x.Query(queryStr+baseCond, false)
  701. stats.OpenCount = parseCountResult(results)
  702. results, _ = x.Query(queryStr+baseCond, true)
  703. stats.ClosedCount = parseCountResult(results)
  704. return stats
  705. }
  706. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  707. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  708. queryStr := "SELECT COUNT(*) FROM `issue` "
  709. baseCond := " WHERE issue.repo_id=? AND issue.is_closed=?"
  710. if isPull {
  711. baseCond += " AND issue.is_pull=1"
  712. } else {
  713. baseCond += " AND issue.is_pull=0"
  714. }
  715. switch filterMode {
  716. case FM_ASSIGN:
  717. baseCond += " AND assignee_id=" + com.ToStr(uid)
  718. case FM_CREATE:
  719. baseCond += " AND poster_id=" + com.ToStr(uid)
  720. }
  721. results, _ := x.Query(queryStr+baseCond, repoID, false)
  722. numOpen = parseCountResult(results)
  723. results, _ = x.Query(queryStr+baseCond, repoID, true)
  724. numClosed = parseCountResult(results)
  725. return numOpen, numClosed
  726. }
  727. func updateIssue(e Engine, issue *Issue) error {
  728. _, err := e.Id(issue.ID).AllCols().Update(issue)
  729. return err
  730. }
  731. // UpdateIssue updates all fields of given issue.
  732. func UpdateIssue(issue *Issue) error {
  733. return updateIssue(x, issue)
  734. }
  735. // updateIssueCols updates specific fields of given issue.
  736. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  737. _, err := e.Id(issue.ID).Cols(cols...).Update(issue)
  738. return err
  739. }
  740. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  741. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  742. return err
  743. }
  744. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  745. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  746. return updateIssueUsersByStatus(x, issueID, isClosed)
  747. }
  748. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  749. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE issue_id=?", false, issue.ID); err != nil {
  750. return err
  751. }
  752. // Assignee ID equals to 0 means clear assignee.
  753. if issue.AssigneeID > 0 {
  754. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE uid=? AND issue_id=?", true, issue.AssigneeID, issue.ID); err != nil {
  755. return err
  756. }
  757. }
  758. return updateIssue(e, issue)
  759. }
  760. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  761. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  762. sess := x.NewSession()
  763. defer sessionRelease(sess)
  764. if err = sess.Begin(); err != nil {
  765. return err
  766. }
  767. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  768. return err
  769. }
  770. return sess.Commit()
  771. }
  772. // UpdateIssueUserByRead updates issue-user relation for reading.
  773. func UpdateIssueUserByRead(uid, issueID int64) error {
  774. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  775. return err
  776. }
  777. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
  778. func UpdateIssueUsersByMentions(uids []int64, iid int64) error {
  779. for _, uid := range uids {
  780. iu := &IssueUser{UID: uid, IssueID: iid}
  781. has, err := x.Get(iu)
  782. if err != nil {
  783. return err
  784. }
  785. iu.IsMentioned = true
  786. if has {
  787. _, err = x.Id(iu.ID).AllCols().Update(iu)
  788. } else {
  789. _, err = x.Insert(iu)
  790. }
  791. if err != nil {
  792. return err
  793. }
  794. }
  795. return nil
  796. }
  797. // .____ ___. .__
  798. // | | _____ \_ |__ ____ | |
  799. // | | \__ \ | __ \_/ __ \| |
  800. // | |___ / __ \| \_\ \ ___/| |__
  801. // |_______ (____ /___ /\___ >____/
  802. // \/ \/ \/ \/
  803. // Label represents a label of repository for issues.
  804. type Label struct {
  805. ID int64 `xorm:"pk autoincr"`
  806. RepoID int64 `xorm:"INDEX"`
  807. Name string
  808. Color string `xorm:"VARCHAR(7)"`
  809. NumIssues int
  810. NumClosedIssues int
  811. NumOpenIssues int `xorm:"-"`
  812. IsChecked bool `xorm:"-"`
  813. }
  814. // CalOpenIssues calculates the open issues of label.
  815. func (m *Label) CalOpenIssues() {
  816. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  817. }
  818. // NewLabel creates new label of repository.
  819. func NewLabel(l *Label) error {
  820. _, err := x.Insert(l)
  821. return err
  822. }
  823. func getLabelByID(e Engine, id int64) (*Label, error) {
  824. if id <= 0 {
  825. return nil, ErrLabelNotExist{id}
  826. }
  827. l := &Label{ID: id}
  828. has, err := x.Get(l)
  829. if err != nil {
  830. return nil, err
  831. } else if !has {
  832. return nil, ErrLabelNotExist{l.ID}
  833. }
  834. return l, nil
  835. }
  836. // GetLabelByID returns a label by given ID.
  837. func GetLabelByID(id int64) (*Label, error) {
  838. return getLabelByID(x, id)
  839. }
  840. // GetLabelsByRepoID returns all labels that belong to given repository by ID.
  841. func GetLabelsByRepoID(repoID int64) ([]*Label, error) {
  842. labels := make([]*Label, 0, 10)
  843. return labels, x.Where("repo_id=?", repoID).Find(&labels)
  844. }
  845. func getLabelsByIssueID(e Engine, issueID int64) ([]*Label, error) {
  846. issueLabels, err := getIssueLabels(e, issueID)
  847. if err != nil {
  848. return nil, fmt.Errorf("getIssueLabels: %v", err)
  849. }
  850. var label *Label
  851. labels := make([]*Label, 0, len(issueLabels))
  852. for idx := range issueLabels {
  853. label, err = getLabelByID(e, issueLabels[idx].LabelID)
  854. if err != nil && !IsErrLabelNotExist(err) {
  855. return nil, fmt.Errorf("getLabelByID: %v", err)
  856. }
  857. labels = append(labels, label)
  858. }
  859. return labels, nil
  860. }
  861. // GetLabelsByIssueID returns all labels that belong to given issue by ID.
  862. func GetLabelsByIssueID(issueID int64) ([]*Label, error) {
  863. return getLabelsByIssueID(x, issueID)
  864. }
  865. func updateLabel(e Engine, l *Label) error {
  866. _, err := e.Id(l.ID).AllCols().Update(l)
  867. return err
  868. }
  869. // UpdateLabel updates label information.
  870. func UpdateLabel(l *Label) error {
  871. return updateLabel(x, l)
  872. }
  873. // DeleteLabel delete a label of given repository.
  874. func DeleteLabel(repoID, labelID int64) error {
  875. l, err := GetLabelByID(labelID)
  876. if err != nil {
  877. if IsErrLabelNotExist(err) {
  878. return nil
  879. }
  880. return err
  881. }
  882. sess := x.NewSession()
  883. defer sessionRelease(sess)
  884. if err = sess.Begin(); err != nil {
  885. return err
  886. }
  887. if _, err = x.Where("label_id=?", labelID).Delete(new(IssueLabel)); err != nil {
  888. return err
  889. } else if _, err = sess.Delete(l); err != nil {
  890. return err
  891. }
  892. return sess.Commit()
  893. }
  894. // .___ .____ ___. .__
  895. // | | ______ ________ __ ____ | | _____ \_ |__ ____ | |
  896. // | |/ ___// ___/ | \_/ __ \| | \__ \ | __ \_/ __ \| |
  897. // | |\___ \ \___ \| | /\ ___/| |___ / __ \| \_\ \ ___/| |__
  898. // |___/____ >____ >____/ \___ >_______ (____ /___ /\___ >____/
  899. // \/ \/ \/ \/ \/ \/ \/
  900. // IssueLabel represetns an issue-lable relation.
  901. type IssueLabel struct {
  902. ID int64 `xorm:"pk autoincr"`
  903. IssueID int64 `xorm:"UNIQUE(s)"`
  904. LabelID int64 `xorm:"UNIQUE(s)"`
  905. }
  906. func hasIssueLabel(e Engine, issueID, labelID int64) bool {
  907. has, _ := e.Where("issue_id=? AND label_id=?", issueID, labelID).Get(new(IssueLabel))
  908. return has
  909. }
  910. // HasIssueLabel returns true if issue has been labeled.
  911. func HasIssueLabel(issueID, labelID int64) bool {
  912. return hasIssueLabel(x, issueID, labelID)
  913. }
  914. func newIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  915. if _, err = e.Insert(&IssueLabel{
  916. IssueID: issue.ID,
  917. LabelID: label.ID,
  918. }); err != nil {
  919. return err
  920. }
  921. label.NumIssues++
  922. if issue.IsClosed {
  923. label.NumClosedIssues++
  924. }
  925. return updateLabel(e, label)
  926. }
  927. // NewIssueLabel creates a new issue-label relation.
  928. func NewIssueLabel(issue *Issue, label *Label) (err error) {
  929. sess := x.NewSession()
  930. defer sessionRelease(sess)
  931. if err = sess.Begin(); err != nil {
  932. return err
  933. }
  934. if err = newIssueLabel(sess, issue, label); err != nil {
  935. return err
  936. }
  937. return sess.Commit()
  938. }
  939. func getIssueLabels(e Engine, issueID int64) ([]*IssueLabel, error) {
  940. issueLabels := make([]*IssueLabel, 0, 10)
  941. return issueLabels, e.Where("issue_id=?", issueID).Asc("label_id").Find(&issueLabels)
  942. }
  943. // GetIssueLabels returns all issue-label relations of given issue by ID.
  944. func GetIssueLabels(issueID int64) ([]*IssueLabel, error) {
  945. return getIssueLabels(x, issueID)
  946. }
  947. func deleteIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  948. if _, err = e.Delete(&IssueLabel{
  949. IssueID: issue.ID,
  950. LabelID: label.ID,
  951. }); err != nil {
  952. return err
  953. }
  954. label.NumIssues--
  955. if issue.IsClosed {
  956. label.NumClosedIssues--
  957. }
  958. return updateLabel(e, label)
  959. }
  960. // DeleteIssueLabel deletes issue-label relation.
  961. func DeleteIssueLabel(issue *Issue, label *Label) (err error) {
  962. sess := x.NewSession()
  963. defer sessionRelease(sess)
  964. if err = sess.Begin(); err != nil {
  965. return err
  966. }
  967. if err = deleteIssueLabel(sess, issue, label); err != nil {
  968. return err
  969. }
  970. return sess.Commit()
  971. }
  972. // _____ .__.__ __
  973. // / \ |__| | ____ _______/ |_ ____ ____ ____
  974. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  975. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  976. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  977. // \/ \/ \/ \/ \/
  978. // Milestone represents a milestone of repository.
  979. type Milestone struct {
  980. ID int64 `xorm:"pk autoincr"`
  981. RepoID int64 `xorm:"INDEX"`
  982. Name string
  983. Content string `xorm:"TEXT"`
  984. RenderedContent string `xorm:"-"`
  985. IsClosed bool
  986. NumIssues int
  987. NumClosedIssues int
  988. NumOpenIssues int `xorm:"-"`
  989. Completeness int // Percentage(1-100).
  990. Deadline time.Time
  991. DeadlineString string `xorm:"-"`
  992. IsOverDue bool `xorm:"-"`
  993. ClosedDate time.Time
  994. }
  995. func (m *Milestone) BeforeUpdate() {
  996. if m.NumIssues > 0 {
  997. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  998. } else {
  999. m.Completeness = 0
  1000. }
  1001. }
  1002. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  1003. if colName == "deadline" {
  1004. if m.Deadline.Year() == 9999 {
  1005. return
  1006. }
  1007. m.DeadlineString = m.Deadline.Format("2006-01-02")
  1008. if time.Now().After(m.Deadline) {
  1009. m.IsOverDue = true
  1010. }
  1011. }
  1012. }
  1013. // CalOpenIssues calculates the open issues of milestone.
  1014. func (m *Milestone) CalOpenIssues() {
  1015. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  1016. }
  1017. // NewMilestone creates new milestone of repository.
  1018. func NewMilestone(m *Milestone) (err error) {
  1019. sess := x.NewSession()
  1020. defer sessionRelease(sess)
  1021. if err = sess.Begin(); err != nil {
  1022. return err
  1023. }
  1024. if _, err = sess.Insert(m); err != nil {
  1025. return err
  1026. }
  1027. if _, err = sess.Exec("UPDATE `repository` SET num_milestones=num_milestones+1 WHERE id=?", m.RepoID); err != nil {
  1028. return err
  1029. }
  1030. return sess.Commit()
  1031. }
  1032. func getMilestoneByID(e Engine, id int64) (*Milestone, error) {
  1033. m := &Milestone{ID: id}
  1034. has, err := e.Get(m)
  1035. if err != nil {
  1036. return nil, err
  1037. } else if !has {
  1038. return nil, ErrMilestoneNotExist{id, 0}
  1039. }
  1040. return m, nil
  1041. }
  1042. // GetMilestoneByID returns the milestone of given ID.
  1043. func GetMilestoneByID(id int64) (*Milestone, error) {
  1044. return getMilestoneByID(x, id)
  1045. }
  1046. // GetRepoMilestoneByID returns the milestone of given ID and repository.
  1047. func GetRepoMilestoneByID(repoID, milestoneID int64) (*Milestone, error) {
  1048. m := &Milestone{ID: milestoneID, RepoID: repoID}
  1049. has, err := x.Get(m)
  1050. if err != nil {
  1051. return nil, err
  1052. } else if !has {
  1053. return nil, ErrMilestoneNotExist{milestoneID, repoID}
  1054. }
  1055. return m, nil
  1056. }
  1057. // GetAllRepoMilestones returns all milestones of given repository.
  1058. func GetAllRepoMilestones(repoID int64) ([]*Milestone, error) {
  1059. miles := make([]*Milestone, 0, 10)
  1060. return miles, x.Where("repo_id=?", repoID).Find(&miles)
  1061. }
  1062. // GetMilestones returns a list of milestones of given repository and status.
  1063. func GetMilestones(repoID int64, page int, isClosed bool) ([]*Milestone, error) {
  1064. miles := make([]*Milestone, 0, setting.IssuePagingNum)
  1065. sess := x.Where("repo_id=? AND is_closed=?", repoID, isClosed)
  1066. if page > 0 {
  1067. sess = sess.Limit(setting.IssuePagingNum, (page-1)*setting.IssuePagingNum)
  1068. }
  1069. return miles, sess.Find(&miles)
  1070. }
  1071. func updateMilestone(e Engine, m *Milestone) error {
  1072. _, err := e.Id(m.ID).AllCols().Update(m)
  1073. return err
  1074. }
  1075. // UpdateMilestone updates information of given milestone.
  1076. func UpdateMilestone(m *Milestone) error {
  1077. return updateMilestone(x, m)
  1078. }
  1079. func countRepoMilestones(e Engine, repoID int64) int64 {
  1080. count, _ := e.Where("repo_id=?", repoID).Count(new(Milestone))
  1081. return count
  1082. }
  1083. // CountRepoMilestones returns number of milestones in given repository.
  1084. func CountRepoMilestones(repoID int64) int64 {
  1085. return countRepoMilestones(x, repoID)
  1086. }
  1087. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  1088. closed, _ := e.Where("repo_id=? AND is_closed=?", repoID, true).Count(new(Milestone))
  1089. return closed
  1090. }
  1091. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  1092. func CountRepoClosedMilestones(repoID int64) int64 {
  1093. return countRepoClosedMilestones(x, repoID)
  1094. }
  1095. // MilestoneStats returns number of open and closed milestones of given repository.
  1096. func MilestoneStats(repoID int64) (open int64, closed int64) {
  1097. open, _ = x.Where("repo_id=? AND is_closed=?", repoID, false).Count(new(Milestone))
  1098. return open, CountRepoClosedMilestones(repoID)
  1099. }
  1100. // ChangeMilestoneStatus changes the milestone open/closed status.
  1101. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  1102. repo, err := GetRepositoryByID(m.RepoID)
  1103. if err != nil {
  1104. return err
  1105. }
  1106. sess := x.NewSession()
  1107. defer sessionRelease(sess)
  1108. if err = sess.Begin(); err != nil {
  1109. return err
  1110. }
  1111. m.IsClosed = isClosed
  1112. if err = updateMilestone(sess, m); err != nil {
  1113. return err
  1114. }
  1115. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1116. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1117. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1118. return err
  1119. }
  1120. return sess.Commit()
  1121. }
  1122. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  1123. if issue.MilestoneID == 0 {
  1124. return nil
  1125. }
  1126. m, err := getMilestoneByID(e, issue.MilestoneID)
  1127. if err != nil {
  1128. return err
  1129. }
  1130. if issue.IsClosed {
  1131. m.NumOpenIssues--
  1132. m.NumClosedIssues++
  1133. } else {
  1134. m.NumOpenIssues++
  1135. m.NumClosedIssues--
  1136. }
  1137. return updateMilestone(e, m)
  1138. }
  1139. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  1140. // for the milestone associated with the given issue.
  1141. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  1142. sess := x.NewSession()
  1143. defer sessionRelease(sess)
  1144. if err = sess.Begin(); err != nil {
  1145. return err
  1146. }
  1147. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  1148. return err
  1149. }
  1150. return sess.Commit()
  1151. }
  1152. func changeMilestoneAssign(e *xorm.Session, oldMid int64, issue *Issue) error {
  1153. if oldMid > 0 {
  1154. m, err := getMilestoneByID(e, oldMid)
  1155. if err != nil {
  1156. return err
  1157. }
  1158. m.NumIssues--
  1159. if issue.IsClosed {
  1160. m.NumClosedIssues--
  1161. }
  1162. if err = updateMilestone(e, m); err != nil {
  1163. return err
  1164. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE issue_id=?", issue.ID); err != nil {
  1165. return err
  1166. }
  1167. }
  1168. if issue.MilestoneID > 0 {
  1169. m, err := getMilestoneByID(e, issue.MilestoneID)
  1170. if err != nil {
  1171. return err
  1172. }
  1173. m.NumIssues++
  1174. if issue.IsClosed {
  1175. m.NumClosedIssues++
  1176. }
  1177. if m.NumIssues == 0 {
  1178. return ErrWrongIssueCounter
  1179. }
  1180. if err = updateMilestone(e, m); err != nil {
  1181. return err
  1182. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=? WHERE issue_id=?", m.ID, issue.ID); err != nil {
  1183. return err
  1184. }
  1185. }
  1186. return updateIssue(e, issue)
  1187. }
  1188. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1189. func ChangeMilestoneAssign(oldMid int64, issue *Issue) (err error) {
  1190. sess := x.NewSession()
  1191. defer sess.Close()
  1192. if err = sess.Begin(); err != nil {
  1193. return err
  1194. }
  1195. if err = changeMilestoneAssign(sess, oldMid, issue); err != nil {
  1196. return err
  1197. }
  1198. return sess.Commit()
  1199. }
  1200. // DeleteMilestoneByID deletes a milestone by given ID.
  1201. func DeleteMilestoneByID(id int64) error {
  1202. m, err := GetMilestoneByID(id)
  1203. if err != nil {
  1204. if IsErrMilestoneNotExist(err) {
  1205. return nil
  1206. }
  1207. return err
  1208. }
  1209. repo, err := GetRepositoryByID(m.RepoID)
  1210. if err != nil {
  1211. return err
  1212. }
  1213. sess := x.NewSession()
  1214. defer sessionRelease(sess)
  1215. if err = sess.Begin(); err != nil {
  1216. return err
  1217. }
  1218. if _, err = sess.Id(m.ID).Delete(new(Milestone)); err != nil {
  1219. return err
  1220. }
  1221. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1222. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1223. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1224. return err
  1225. }
  1226. if _, err = sess.Exec("UPDATE `issue` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1227. return err
  1228. } else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1229. return err
  1230. }
  1231. return sess.Commit()
  1232. }
  1233. // _________ __
  1234. // \_ ___ \ ____ _____ _____ ____ _____/ |_
  1235. // / \ \/ / _ \ / \ / \_/ __ \ / \ __\
  1236. // \ \___( <_> ) Y Y \ Y Y \ ___/| | \ |
  1237. // \______ /\____/|__|_| /__|_| /\___ >___| /__|
  1238. // \/ \/ \/ \/ \/
  1239. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  1240. type CommentType int
  1241. const (
  1242. // Plain comment, can be associated with a commit (CommitId > 0) and a line (Line > 0)
  1243. COMMENT_TYPE_COMMENT CommentType = iota
  1244. COMMENT_TYPE_REOPEN
  1245. COMMENT_TYPE_CLOSE
  1246. // References.
  1247. COMMENT_TYPE_ISSUE_REF
  1248. // Reference from a commit (not part of a pull request)
  1249. COMMENT_TYPE_COMMIT_REF
  1250. // Reference from a comment
  1251. COMMENT_TYPE_COMMENT_REF
  1252. // Reference from a pull request
  1253. COMMENT_TYPE_PULL_REF
  1254. )
  1255. type CommentTag int
  1256. const (
  1257. COMMENT_TAG_NONE CommentTag = iota
  1258. COMMENT_TAG_POSTER
  1259. COMMENT_TAG_ADMIN
  1260. COMMENT_TAG_OWNER
  1261. )
  1262. // Comment represents a comment in commit and issue page.
  1263. type Comment struct {
  1264. ID int64 `xorm:"pk autoincr"`
  1265. Type CommentType
  1266. PosterID int64
  1267. Poster *User `xorm:"-"`
  1268. IssueID int64 `xorm:"INDEX"`
  1269. CommitID int64
  1270. Line int64
  1271. Content string `xorm:"TEXT"`
  1272. RenderedContent string `xorm:"-"`
  1273. Created time.Time `xorm:"CREATED"`
  1274. // Reference issue in commit message
  1275. CommitSHA string `xorm:"VARCHAR(40)"`
  1276. Attachments []*Attachment `xorm:"-"`
  1277. // For view issue page.
  1278. ShowTag CommentTag `xorm:"-"`
  1279. }
  1280. func (c *Comment) AfterSet(colName string, _ xorm.Cell) {
  1281. var err error
  1282. switch colName {
  1283. case "id":
  1284. c.Attachments, err = GetAttachmentsByCommentID(c.ID)
  1285. if err != nil {
  1286. log.Error(3, "GetAttachmentsByCommentID[%d]: %v", c.ID, err)
  1287. }
  1288. case "poster_id":
  1289. c.Poster, err = GetUserByID(c.PosterID)
  1290. if err != nil {
  1291. if IsErrUserNotExist(err) {
  1292. c.PosterID = -1
  1293. c.Poster = NewFakeUser()
  1294. } else {
  1295. log.Error(3, "GetUserByID[%d]: %v", c.ID, err)
  1296. }
  1297. }
  1298. case "created":
  1299. c.Created = regulateTimeZone(c.Created)
  1300. }
  1301. }
  1302. func (c *Comment) AfterDelete() {
  1303. _, err := DeleteAttachmentsByComment(c.ID, true)
  1304. if err != nil {
  1305. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  1306. }
  1307. }
  1308. // HashTag returns unique hash tag for comment.
  1309. func (c *Comment) HashTag() string {
  1310. return "issuecomment-" + com.ToStr(c.ID)
  1311. }
  1312. // EventTag returns unique event hash tag for comment.
  1313. func (c *Comment) EventTag() string {
  1314. return "event-" + com.ToStr(c.ID)
  1315. }
  1316. func createComment(e *xorm.Session, u *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content, commitSHA string, uuids []string) (_ *Comment, err error) {
  1317. comment := &Comment{
  1318. PosterID: u.Id,
  1319. Type: cmtType,
  1320. IssueID: issue.ID,
  1321. CommitID: commitID,
  1322. Line: line,
  1323. Content: content,
  1324. CommitSHA: commitSHA,
  1325. }
  1326. if _, err = e.Insert(comment); err != nil {
  1327. return nil, err
  1328. }
  1329. // Check comment type.
  1330. switch cmtType {
  1331. case COMMENT_TYPE_COMMENT:
  1332. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", issue.ID); err != nil {
  1333. return nil, err
  1334. }
  1335. // Check attachments.
  1336. attachments := make([]*Attachment, 0, len(uuids))
  1337. for _, uuid := range uuids {
  1338. attach, err := getAttachmentByUUID(e, uuid)
  1339. if err != nil {
  1340. if IsErrAttachmentNotExist(err) {
  1341. continue
  1342. }
  1343. return nil, fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  1344. }
  1345. attachments = append(attachments, attach)
  1346. }
  1347. for i := range attachments {
  1348. attachments[i].IssueID = issue.ID
  1349. attachments[i].CommentID = comment.ID
  1350. // No assign value could be 0, so ignore AllCols().
  1351. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  1352. return nil, fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  1353. }
  1354. }
  1355. // Notify watchers.
  1356. act := &Action{
  1357. ActUserID: u.Id,
  1358. ActUserName: u.LowerName,
  1359. ActEmail: u.Email,
  1360. OpType: COMMENT_ISSUE,
  1361. Content: fmt.Sprintf("%d|%s", issue.Index, strings.Split(content, "\n")[0]),
  1362. RepoID: repo.ID,
  1363. RepoUserName: repo.Owner.LowerName,
  1364. RepoName: repo.LowerName,
  1365. IsPrivate: repo.IsPrivate,
  1366. }
  1367. if err = notifyWatchers(e, act); err != nil {
  1368. return nil, err
  1369. }
  1370. case COMMENT_TYPE_REOPEN:
  1371. if issue.IsPull {
  1372. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls-1 WHERE id=?", repo.ID)
  1373. } else {
  1374. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", repo.ID)
  1375. }
  1376. if err != nil {
  1377. return nil, err
  1378. }
  1379. case COMMENT_TYPE_CLOSE:
  1380. if issue.IsPull {
  1381. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls+1 WHERE id=?", repo.ID)
  1382. } else {
  1383. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", repo.ID)
  1384. }
  1385. if err != nil {
  1386. return nil, err
  1387. }
  1388. }
  1389. return comment, nil
  1390. }
  1391. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  1392. cmtType := COMMENT_TYPE_CLOSE
  1393. if !issue.IsClosed {
  1394. cmtType = COMMENT_TYPE_REOPEN
  1395. }
  1396. return createComment(e, doer, repo, issue, 0, 0, cmtType, "", "", nil)
  1397. }
  1398. // CreateComment creates comment of issue or commit.
  1399. func CreateComment(doer *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content, commitSHA string, attachments []string) (comment *Comment, err error) {
  1400. sess := x.NewSession()
  1401. defer sessionRelease(sess)
  1402. if err = sess.Begin(); err != nil {
  1403. return nil, err
  1404. }
  1405. comment, err = createComment(sess, doer, repo, issue, commitID, line, cmtType, content, commitSHA, attachments)
  1406. if err != nil {
  1407. return nil, err
  1408. }
  1409. return comment, sess.Commit()
  1410. }
  1411. // CreateIssueComment creates a plain issue comment.
  1412. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  1413. return CreateComment(doer, repo, issue, 0, 0, COMMENT_TYPE_COMMENT, content, "", attachments)
  1414. }
  1415. // CreateRefComment creates a commit reference comment to issue.
  1416. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  1417. if len(commitSHA) == 0 {
  1418. return fmt.Errorf("cannot create reference with empty commit SHA")
  1419. }
  1420. // Check if same reference from same commit has already existed.
  1421. has, err := x.Get(&Comment{
  1422. Type: COMMENT_TYPE_COMMIT_REF,
  1423. IssueID: issue.ID,
  1424. CommitSHA: commitSHA,
  1425. })
  1426. if err != nil {
  1427. return fmt.Errorf("check reference comment: %v", err)
  1428. } else if has {
  1429. return nil
  1430. }
  1431. _, err = CreateComment(doer, repo, issue, 0, 0, COMMENT_TYPE_COMMIT_REF, content, commitSHA, nil)
  1432. return err
  1433. }
  1434. // GetCommentByID returns the comment by given ID.
  1435. func GetCommentByID(id int64) (*Comment, error) {
  1436. c := new(Comment)
  1437. has, err := x.Id(id).Get(c)
  1438. if err != nil {
  1439. return nil, err
  1440. } else if !has {
  1441. return nil, ErrCommentNotExist{id}
  1442. }
  1443. return c, nil
  1444. }
  1445. // GetCommentsByIssueID returns all comments of issue by given ID.
  1446. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  1447. comments := make([]*Comment, 0, 10)
  1448. return comments, x.Where("issue_id=?", issueID).Asc("created").Find(&comments)
  1449. }
  1450. // UpdateComment updates information of comment.
  1451. func UpdateComment(c *Comment) error {
  1452. _, err := x.Id(c.ID).AllCols().Update(c)
  1453. return err
  1454. }
  1455. // Attachment represent a attachment of issue/comment/release.
  1456. type Attachment struct {
  1457. ID int64 `xorm:"pk autoincr"`
  1458. UUID string `xorm:"uuid UNIQUE"`
  1459. IssueID int64 `xorm:"INDEX"`
  1460. CommentID int64
  1461. ReleaseID int64 `xorm:"INDEX"`
  1462. Name string
  1463. Created time.Time `xorm:"CREATED"`
  1464. }
  1465. // AttachmentLocalPath returns where attachment is stored in local file system based on given UUID.
  1466. func AttachmentLocalPath(uuid string) string {
  1467. return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid)
  1468. }
  1469. // LocalPath returns where attachment is stored in local file system.
  1470. func (attach *Attachment) LocalPath() string {
  1471. return AttachmentLocalPath(attach.UUID)
  1472. }
  1473. // NewAttachment creates a new attachment object.
  1474. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) {
  1475. attach := &Attachment{
  1476. UUID: gouuid.NewV4().String(),
  1477. Name: name,
  1478. }
  1479. if err = os.MkdirAll(path.Dir(attach.LocalPath()), os.ModePerm); err != nil {
  1480. return nil, fmt.Errorf("MkdirAll: %v", err)
  1481. }
  1482. fw, err := os.Create(attach.LocalPath())
  1483. if err != nil {
  1484. return nil, fmt.Errorf("Create: %v", err)
  1485. }
  1486. defer fw.Close()
  1487. if _, err = fw.Write(buf); err != nil {
  1488. return nil, fmt.Errorf("Write: %v", err)
  1489. } else if _, err = io.Copy(fw, file); err != nil {
  1490. return nil, fmt.Errorf("Copy: %v", err)
  1491. }
  1492. sess := x.NewSession()
  1493. defer sessionRelease(sess)
  1494. if err := sess.Begin(); err != nil {
  1495. return nil, err
  1496. }
  1497. if _, err := sess.Insert(attach); err != nil {
  1498. return nil, err
  1499. }
  1500. return attach, sess.Commit()
  1501. }
  1502. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  1503. attach := &Attachment{UUID: uuid}
  1504. has, err := x.Get(attach)
  1505. if err != nil {
  1506. return nil, err
  1507. } else if !has {
  1508. return nil, ErrAttachmentNotExist{0, uuid}
  1509. }
  1510. return attach, nil
  1511. }
  1512. // GetAttachmentByUUID returns attachment by given UUID.
  1513. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  1514. return getAttachmentByUUID(x, uuid)
  1515. }
  1516. // GetAttachmentsByIssueID returns all attachments for given issue by ID.
  1517. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  1518. attachments := make([]*Attachment, 0, 10)
  1519. return attachments, x.Where("issue_id=? AND comment_id=0", issueID).Find(&attachments)
  1520. }
  1521. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  1522. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  1523. attachments := make([]*Attachment, 0, 10)
  1524. return attachments, x.Where("comment_id=?", commentID).Find(&attachments)
  1525. }
  1526. // DeleteAttachment deletes the given attachment and optionally the associated file.
  1527. func DeleteAttachment(a *Attachment, remove bool) error {
  1528. _, err := DeleteAttachments([]*Attachment{a}, remove)
  1529. return err
  1530. }
  1531. // DeleteAttachments deletes the given attachments and optionally the associated files.
  1532. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  1533. for i, a := range attachments {
  1534. if remove {
  1535. if err := os.Remove(a.LocalPath()); err != nil {
  1536. return i, err
  1537. }
  1538. }
  1539. if _, err := x.Delete(a.ID); err != nil {
  1540. return i, err
  1541. }
  1542. }
  1543. return len(attachments), nil
  1544. }
  1545. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  1546. func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
  1547. attachments, err := GetAttachmentsByIssueID(issueId)
  1548. if err != nil {
  1549. return 0, err
  1550. }
  1551. return DeleteAttachments(attachments, remove)
  1552. }
  1553. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  1554. func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
  1555. attachments, err := GetAttachmentsByCommentID(commentId)
  1556. if err != nil {
  1557. return 0, err
  1558. }
  1559. return DeleteAttachments(attachments, remove)
  1560. }