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