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

issue.go 49 kB

11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867
  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. "errors"
  7. "fmt"
  8. "sort"
  9. "strings"
  10. "time"
  11. api "code.gitea.io/sdk/gitea"
  12. "github.com/Unknwon/com"
  13. "github.com/go-xorm/xorm"
  14. "code.gitea.io/gitea/modules/base"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/util"
  18. )
  19. var (
  20. errMissingIssueNumber = errors.New("No issue number specified")
  21. )
  22. // Issue represents an issue or pull request of repository.
  23. type Issue struct {
  24. ID int64 `xorm:"pk autoincr"`
  25. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  26. Repo *Repository `xorm:"-"`
  27. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  28. PosterID int64 `xorm:"INDEX"`
  29. Poster *User `xorm:"-"`
  30. Title string `xorm:"name"`
  31. Content string `xorm:"TEXT"`
  32. RenderedContent string `xorm:"-"`
  33. Labels []*Label `xorm:"-"`
  34. MilestoneID int64 `xorm:"INDEX"`
  35. Milestone *Milestone `xorm:"-"`
  36. Priority int
  37. AssigneeID int64 `xorm:"INDEX"`
  38. Assignee *User `xorm:"-"`
  39. IsClosed bool `xorm:"INDEX"`
  40. IsRead bool `xorm:"-"`
  41. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  42. PullRequest *PullRequest `xorm:"-"`
  43. NumComments int
  44. Deadline time.Time `xorm:"-"`
  45. DeadlineUnix int64 `xorm:"INDEX"`
  46. Created time.Time `xorm:"-"`
  47. CreatedUnix int64 `xorm:"INDEX"`
  48. Updated time.Time `xorm:"-"`
  49. UpdatedUnix int64 `xorm:"INDEX"`
  50. Attachments []*Attachment `xorm:"-"`
  51. Comments []*Comment `xorm:"-"`
  52. }
  53. // BeforeInsert is invoked from XORM before inserting an object of this type.
  54. func (issue *Issue) BeforeInsert() {
  55. issue.CreatedUnix = time.Now().Unix()
  56. issue.UpdatedUnix = issue.CreatedUnix
  57. }
  58. // BeforeUpdate is invoked from XORM before updating this object.
  59. func (issue *Issue) BeforeUpdate() {
  60. issue.UpdatedUnix = time.Now().Unix()
  61. issue.DeadlineUnix = issue.Deadline.Unix()
  62. }
  63. // AfterSet is invoked from XORM after setting the value of a field of
  64. // this object.
  65. func (issue *Issue) AfterSet(colName string, _ xorm.Cell) {
  66. switch colName {
  67. case "deadline_unix":
  68. issue.Deadline = time.Unix(issue.DeadlineUnix, 0).Local()
  69. case "created_unix":
  70. issue.Created = time.Unix(issue.CreatedUnix, 0).Local()
  71. case "updated_unix":
  72. issue.Updated = time.Unix(issue.UpdatedUnix, 0).Local()
  73. }
  74. }
  75. func (issue *Issue) loadRepo(e Engine) (err error) {
  76. if issue.Repo == nil {
  77. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  78. if err != nil {
  79. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  80. }
  81. }
  82. return nil
  83. }
  84. // GetPullRequest returns the issue pull request
  85. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  86. if !issue.IsPull {
  87. return nil, fmt.Errorf("Issue is not a pull request")
  88. }
  89. pr, err = getPullRequestByIssueID(x, issue.ID)
  90. return
  91. }
  92. func (issue *Issue) loadLabels(e Engine) (err error) {
  93. if issue.Labels == nil {
  94. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  95. if err != nil {
  96. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  97. }
  98. }
  99. return nil
  100. }
  101. func (issue *Issue) loadPoster(e Engine) (err error) {
  102. if issue.Poster == nil {
  103. issue.Poster, err = getUserByID(e, issue.PosterID)
  104. if err != nil {
  105. issue.PosterID = -1
  106. issue.Poster = NewGhostUser()
  107. if !IsErrUserNotExist(err) {
  108. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  109. }
  110. err = nil
  111. return
  112. }
  113. }
  114. return
  115. }
  116. func (issue *Issue) loadAttributes(e Engine) (err error) {
  117. if err = issue.loadRepo(e); err != nil {
  118. return
  119. }
  120. if err = issue.loadPoster(e); err != nil {
  121. return
  122. }
  123. if err = issue.loadLabels(e); err != nil {
  124. return
  125. }
  126. if issue.Milestone == nil && issue.MilestoneID > 0 {
  127. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  128. if err != nil {
  129. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  130. }
  131. }
  132. if issue.Assignee == nil && issue.AssigneeID > 0 {
  133. issue.Assignee, err = getUserByID(e, issue.AssigneeID)
  134. if err != nil {
  135. return fmt.Errorf("getUserByID.(assignee) [%d]: %v", issue.AssigneeID, err)
  136. }
  137. }
  138. if issue.IsPull && issue.PullRequest == nil {
  139. // It is possible pull request is not yet created.
  140. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  141. if err != nil && !IsErrPullRequestNotExist(err) {
  142. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  143. }
  144. }
  145. if issue.Attachments == nil {
  146. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  147. if err != nil {
  148. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  149. }
  150. }
  151. if issue.Comments == nil {
  152. issue.Comments, err = getCommentsByIssueID(e, issue.ID)
  153. if err != nil {
  154. return fmt.Errorf("getCommentsByIssueID [%d]: %v", issue.ID, err)
  155. }
  156. }
  157. return nil
  158. }
  159. // LoadAttributes loads the attribute of this issue.
  160. func (issue *Issue) LoadAttributes() error {
  161. return issue.loadAttributes(x)
  162. }
  163. // HTMLURL returns the absolute URL to this issue.
  164. func (issue *Issue) HTMLURL() string {
  165. var path string
  166. if issue.IsPull {
  167. path = "pulls"
  168. } else {
  169. path = "issues"
  170. }
  171. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  172. }
  173. // DiffURL returns the absolute URL to this diff
  174. func (issue *Issue) DiffURL() string {
  175. if issue.IsPull {
  176. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  177. }
  178. return ""
  179. }
  180. // PatchURL returns the absolute URL to this patch
  181. func (issue *Issue) PatchURL() string {
  182. if issue.IsPull {
  183. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  184. }
  185. return ""
  186. }
  187. // State returns string representation of issue status.
  188. func (issue *Issue) State() api.StateType {
  189. if issue.IsClosed {
  190. return api.StateClosed
  191. }
  192. return api.StateOpen
  193. }
  194. // APIFormat assumes some fields assigned with values:
  195. // Required - Poster, Labels,
  196. // Optional - Milestone, Assignee, PullRequest
  197. func (issue *Issue) APIFormat() *api.Issue {
  198. apiLabels := make([]*api.Label, len(issue.Labels))
  199. for i := range issue.Labels {
  200. apiLabels[i] = issue.Labels[i].APIFormat()
  201. }
  202. apiIssue := &api.Issue{
  203. ID: issue.ID,
  204. Index: issue.Index,
  205. Poster: issue.Poster.APIFormat(),
  206. Title: issue.Title,
  207. Body: issue.Content,
  208. Labels: apiLabels,
  209. State: issue.State(),
  210. Comments: issue.NumComments,
  211. Created: issue.Created,
  212. Updated: issue.Updated,
  213. }
  214. if issue.Milestone != nil {
  215. apiIssue.Milestone = issue.Milestone.APIFormat()
  216. }
  217. if issue.Assignee != nil {
  218. apiIssue.Assignee = issue.Assignee.APIFormat()
  219. }
  220. if issue.IsPull {
  221. apiIssue.PullRequest = &api.PullRequestMeta{
  222. HasMerged: issue.PullRequest.HasMerged,
  223. }
  224. if issue.PullRequest.HasMerged {
  225. apiIssue.PullRequest.Merged = &issue.PullRequest.Merged
  226. }
  227. }
  228. return apiIssue
  229. }
  230. // HashTag returns unique hash tag for issue.
  231. func (issue *Issue) HashTag() string {
  232. return "issue-" + com.ToStr(issue.ID)
  233. }
  234. // IsPoster returns true if given user by ID is the poster.
  235. func (issue *Issue) IsPoster(uid int64) bool {
  236. return issue.PosterID == uid
  237. }
  238. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  239. return hasIssueLabel(e, issue.ID, labelID)
  240. }
  241. // HasLabel returns true if issue has been labeled by given ID.
  242. func (issue *Issue) HasLabel(labelID int64) bool {
  243. return issue.hasLabel(x, labelID)
  244. }
  245. func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
  246. var err error
  247. if issue.IsPull {
  248. err = issue.PullRequest.LoadIssue()
  249. if err != nil {
  250. log.Error(4, "LoadIssue: %v", err)
  251. return
  252. }
  253. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  254. Action: api.HookIssueLabelUpdated,
  255. Index: issue.Index,
  256. PullRequest: issue.PullRequest.APIFormat(),
  257. Repository: issue.Repo.APIFormat(AccessModeNone),
  258. Sender: doer.APIFormat(),
  259. })
  260. }
  261. if err != nil {
  262. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  263. } else {
  264. go HookQueue.Add(issue.RepoID)
  265. }
  266. }
  267. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  268. return newIssueLabel(e, issue, label, doer)
  269. }
  270. // AddLabel adds a new label to the issue.
  271. func (issue *Issue) AddLabel(doer *User, label *Label) error {
  272. if err := NewIssueLabel(issue, label, doer); err != nil {
  273. return err
  274. }
  275. issue.sendLabelUpdatedWebhook(doer)
  276. return nil
  277. }
  278. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  279. return newIssueLabels(e, issue, labels, doer)
  280. }
  281. // AddLabels adds a list of new labels to the issue.
  282. func (issue *Issue) AddLabels(doer *User, labels []*Label) error {
  283. if err := NewIssueLabels(issue, labels, doer); err != nil {
  284. return err
  285. }
  286. issue.sendLabelUpdatedWebhook(doer)
  287. return nil
  288. }
  289. func (issue *Issue) getLabels(e Engine) (err error) {
  290. if len(issue.Labels) > 0 {
  291. return nil
  292. }
  293. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  294. if err != nil {
  295. return fmt.Errorf("getLabelsByIssueID: %v", err)
  296. }
  297. return nil
  298. }
  299. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  300. return deleteIssueLabel(e, doer, issue, label)
  301. }
  302. // RemoveLabel removes a label from issue by given ID.
  303. func (issue *Issue) RemoveLabel(doer *User, label *Label) error {
  304. if err := issue.loadRepo(x); err != nil {
  305. return err
  306. }
  307. if has, err := HasAccess(doer, issue.Repo, AccessModeWrite); err != nil {
  308. return err
  309. } else if !has {
  310. return ErrLabelNotExist{}
  311. }
  312. if err := DeleteIssueLabel(issue, doer, label); err != nil {
  313. return err
  314. }
  315. issue.sendLabelUpdatedWebhook(doer)
  316. return nil
  317. }
  318. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  319. if err = issue.getLabels(e); err != nil {
  320. return fmt.Errorf("getLabels: %v", err)
  321. }
  322. for i := range issue.Labels {
  323. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  324. return fmt.Errorf("removeLabel: %v", err)
  325. }
  326. }
  327. return nil
  328. }
  329. // ClearLabels removes all issue labels as the given user.
  330. // Triggers appropriate WebHooks, if any.
  331. func (issue *Issue) ClearLabels(doer *User) (err error) {
  332. sess := x.NewSession()
  333. defer sessionRelease(sess)
  334. if err = sess.Begin(); err != nil {
  335. return err
  336. }
  337. if err := issue.loadRepo(sess); err != nil {
  338. return err
  339. }
  340. if has, err := hasAccess(sess, doer, issue.Repo, AccessModeWrite); err != nil {
  341. return err
  342. } else if !has {
  343. return ErrLabelNotExist{}
  344. }
  345. if err = issue.clearLabels(sess, doer); err != nil {
  346. return err
  347. }
  348. if err = sess.Commit(); err != nil {
  349. return fmt.Errorf("Commit: %v", err)
  350. }
  351. if issue.IsPull {
  352. err = issue.PullRequest.LoadIssue()
  353. if err != nil {
  354. log.Error(4, "LoadIssue: %v", err)
  355. return
  356. }
  357. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  358. Action: api.HookIssueLabelCleared,
  359. Index: issue.Index,
  360. PullRequest: issue.PullRequest.APIFormat(),
  361. Repository: issue.Repo.APIFormat(AccessModeNone),
  362. Sender: doer.APIFormat(),
  363. })
  364. }
  365. if err != nil {
  366. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  367. } else {
  368. go HookQueue.Add(issue.RepoID)
  369. }
  370. return nil
  371. }
  372. type labelSorter []*Label
  373. func (ts labelSorter) Len() int {
  374. return len([]*Label(ts))
  375. }
  376. func (ts labelSorter) Less(i, j int) bool {
  377. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  378. }
  379. func (ts labelSorter) Swap(i, j int) {
  380. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  381. }
  382. // ReplaceLabels removes all current labels and add new labels to the issue.
  383. // Triggers appropriate WebHooks, if any.
  384. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  385. sess := x.NewSession()
  386. defer sessionRelease(sess)
  387. if err = sess.Begin(); err != nil {
  388. return err
  389. }
  390. if err = issue.loadLabels(sess); err != nil {
  391. return err
  392. }
  393. sort.Sort(labelSorter(labels))
  394. sort.Sort(labelSorter(issue.Labels))
  395. var toAdd, toRemove []*Label
  396. for _, l := range labels {
  397. var exist bool
  398. for _, oriLabel := range issue.Labels {
  399. if oriLabel.ID == l.ID {
  400. exist = true
  401. break
  402. }
  403. }
  404. if !exist {
  405. toAdd = append(toAdd, l)
  406. }
  407. }
  408. for _, oriLabel := range issue.Labels {
  409. var exist bool
  410. for _, l := range labels {
  411. if oriLabel.ID == l.ID {
  412. exist = true
  413. break
  414. }
  415. }
  416. if !exist {
  417. toRemove = append(toRemove, oriLabel)
  418. }
  419. }
  420. if len(toAdd) > 0 {
  421. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  422. return fmt.Errorf("addLabels: %v", err)
  423. }
  424. }
  425. if len(toRemove) > 0 {
  426. for _, l := range toRemove {
  427. if err = issue.removeLabel(sess, doer, l); err != nil {
  428. return fmt.Errorf("removeLabel: %v", err)
  429. }
  430. }
  431. }
  432. return sess.Commit()
  433. }
  434. // GetAssignee sets the Assignee attribute of this issue.
  435. func (issue *Issue) GetAssignee() (err error) {
  436. if issue.AssigneeID == 0 || issue.Assignee != nil {
  437. return nil
  438. }
  439. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  440. if IsErrUserNotExist(err) {
  441. return nil
  442. }
  443. return err
  444. }
  445. // ReadBy sets issue to be read by given user.
  446. func (issue *Issue) ReadBy(userID int64) error {
  447. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  448. return err
  449. }
  450. if err := setNotificationStatusReadIfUnread(x, userID, issue.ID); err != nil {
  451. return err
  452. }
  453. return nil
  454. }
  455. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  456. if _, err := e.Id(issue.ID).Cols(cols...).Update(issue); err != nil {
  457. return err
  458. }
  459. UpdateIssueIndexer(issue)
  460. return nil
  461. }
  462. // UpdateIssueCols only updates values of specific columns for given issue.
  463. func UpdateIssueCols(issue *Issue, cols ...string) error {
  464. return updateIssueCols(x, issue, cols...)
  465. }
  466. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
  467. // Nothing should be performed if current status is same as target status
  468. if issue.IsClosed == isClosed {
  469. return nil
  470. }
  471. issue.IsClosed = isClosed
  472. if err = updateIssueCols(e, issue, "is_closed"); err != nil {
  473. return err
  474. } else if err = updateIssueUsersByStatus(e, issue.ID, isClosed); err != nil {
  475. return err
  476. }
  477. // Update issue count of labels
  478. if err = issue.getLabels(e); err != nil {
  479. return err
  480. }
  481. for idx := range issue.Labels {
  482. if issue.IsClosed {
  483. issue.Labels[idx].NumClosedIssues++
  484. } else {
  485. issue.Labels[idx].NumClosedIssues--
  486. }
  487. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  488. return err
  489. }
  490. }
  491. // Update issue count of milestone
  492. if err = changeMilestoneIssueStats(e, issue); err != nil {
  493. return err
  494. }
  495. // New action comment
  496. if _, err = createStatusComment(e, doer, repo, issue); err != nil {
  497. return err
  498. }
  499. return nil
  500. }
  501. // ChangeStatus changes issue status to open or closed.
  502. func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (err error) {
  503. sess := x.NewSession()
  504. defer sessionRelease(sess)
  505. if err = sess.Begin(); err != nil {
  506. return err
  507. }
  508. if err = issue.changeStatus(sess, doer, repo, isClosed); err != nil {
  509. return err
  510. }
  511. if err = sess.Commit(); err != nil {
  512. return fmt.Errorf("Commit: %v", err)
  513. }
  514. if issue.IsPull {
  515. // Merge pull request calls issue.changeStatus so we need to handle separately.
  516. issue.PullRequest.Issue = issue
  517. apiPullRequest := &api.PullRequestPayload{
  518. Index: issue.Index,
  519. PullRequest: issue.PullRequest.APIFormat(),
  520. Repository: repo.APIFormat(AccessModeNone),
  521. Sender: doer.APIFormat(),
  522. }
  523. if isClosed {
  524. apiPullRequest.Action = api.HookIssueClosed
  525. } else {
  526. apiPullRequest.Action = api.HookIssueReOpened
  527. }
  528. err = PrepareWebhooks(repo, HookEventPullRequest, apiPullRequest)
  529. }
  530. if err != nil {
  531. log.Error(4, "PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  532. } else {
  533. go HookQueue.Add(repo.ID)
  534. }
  535. return nil
  536. }
  537. // ChangeTitle changes the title of this issue, as the given user.
  538. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
  539. oldTitle := issue.Title
  540. issue.Title = title
  541. if err = UpdateIssueCols(issue, "name"); err != nil {
  542. return fmt.Errorf("UpdateIssueCols: %v", err)
  543. }
  544. if issue.IsPull {
  545. issue.PullRequest.Issue = issue
  546. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  547. Action: api.HookIssueEdited,
  548. Index: issue.Index,
  549. Changes: &api.ChangesPayload{
  550. Title: &api.ChangesFromPayload{
  551. From: oldTitle,
  552. },
  553. },
  554. PullRequest: issue.PullRequest.APIFormat(),
  555. Repository: issue.Repo.APIFormat(AccessModeNone),
  556. Sender: doer.APIFormat(),
  557. })
  558. }
  559. if err != nil {
  560. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  561. } else {
  562. go HookQueue.Add(issue.RepoID)
  563. }
  564. return nil
  565. }
  566. // ChangeContent changes issue content, as the given user.
  567. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  568. oldContent := issue.Content
  569. issue.Content = content
  570. if err = UpdateIssueCols(issue, "content"); err != nil {
  571. return fmt.Errorf("UpdateIssueCols: %v", err)
  572. }
  573. if issue.IsPull {
  574. issue.PullRequest.Issue = issue
  575. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  576. Action: api.HookIssueEdited,
  577. Index: issue.Index,
  578. Changes: &api.ChangesPayload{
  579. Body: &api.ChangesFromPayload{
  580. From: oldContent,
  581. },
  582. },
  583. PullRequest: issue.PullRequest.APIFormat(),
  584. Repository: issue.Repo.APIFormat(AccessModeNone),
  585. Sender: doer.APIFormat(),
  586. })
  587. }
  588. if err != nil {
  589. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  590. } else {
  591. go HookQueue.Add(issue.RepoID)
  592. }
  593. return nil
  594. }
  595. // ChangeAssignee changes the Asssignee field of this issue.
  596. func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
  597. issue.AssigneeID = assigneeID
  598. if err = UpdateIssueUserByAssignee(issue); err != nil {
  599. return fmt.Errorf("UpdateIssueUserByAssignee: %v", err)
  600. }
  601. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  602. if err != nil && !IsErrUserNotExist(err) {
  603. log.Error(4, "GetUserByID [assignee_id: %v]: %v", issue.AssigneeID, err)
  604. return nil
  605. }
  606. // Error not nil here means user does not exist, which is remove assignee.
  607. isRemoveAssignee := err != nil
  608. if issue.IsPull {
  609. issue.PullRequest.Issue = issue
  610. apiPullRequest := &api.PullRequestPayload{
  611. Index: issue.Index,
  612. PullRequest: issue.PullRequest.APIFormat(),
  613. Repository: issue.Repo.APIFormat(AccessModeNone),
  614. Sender: doer.APIFormat(),
  615. }
  616. if isRemoveAssignee {
  617. apiPullRequest.Action = api.HookIssueUnassigned
  618. } else {
  619. apiPullRequest.Action = api.HookIssueAssigned
  620. }
  621. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest)
  622. }
  623. if err != nil {
  624. log.Error(4, "PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err)
  625. } else {
  626. go HookQueue.Add(issue.RepoID)
  627. }
  628. return nil
  629. }
  630. // NewIssueOptions represents the options of a new issue.
  631. type NewIssueOptions struct {
  632. Repo *Repository
  633. Issue *Issue
  634. LableIDs []int64
  635. Attachments []string // In UUID format.
  636. IsPull bool
  637. }
  638. func newIssue(e *xorm.Session, opts NewIssueOptions) (err error) {
  639. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  640. opts.Issue.Index = opts.Repo.NextIssueIndex()
  641. if opts.Issue.MilestoneID > 0 {
  642. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  643. if err != nil && !IsErrMilestoneNotExist(err) {
  644. return fmt.Errorf("getMilestoneByID: %v", err)
  645. }
  646. // Assume milestone is invalid and drop silently.
  647. opts.Issue.MilestoneID = 0
  648. if milestone != nil {
  649. opts.Issue.MilestoneID = milestone.ID
  650. opts.Issue.Milestone = milestone
  651. if err = changeMilestoneAssign(e, opts.Issue, -1); err != nil {
  652. return err
  653. }
  654. }
  655. }
  656. if opts.Issue.AssigneeID > 0 {
  657. assignee, err := getUserByID(e, opts.Issue.AssigneeID)
  658. if err != nil && !IsErrUserNotExist(err) {
  659. return fmt.Errorf("getUserByID: %v", err)
  660. }
  661. // Assume assignee is invalid and drop silently.
  662. opts.Issue.AssigneeID = 0
  663. if assignee != nil {
  664. valid, err := hasAccess(e, assignee, opts.Repo, AccessModeWrite)
  665. if err != nil {
  666. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assignee.ID, opts.Repo.ID, err)
  667. }
  668. if valid {
  669. opts.Issue.AssigneeID = assignee.ID
  670. opts.Issue.Assignee = assignee
  671. }
  672. }
  673. }
  674. // Milestone and assignee validation should happen before insert actual object.
  675. if _, err = e.Insert(opts.Issue); err != nil {
  676. return err
  677. }
  678. if opts.IsPull {
  679. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  680. } else {
  681. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  682. }
  683. if err != nil {
  684. return err
  685. }
  686. if len(opts.LableIDs) > 0 {
  687. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  688. // So we have to get all needed labels first.
  689. labels := make([]*Label, 0, len(opts.LableIDs))
  690. if err = e.In("id", opts.LableIDs).Find(&labels); err != nil {
  691. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LableIDs, err)
  692. }
  693. if err = opts.Issue.loadPoster(e); err != nil {
  694. return err
  695. }
  696. for _, label := range labels {
  697. // Silently drop invalid labels.
  698. if label.RepoID != opts.Repo.ID {
  699. continue
  700. }
  701. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  702. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  703. }
  704. }
  705. }
  706. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  707. return err
  708. }
  709. UpdateIssueIndexer(opts.Issue)
  710. if len(opts.Attachments) > 0 {
  711. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  712. if err != nil {
  713. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  714. }
  715. for i := 0; i < len(attachments); i++ {
  716. attachments[i].IssueID = opts.Issue.ID
  717. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  718. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  719. }
  720. }
  721. }
  722. return opts.Issue.loadAttributes(e)
  723. }
  724. // NewIssue creates new issue with labels for repository.
  725. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  726. sess := x.NewSession()
  727. defer sessionRelease(sess)
  728. if err = sess.Begin(); err != nil {
  729. return err
  730. }
  731. if err = newIssue(sess, NewIssueOptions{
  732. Repo: repo,
  733. Issue: issue,
  734. LableIDs: labelIDs,
  735. Attachments: uuids,
  736. }); err != nil {
  737. return fmt.Errorf("newIssue: %v", err)
  738. }
  739. if err = sess.Commit(); err != nil {
  740. return fmt.Errorf("Commit: %v", err)
  741. }
  742. if err = NotifyWatchers(&Action{
  743. ActUserID: issue.Poster.ID,
  744. ActUserName: issue.Poster.Name,
  745. OpType: ActionCreateIssue,
  746. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  747. RepoID: repo.ID,
  748. RepoUserName: repo.Owner.Name,
  749. RepoName: repo.Name,
  750. IsPrivate: repo.IsPrivate,
  751. }); err != nil {
  752. log.Error(4, "NotifyWatchers: %v", err)
  753. }
  754. if err = issue.MailParticipants(); err != nil {
  755. log.Error(4, "MailParticipants: %v", err)
  756. }
  757. return nil
  758. }
  759. // GetIssueByRef returns an Issue specified by a GFM reference.
  760. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  761. func GetIssueByRef(ref string) (*Issue, error) {
  762. n := strings.IndexByte(ref, byte('#'))
  763. if n == -1 {
  764. return nil, errMissingIssueNumber
  765. }
  766. index, err := com.StrTo(ref[n+1:]).Int64()
  767. if err != nil {
  768. return nil, err
  769. }
  770. repo, err := GetRepositoryByRef(ref[:n])
  771. if err != nil {
  772. return nil, err
  773. }
  774. issue, err := GetIssueByIndex(repo.ID, index)
  775. if err != nil {
  776. return nil, err
  777. }
  778. return issue, issue.LoadAttributes()
  779. }
  780. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  781. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  782. issue := &Issue{
  783. RepoID: repoID,
  784. Index: index,
  785. }
  786. has, err := x.Get(issue)
  787. if err != nil {
  788. return nil, err
  789. } else if !has {
  790. return nil, ErrIssueNotExist{0, repoID, index}
  791. }
  792. return issue, nil
  793. }
  794. // GetIssueByIndex returns issue by index in a repository.
  795. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  796. issue, err := GetRawIssueByIndex(repoID, index)
  797. if err != nil {
  798. return nil, err
  799. }
  800. return issue, issue.LoadAttributes()
  801. }
  802. func getIssueByID(e Engine, id int64) (*Issue, error) {
  803. issue := new(Issue)
  804. has, err := e.Id(id).Get(issue)
  805. if err != nil {
  806. return nil, err
  807. } else if !has {
  808. return nil, ErrIssueNotExist{id, 0, 0}
  809. }
  810. return issue, issue.LoadAttributes()
  811. }
  812. // GetIssueByID returns an issue by given ID.
  813. func GetIssueByID(id int64) (*Issue, error) {
  814. return getIssueByID(x, id)
  815. }
  816. // IssuesOptions represents options of an issue.
  817. type IssuesOptions struct {
  818. RepoID int64
  819. AssigneeID int64
  820. PosterID int64
  821. MentionedID int64
  822. MilestoneID int64
  823. RepoIDs []int64
  824. Page int
  825. IsClosed util.OptionalBool
  826. IsPull util.OptionalBool
  827. Labels string
  828. SortType string
  829. IssueIDs []int64
  830. }
  831. // sortIssuesSession sort an issues-related session based on the provided
  832. // sortType string
  833. func sortIssuesSession(sess *xorm.Session, sortType string) {
  834. switch sortType {
  835. case "oldest":
  836. sess.Asc("issue.created_unix")
  837. case "recentupdate":
  838. sess.Desc("issue.updated_unix")
  839. case "leastupdate":
  840. sess.Asc("issue.updated_unix")
  841. case "mostcomment":
  842. sess.Desc("issue.num_comments")
  843. case "leastcomment":
  844. sess.Asc("issue.num_comments")
  845. case "priority":
  846. sess.Desc("issue.priority")
  847. default:
  848. sess.Desc("issue.created_unix")
  849. }
  850. }
  851. // Issues returns a list of issues by given conditions.
  852. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  853. var sess *xorm.Session
  854. if opts.Page >= 0 {
  855. var start int
  856. if opts.Page == 0 {
  857. start = 0
  858. } else {
  859. start = (opts.Page - 1) * setting.UI.IssuePagingNum
  860. }
  861. sess = x.Limit(setting.UI.IssuePagingNum, start)
  862. } else {
  863. sess = x.NewSession()
  864. defer sess.Close()
  865. }
  866. if len(opts.IssueIDs) > 0 {
  867. sess.In("issue.id", opts.IssueIDs)
  868. }
  869. if opts.RepoID > 0 {
  870. sess.And("issue.repo_id=?", opts.RepoID)
  871. } else if len(opts.RepoIDs) > 0 {
  872. // In case repository IDs are provided but actually no repository has issue.
  873. sess.In("issue.repo_id", opts.RepoIDs)
  874. }
  875. switch opts.IsClosed {
  876. case util.OptionalBoolTrue:
  877. sess.And("issue.is_closed=?", true)
  878. case util.OptionalBoolFalse:
  879. sess.And("issue.is_closed=?", false)
  880. }
  881. if opts.AssigneeID > 0 {
  882. sess.And("issue.assignee_id=?", opts.AssigneeID)
  883. }
  884. if opts.PosterID > 0 {
  885. sess.And("issue.poster_id=?", opts.PosterID)
  886. }
  887. if opts.MentionedID > 0 {
  888. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  889. And("issue_user.is_mentioned = ?", true).
  890. And("issue_user.uid = ?", opts.MentionedID)
  891. }
  892. if opts.MilestoneID > 0 {
  893. sess.And("issue.milestone_id=?", opts.MilestoneID)
  894. }
  895. switch opts.IsPull {
  896. case util.OptionalBoolTrue:
  897. sess.And("issue.is_pull=?", true)
  898. case util.OptionalBoolFalse:
  899. sess.And("issue.is_pull=?", false)
  900. }
  901. sortIssuesSession(sess, opts.SortType)
  902. if len(opts.Labels) > 0 && opts.Labels != "0" {
  903. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  904. if err != nil {
  905. return nil, err
  906. }
  907. if len(labelIDs) > 0 {
  908. sess.
  909. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  910. In("issue_label.label_id", labelIDs)
  911. }
  912. }
  913. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  914. if err := sess.Find(&issues); err != nil {
  915. return nil, fmt.Errorf("Find: %v", err)
  916. }
  917. // FIXME: use IssueList to improve performance.
  918. for i := range issues {
  919. if err := issues[i].LoadAttributes(); err != nil {
  920. return nil, fmt.Errorf("LoadAttributes [%d]: %v", issues[i].ID, err)
  921. }
  922. }
  923. return issues, nil
  924. }
  925. // .___ ____ ___
  926. // | | ______ ________ __ ____ | | \______ ___________
  927. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  928. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  929. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  930. // \/ \/ \/ \/ \/
  931. // IssueUser represents an issue-user relation.
  932. type IssueUser struct {
  933. ID int64 `xorm:"pk autoincr"`
  934. UID int64 `xorm:"INDEX"` // User ID.
  935. IssueID int64
  936. RepoID int64 `xorm:"INDEX"`
  937. MilestoneID int64
  938. IsRead bool
  939. IsAssigned bool
  940. IsMentioned bool
  941. IsPoster bool
  942. IsClosed bool
  943. }
  944. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  945. assignees, err := repo.getAssignees(e)
  946. if err != nil {
  947. return fmt.Errorf("getAssignees: %v", err)
  948. }
  949. // Poster can be anyone, append later if not one of assignees.
  950. isPosterAssignee := false
  951. // Leave a seat for poster itself to append later, but if poster is one of assignee
  952. // and just waste 1 unit is cheaper than re-allocate memory once.
  953. issueUsers := make([]*IssueUser, 0, len(assignees)+1)
  954. for _, assignee := range assignees {
  955. isPoster := assignee.ID == issue.PosterID
  956. issueUsers = append(issueUsers, &IssueUser{
  957. IssueID: issue.ID,
  958. RepoID: repo.ID,
  959. UID: assignee.ID,
  960. IsPoster: isPoster,
  961. IsAssigned: assignee.ID == issue.AssigneeID,
  962. })
  963. if !isPosterAssignee && isPoster {
  964. isPosterAssignee = true
  965. }
  966. }
  967. if !isPosterAssignee {
  968. issueUsers = append(issueUsers, &IssueUser{
  969. IssueID: issue.ID,
  970. RepoID: repo.ID,
  971. UID: issue.PosterID,
  972. IsPoster: true,
  973. })
  974. }
  975. if _, err = e.Insert(issueUsers); err != nil {
  976. return err
  977. }
  978. return nil
  979. }
  980. // NewIssueUsers adds new issue-user relations for new issue of repository.
  981. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  982. sess := x.NewSession()
  983. defer sessionRelease(sess)
  984. if err = sess.Begin(); err != nil {
  985. return err
  986. }
  987. if err = newIssueUsers(sess, repo, issue); err != nil {
  988. return err
  989. }
  990. return sess.Commit()
  991. }
  992. // PairsContains returns true when pairs list contains given issue.
  993. func PairsContains(ius []*IssueUser, issueID, uid int64) int {
  994. for i := range ius {
  995. if ius[i].IssueID == issueID &&
  996. ius[i].UID == uid {
  997. return i
  998. }
  999. }
  1000. return -1
  1001. }
  1002. // GetIssueUsers returns issue-user pairs by given repository and user.
  1003. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  1004. ius := make([]*IssueUser, 0, 10)
  1005. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  1006. return ius, err
  1007. }
  1008. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  1009. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  1010. if len(rids) == 0 {
  1011. return []*IssueUser{}, nil
  1012. }
  1013. ius := make([]*IssueUser, 0, 10)
  1014. sess := x.
  1015. Limit(20, (page-1)*20).
  1016. Where("is_closed=?", isClosed).
  1017. In("repo_id", rids)
  1018. err := sess.Find(&ius)
  1019. return ius, err
  1020. }
  1021. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  1022. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  1023. ius := make([]*IssueUser, 0, 10)
  1024. sess := x.
  1025. Limit(20, (page-1)*20).
  1026. Where("uid=?", uid).
  1027. And("is_closed=?", isClosed)
  1028. if rid > 0 {
  1029. sess.And("repo_id=?", rid)
  1030. }
  1031. switch filterMode {
  1032. case FilterModeAssign:
  1033. sess.And("is_assigned=?", true)
  1034. case FilterModeCreate:
  1035. sess.And("is_poster=?", true)
  1036. default:
  1037. return ius, nil
  1038. }
  1039. err := sess.Find(&ius)
  1040. return ius, err
  1041. }
  1042. // UpdateIssueMentions extracts mentioned people from content and
  1043. // updates issue-user relations for them.
  1044. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  1045. if len(mentions) == 0 {
  1046. return nil
  1047. }
  1048. for i := range mentions {
  1049. mentions[i] = strings.ToLower(mentions[i])
  1050. }
  1051. users := make([]*User, 0, len(mentions))
  1052. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  1053. return fmt.Errorf("find mentioned users: %v", err)
  1054. }
  1055. ids := make([]int64, 0, len(mentions))
  1056. for _, user := range users {
  1057. ids = append(ids, user.ID)
  1058. if !user.IsOrganization() || user.NumMembers == 0 {
  1059. continue
  1060. }
  1061. memberIDs := make([]int64, 0, user.NumMembers)
  1062. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  1063. if err != nil {
  1064. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  1065. }
  1066. for _, orgUser := range orgUsers {
  1067. memberIDs = append(memberIDs, orgUser.ID)
  1068. }
  1069. ids = append(ids, memberIDs...)
  1070. }
  1071. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  1072. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1073. }
  1074. return nil
  1075. }
  1076. // IssueStats represents issue statistic information.
  1077. type IssueStats struct {
  1078. OpenCount, ClosedCount int64
  1079. AllCount int64
  1080. AssignCount int64
  1081. CreateCount int64
  1082. MentionCount int64
  1083. }
  1084. // Filter modes.
  1085. const (
  1086. FilterModeAll = iota
  1087. FilterModeAssign
  1088. FilterModeCreate
  1089. FilterModeMention
  1090. )
  1091. func parseCountResult(results []map[string][]byte) int64 {
  1092. if len(results) == 0 {
  1093. return 0
  1094. }
  1095. for _, result := range results[0] {
  1096. return com.StrTo(string(result)).MustInt64()
  1097. }
  1098. return 0
  1099. }
  1100. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1101. type IssueStatsOptions struct {
  1102. RepoID int64
  1103. Labels string
  1104. MilestoneID int64
  1105. AssigneeID int64
  1106. MentionedID int64
  1107. PosterID int64
  1108. IsPull bool
  1109. IssueIDs []int64
  1110. }
  1111. // GetIssueStats returns issue statistic information by given conditions.
  1112. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1113. stats := &IssueStats{}
  1114. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1115. sess := x.
  1116. Where("issue.repo_id = ?", opts.RepoID).
  1117. And("is_pull = ?", opts.IsPull)
  1118. if len(opts.IssueIDs) > 0 {
  1119. sess.In("issue.id", opts.IssueIDs)
  1120. }
  1121. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1122. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1123. if err != nil {
  1124. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1125. } else if len(labelIDs) > 0 {
  1126. sess.Join("INNER", "issue_label", "issue.id = issue_id").
  1127. In("label_id", labelIDs)
  1128. }
  1129. }
  1130. if opts.MilestoneID > 0 {
  1131. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1132. }
  1133. if opts.AssigneeID > 0 {
  1134. sess.And("assignee_id = ?", opts.AssigneeID)
  1135. }
  1136. if opts.PosterID > 0 {
  1137. sess.And("poster_id = ?", opts.PosterID)
  1138. }
  1139. if opts.MentionedID > 0 {
  1140. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1141. And("issue_user.uid = ?", opts.MentionedID).
  1142. And("issue_user.is_mentioned = ?", true)
  1143. }
  1144. return sess
  1145. }
  1146. var err error
  1147. stats.OpenCount, err = countSession(opts).
  1148. And("is_closed = ?", false).
  1149. Count(&Issue{})
  1150. if err != nil {
  1151. return nil, err
  1152. }
  1153. stats.ClosedCount, err = countSession(opts).
  1154. And("is_closed = ?", true).
  1155. Count(&Issue{})
  1156. if err != nil {
  1157. return nil, err
  1158. }
  1159. return stats, nil
  1160. }
  1161. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1162. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  1163. stats := &IssueStats{}
  1164. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1165. sess := x.
  1166. Where("issue.is_closed = ?", isClosed).
  1167. And("issue.is_pull = ?", isPull)
  1168. if repoID > 0 {
  1169. sess.And("repo_id = ?", repoID)
  1170. } else if len(repoIDs) > 0 {
  1171. sess.In("repo_id", repoIDs)
  1172. }
  1173. return sess
  1174. }
  1175. stats.AssignCount, _ = countSession(false, isPull, repoID, repoIDs).
  1176. And("assignee_id = ?", uid).
  1177. Count(&Issue{})
  1178. stats.CreateCount, _ = countSession(false, isPull, repoID, repoIDs).
  1179. And("poster_id = ?", uid).
  1180. Count(&Issue{})
  1181. openCountSession := countSession(false, isPull, repoID, repoIDs)
  1182. closedCountSession := countSession(true, isPull, repoID, repoIDs)
  1183. switch filterMode {
  1184. case FilterModeAssign:
  1185. openCountSession.And("assignee_id = ?", uid)
  1186. closedCountSession.And("assignee_id = ?", uid)
  1187. case FilterModeCreate:
  1188. openCountSession.And("poster_id = ?", uid)
  1189. closedCountSession.And("poster_id = ?", uid)
  1190. }
  1191. stats.OpenCount, _ = openCountSession.Count(&Issue{})
  1192. stats.ClosedCount, _ = closedCountSession.Count(&Issue{})
  1193. return stats
  1194. }
  1195. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1196. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1197. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1198. sess := x.
  1199. Where("issue.repo_id = ?", isClosed).
  1200. And("is_pull = ?", isPull).
  1201. And("repo_id = ?", repoID)
  1202. return sess
  1203. }
  1204. openCountSession := countSession(false, isPull, repoID)
  1205. closedCountSession := countSession(true, isPull, repoID)
  1206. switch filterMode {
  1207. case FilterModeAssign:
  1208. openCountSession.And("assignee_id = ?", uid)
  1209. closedCountSession.And("assignee_id = ?", uid)
  1210. case FilterModeCreate:
  1211. openCountSession.And("poster_id = ?", uid)
  1212. closedCountSession.And("poster_id = ?", uid)
  1213. }
  1214. openResult, _ := openCountSession.Count(&Issue{})
  1215. closedResult, _ := closedCountSession.Count(&Issue{})
  1216. return openResult, closedResult
  1217. }
  1218. func updateIssue(e Engine, issue *Issue) error {
  1219. _, err := e.Id(issue.ID).AllCols().Update(issue)
  1220. if err != nil {
  1221. return err
  1222. }
  1223. UpdateIssueIndexer(issue)
  1224. return nil
  1225. }
  1226. // UpdateIssue updates all fields of given issue.
  1227. func UpdateIssue(issue *Issue) error {
  1228. return updateIssue(x, issue)
  1229. }
  1230. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  1231. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  1232. return err
  1233. }
  1234. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  1235. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  1236. return updateIssueUsersByStatus(x, issueID, isClosed)
  1237. }
  1238. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  1239. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE issue_id = ?", false, issue.ID); err != nil {
  1240. return err
  1241. }
  1242. // Assignee ID equals to 0 means clear assignee.
  1243. if issue.AssigneeID > 0 {
  1244. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE uid = ? AND issue_id = ?", true, issue.AssigneeID, issue.ID); err != nil {
  1245. return err
  1246. }
  1247. }
  1248. return updateIssue(e, issue)
  1249. }
  1250. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  1251. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  1252. sess := x.NewSession()
  1253. defer sessionRelease(sess)
  1254. if err = sess.Begin(); err != nil {
  1255. return err
  1256. }
  1257. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  1258. return err
  1259. }
  1260. return sess.Commit()
  1261. }
  1262. // UpdateIssueUserByRead updates issue-user relation for reading.
  1263. func UpdateIssueUserByRead(uid, issueID int64) error {
  1264. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  1265. return err
  1266. }
  1267. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
  1268. func UpdateIssueUsersByMentions(e Engine, issueID int64, uids []int64) error {
  1269. for _, uid := range uids {
  1270. iu := &IssueUser{
  1271. UID: uid,
  1272. IssueID: issueID,
  1273. }
  1274. has, err := e.Get(iu)
  1275. if err != nil {
  1276. return err
  1277. }
  1278. iu.IsMentioned = true
  1279. if has {
  1280. _, err = e.Id(iu.ID).AllCols().Update(iu)
  1281. } else {
  1282. _, err = e.Insert(iu)
  1283. }
  1284. if err != nil {
  1285. return err
  1286. }
  1287. }
  1288. return nil
  1289. }
  1290. // _____ .__.__ __
  1291. // / \ |__| | ____ _______/ |_ ____ ____ ____
  1292. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  1293. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  1294. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  1295. // \/ \/ \/ \/ \/
  1296. // Milestone represents a milestone of repository.
  1297. type Milestone struct {
  1298. ID int64 `xorm:"pk autoincr"`
  1299. RepoID int64 `xorm:"INDEX"`
  1300. Name string
  1301. Content string `xorm:"TEXT"`
  1302. RenderedContent string `xorm:"-"`
  1303. IsClosed bool
  1304. NumIssues int
  1305. NumClosedIssues int
  1306. NumOpenIssues int `xorm:"-"`
  1307. Completeness int // Percentage(1-100).
  1308. IsOverDue bool `xorm:"-"`
  1309. DeadlineString string `xorm:"-"`
  1310. Deadline time.Time `xorm:"-"`
  1311. DeadlineUnix int64
  1312. ClosedDate time.Time `xorm:"-"`
  1313. ClosedDateUnix int64
  1314. }
  1315. // BeforeInsert is invoked from XORM before inserting an object of this type.
  1316. func (m *Milestone) BeforeInsert() {
  1317. m.DeadlineUnix = m.Deadline.Unix()
  1318. }
  1319. // BeforeUpdate is invoked from XORM before updating this object.
  1320. func (m *Milestone) BeforeUpdate() {
  1321. if m.NumIssues > 0 {
  1322. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  1323. } else {
  1324. m.Completeness = 0
  1325. }
  1326. m.DeadlineUnix = m.Deadline.Unix()
  1327. m.ClosedDateUnix = m.ClosedDate.Unix()
  1328. }
  1329. // AfterSet is invoked from XORM after setting the value of a field of
  1330. // this object.
  1331. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  1332. switch colName {
  1333. case "num_closed_issues":
  1334. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  1335. case "deadline_unix":
  1336. m.Deadline = time.Unix(m.DeadlineUnix, 0).Local()
  1337. if m.Deadline.Year() == 9999 {
  1338. return
  1339. }
  1340. m.DeadlineString = m.Deadline.Format("2006-01-02")
  1341. if time.Now().Local().After(m.Deadline) {
  1342. m.IsOverDue = true
  1343. }
  1344. case "closed_date_unix":
  1345. m.ClosedDate = time.Unix(m.ClosedDateUnix, 0).Local()
  1346. }
  1347. }
  1348. // State returns string representation of milestone status.
  1349. func (m *Milestone) State() api.StateType {
  1350. if m.IsClosed {
  1351. return api.StateClosed
  1352. }
  1353. return api.StateOpen
  1354. }
  1355. // APIFormat returns this Milestone in API format.
  1356. func (m *Milestone) APIFormat() *api.Milestone {
  1357. apiMilestone := &api.Milestone{
  1358. ID: m.ID,
  1359. State: m.State(),
  1360. Title: m.Name,
  1361. Description: m.Content,
  1362. OpenIssues: m.NumOpenIssues,
  1363. ClosedIssues: m.NumClosedIssues,
  1364. }
  1365. if m.IsClosed {
  1366. apiMilestone.Closed = &m.ClosedDate
  1367. }
  1368. if m.Deadline.Year() < 9999 {
  1369. apiMilestone.Deadline = &m.Deadline
  1370. }
  1371. return apiMilestone
  1372. }
  1373. // NewMilestone creates new milestone of repository.
  1374. func NewMilestone(m *Milestone) (err error) {
  1375. sess := x.NewSession()
  1376. defer sessionRelease(sess)
  1377. if err = sess.Begin(); err != nil {
  1378. return err
  1379. }
  1380. if _, err = sess.Insert(m); err != nil {
  1381. return err
  1382. }
  1383. if _, err = sess.Exec("UPDATE `repository` SET num_milestones = num_milestones + 1 WHERE id = ?", m.RepoID); err != nil {
  1384. return err
  1385. }
  1386. return sess.Commit()
  1387. }
  1388. func getMilestoneByRepoID(e Engine, repoID, id int64) (*Milestone, error) {
  1389. m := &Milestone{
  1390. ID: id,
  1391. RepoID: repoID,
  1392. }
  1393. has, err := e.Get(m)
  1394. if err != nil {
  1395. return nil, err
  1396. } else if !has {
  1397. return nil, ErrMilestoneNotExist{id, repoID}
  1398. }
  1399. return m, nil
  1400. }
  1401. // GetMilestoneByRepoID returns the milestone in a repository.
  1402. func GetMilestoneByRepoID(repoID, id int64) (*Milestone, error) {
  1403. return getMilestoneByRepoID(x, repoID, id)
  1404. }
  1405. // GetMilestonesByRepoID returns all milestones of a repository.
  1406. func GetMilestonesByRepoID(repoID int64) ([]*Milestone, error) {
  1407. miles := make([]*Milestone, 0, 10)
  1408. return miles, x.Where("repo_id = ?", repoID).Find(&miles)
  1409. }
  1410. // GetMilestones returns a list of milestones of given repository and status.
  1411. func GetMilestones(repoID int64, page int, isClosed bool, sortType string) ([]*Milestone, error) {
  1412. miles := make([]*Milestone, 0, setting.UI.IssuePagingNum)
  1413. sess := x.Where("repo_id = ? AND is_closed = ?", repoID, isClosed)
  1414. if page > 0 {
  1415. sess = sess.Limit(setting.UI.IssuePagingNum, (page-1)*setting.UI.IssuePagingNum)
  1416. }
  1417. switch sortType {
  1418. case "furthestduedate":
  1419. sess.Desc("deadline_unix")
  1420. case "leastcomplete":
  1421. sess.Asc("completeness")
  1422. case "mostcomplete":
  1423. sess.Desc("completeness")
  1424. case "leastissues":
  1425. sess.Asc("num_issues")
  1426. case "mostissues":
  1427. sess.Desc("num_issues")
  1428. default:
  1429. sess.Asc("deadline_unix")
  1430. }
  1431. return miles, sess.Find(&miles)
  1432. }
  1433. func updateMilestone(e Engine, m *Milestone) error {
  1434. _, err := e.Id(m.ID).AllCols().Update(m)
  1435. return err
  1436. }
  1437. // UpdateMilestone updates information of given milestone.
  1438. func UpdateMilestone(m *Milestone) error {
  1439. return updateMilestone(x, m)
  1440. }
  1441. func countRepoMilestones(e Engine, repoID int64) int64 {
  1442. count, _ := e.
  1443. Where("repo_id=?", repoID).
  1444. Count(new(Milestone))
  1445. return count
  1446. }
  1447. // CountRepoMilestones returns number of milestones in given repository.
  1448. func CountRepoMilestones(repoID int64) int64 {
  1449. return countRepoMilestones(x, repoID)
  1450. }
  1451. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  1452. closed, _ := e.
  1453. Where("repo_id=? AND is_closed=?", repoID, true).
  1454. Count(new(Milestone))
  1455. return closed
  1456. }
  1457. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  1458. func CountRepoClosedMilestones(repoID int64) int64 {
  1459. return countRepoClosedMilestones(x, repoID)
  1460. }
  1461. // MilestoneStats returns number of open and closed milestones of given repository.
  1462. func MilestoneStats(repoID int64) (open int64, closed int64) {
  1463. open, _ = x.
  1464. Where("repo_id=? AND is_closed=?", repoID, false).
  1465. Count(new(Milestone))
  1466. return open, CountRepoClosedMilestones(repoID)
  1467. }
  1468. // ChangeMilestoneStatus changes the milestone open/closed status.
  1469. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  1470. repo, err := GetRepositoryByID(m.RepoID)
  1471. if err != nil {
  1472. return err
  1473. }
  1474. sess := x.NewSession()
  1475. defer sessionRelease(sess)
  1476. if err = sess.Begin(); err != nil {
  1477. return err
  1478. }
  1479. m.IsClosed = isClosed
  1480. if err = updateMilestone(sess, m); err != nil {
  1481. return err
  1482. }
  1483. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1484. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1485. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1486. return err
  1487. }
  1488. return sess.Commit()
  1489. }
  1490. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  1491. if issue.MilestoneID == 0 {
  1492. return nil
  1493. }
  1494. m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  1495. if err != nil {
  1496. return err
  1497. }
  1498. if issue.IsClosed {
  1499. m.NumOpenIssues--
  1500. m.NumClosedIssues++
  1501. } else {
  1502. m.NumOpenIssues++
  1503. m.NumClosedIssues--
  1504. }
  1505. return updateMilestone(e, m)
  1506. }
  1507. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  1508. // for the milestone associated with the given issue.
  1509. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  1510. sess := x.NewSession()
  1511. defer sessionRelease(sess)
  1512. if err = sess.Begin(); err != nil {
  1513. return err
  1514. }
  1515. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  1516. return err
  1517. }
  1518. return sess.Commit()
  1519. }
  1520. func changeMilestoneAssign(e *xorm.Session, issue *Issue, oldMilestoneID int64) error {
  1521. if oldMilestoneID > 0 {
  1522. m, err := getMilestoneByRepoID(e, issue.RepoID, oldMilestoneID)
  1523. if err != nil {
  1524. return err
  1525. }
  1526. m.NumIssues--
  1527. if issue.IsClosed {
  1528. m.NumClosedIssues--
  1529. }
  1530. if err = updateMilestone(e, m); err != nil {
  1531. return err
  1532. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id = 0 WHERE issue_id = ?", issue.ID); err != nil {
  1533. return err
  1534. }
  1535. }
  1536. if issue.MilestoneID > 0 {
  1537. m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  1538. if err != nil {
  1539. return err
  1540. }
  1541. m.NumIssues++
  1542. if issue.IsClosed {
  1543. m.NumClosedIssues++
  1544. }
  1545. if err = updateMilestone(e, m); err != nil {
  1546. return err
  1547. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id = ? WHERE issue_id = ?", m.ID, issue.ID); err != nil {
  1548. return err
  1549. }
  1550. }
  1551. return updateIssue(e, issue)
  1552. }
  1553. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1554. func ChangeMilestoneAssign(issue *Issue, oldMilestoneID int64) (err error) {
  1555. sess := x.NewSession()
  1556. defer sess.Close()
  1557. if err = sess.Begin(); err != nil {
  1558. return err
  1559. }
  1560. if err = changeMilestoneAssign(sess, issue, oldMilestoneID); err != nil {
  1561. return err
  1562. }
  1563. return sess.Commit()
  1564. }
  1565. // DeleteMilestoneByRepoID deletes a milestone from a repository.
  1566. func DeleteMilestoneByRepoID(repoID, id int64) error {
  1567. m, err := GetMilestoneByRepoID(repoID, id)
  1568. if err != nil {
  1569. if IsErrMilestoneNotExist(err) {
  1570. return nil
  1571. }
  1572. return err
  1573. }
  1574. repo, err := GetRepositoryByID(m.RepoID)
  1575. if err != nil {
  1576. return err
  1577. }
  1578. sess := x.NewSession()
  1579. defer sessionRelease(sess)
  1580. if err = sess.Begin(); err != nil {
  1581. return err
  1582. }
  1583. if _, err = sess.Id(m.ID).Delete(new(Milestone)); err != nil {
  1584. return err
  1585. }
  1586. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1587. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1588. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1589. return err
  1590. }
  1591. if _, err = sess.Exec("UPDATE `issue` SET milestone_id = 0 WHERE milestone_id = ?", m.ID); err != nil {
  1592. return err
  1593. } else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id = 0 WHERE milestone_id = ?", m.ID); err != nil {
  1594. return err
  1595. }
  1596. return sess.Commit()
  1597. }