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
8 years ago
11 years ago
11 years ago
11 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
11 years ago
8 years ago
11 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
8 years ago
8 years ago
11 years ago
11 years ago
11 years ago
11 years ago
8 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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880
  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, issue, label, doer)
  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, label, doer); 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, doer *User, 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. }
  652. }
  653. if opts.Issue.AssigneeID > 0 {
  654. assignee, err := getUserByID(e, opts.Issue.AssigneeID)
  655. if err != nil && !IsErrUserNotExist(err) {
  656. return fmt.Errorf("getUserByID: %v", err)
  657. }
  658. // Assume assignee is invalid and drop silently.
  659. opts.Issue.AssigneeID = 0
  660. if assignee != nil {
  661. valid, err := hasAccess(e, assignee, opts.Repo, AccessModeWrite)
  662. if err != nil {
  663. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assignee.ID, opts.Repo.ID, err)
  664. }
  665. if valid {
  666. opts.Issue.AssigneeID = assignee.ID
  667. opts.Issue.Assignee = assignee
  668. }
  669. }
  670. }
  671. // Milestone and assignee validation should happen before insert actual object.
  672. if _, err = e.Insert(opts.Issue); err != nil {
  673. return err
  674. }
  675. if opts.Issue.MilestoneID > 0 {
  676. if err = changeMilestoneAssign(e, doer, opts.Issue, -1); err != nil {
  677. return err
  678. }
  679. }
  680. if opts.IsPull {
  681. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  682. } else {
  683. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  684. }
  685. if err != nil {
  686. return err
  687. }
  688. if len(opts.LableIDs) > 0 {
  689. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  690. // So we have to get all needed labels first.
  691. labels := make([]*Label, 0, len(opts.LableIDs))
  692. if err = e.In("id", opts.LableIDs).Find(&labels); err != nil {
  693. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LableIDs, err)
  694. }
  695. if err = opts.Issue.loadPoster(e); err != nil {
  696. return err
  697. }
  698. for _, label := range labels {
  699. // Silently drop invalid labels.
  700. if label.RepoID != opts.Repo.ID {
  701. continue
  702. }
  703. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  704. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  705. }
  706. }
  707. }
  708. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  709. return err
  710. }
  711. UpdateIssueIndexer(opts.Issue)
  712. if len(opts.Attachments) > 0 {
  713. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  714. if err != nil {
  715. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  716. }
  717. for i := 0; i < len(attachments); i++ {
  718. attachments[i].IssueID = opts.Issue.ID
  719. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  720. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  721. }
  722. }
  723. }
  724. return opts.Issue.loadAttributes(e)
  725. }
  726. // NewIssue creates new issue with labels for repository.
  727. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  728. sess := x.NewSession()
  729. defer sessionRelease(sess)
  730. if err = sess.Begin(); err != nil {
  731. return err
  732. }
  733. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  734. Repo: repo,
  735. Issue: issue,
  736. LableIDs: labelIDs,
  737. Attachments: uuids,
  738. }); err != nil {
  739. return fmt.Errorf("newIssue: %v", err)
  740. }
  741. if err = sess.Commit(); err != nil {
  742. return fmt.Errorf("Commit: %v", err)
  743. }
  744. if err = NotifyWatchers(&Action{
  745. ActUserID: issue.Poster.ID,
  746. ActUserName: issue.Poster.Name,
  747. OpType: ActionCreateIssue,
  748. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  749. RepoID: repo.ID,
  750. RepoUserName: repo.Owner.Name,
  751. RepoName: repo.Name,
  752. IsPrivate: repo.IsPrivate,
  753. }); err != nil {
  754. log.Error(4, "NotifyWatchers: %v", err)
  755. }
  756. if err = issue.MailParticipants(); err != nil {
  757. log.Error(4, "MailParticipants: %v", err)
  758. }
  759. return nil
  760. }
  761. // GetIssueByRef returns an Issue specified by a GFM reference.
  762. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  763. func GetIssueByRef(ref string) (*Issue, error) {
  764. n := strings.IndexByte(ref, byte('#'))
  765. if n == -1 {
  766. return nil, errMissingIssueNumber
  767. }
  768. index, err := com.StrTo(ref[n+1:]).Int64()
  769. if err != nil {
  770. return nil, err
  771. }
  772. repo, err := GetRepositoryByRef(ref[:n])
  773. if err != nil {
  774. return nil, err
  775. }
  776. issue, err := GetIssueByIndex(repo.ID, index)
  777. if err != nil {
  778. return nil, err
  779. }
  780. return issue, issue.LoadAttributes()
  781. }
  782. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  783. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  784. issue := &Issue{
  785. RepoID: repoID,
  786. Index: index,
  787. }
  788. has, err := x.Get(issue)
  789. if err != nil {
  790. return nil, err
  791. } else if !has {
  792. return nil, ErrIssueNotExist{0, repoID, index}
  793. }
  794. return issue, nil
  795. }
  796. // GetIssueByIndex returns issue by index in a repository.
  797. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  798. issue, err := GetRawIssueByIndex(repoID, index)
  799. if err != nil {
  800. return nil, err
  801. }
  802. return issue, issue.LoadAttributes()
  803. }
  804. func getIssueByID(e Engine, id int64) (*Issue, error) {
  805. issue := new(Issue)
  806. has, err := e.Id(id).Get(issue)
  807. if err != nil {
  808. return nil, err
  809. } else if !has {
  810. return nil, ErrIssueNotExist{id, 0, 0}
  811. }
  812. return issue, issue.LoadAttributes()
  813. }
  814. // GetIssueByID returns an issue by given ID.
  815. func GetIssueByID(id int64) (*Issue, error) {
  816. return getIssueByID(x, id)
  817. }
  818. // IssuesOptions represents options of an issue.
  819. type IssuesOptions struct {
  820. RepoID int64
  821. AssigneeID int64
  822. PosterID int64
  823. MentionedID int64
  824. MilestoneID int64
  825. RepoIDs []int64
  826. Page int
  827. IsClosed util.OptionalBool
  828. IsPull util.OptionalBool
  829. Labels string
  830. SortType string
  831. IssueIDs []int64
  832. }
  833. // sortIssuesSession sort an issues-related session based on the provided
  834. // sortType string
  835. func sortIssuesSession(sess *xorm.Session, sortType string) {
  836. switch sortType {
  837. case "oldest":
  838. sess.Asc("issue.created_unix")
  839. case "recentupdate":
  840. sess.Desc("issue.updated_unix")
  841. case "leastupdate":
  842. sess.Asc("issue.updated_unix")
  843. case "mostcomment":
  844. sess.Desc("issue.num_comments")
  845. case "leastcomment":
  846. sess.Asc("issue.num_comments")
  847. case "priority":
  848. sess.Desc("issue.priority")
  849. default:
  850. sess.Desc("issue.created_unix")
  851. }
  852. }
  853. // Issues returns a list of issues by given conditions.
  854. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  855. var sess *xorm.Session
  856. if opts.Page >= 0 {
  857. var start int
  858. if opts.Page == 0 {
  859. start = 0
  860. } else {
  861. start = (opts.Page - 1) * setting.UI.IssuePagingNum
  862. }
  863. sess = x.Limit(setting.UI.IssuePagingNum, start)
  864. } else {
  865. sess = x.NewSession()
  866. defer sess.Close()
  867. }
  868. if len(opts.IssueIDs) > 0 {
  869. sess.In("issue.id", opts.IssueIDs)
  870. }
  871. if opts.RepoID > 0 {
  872. sess.And("issue.repo_id=?", opts.RepoID)
  873. } else if len(opts.RepoIDs) > 0 {
  874. // In case repository IDs are provided but actually no repository has issue.
  875. sess.In("issue.repo_id", opts.RepoIDs)
  876. }
  877. switch opts.IsClosed {
  878. case util.OptionalBoolTrue:
  879. sess.And("issue.is_closed=?", true)
  880. case util.OptionalBoolFalse:
  881. sess.And("issue.is_closed=?", false)
  882. }
  883. if opts.AssigneeID > 0 {
  884. sess.And("issue.assignee_id=?", opts.AssigneeID)
  885. }
  886. if opts.PosterID > 0 {
  887. sess.And("issue.poster_id=?", opts.PosterID)
  888. }
  889. if opts.MentionedID > 0 {
  890. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  891. And("issue_user.is_mentioned = ?", true).
  892. And("issue_user.uid = ?", opts.MentionedID)
  893. }
  894. if opts.MilestoneID > 0 {
  895. sess.And("issue.milestone_id=?", opts.MilestoneID)
  896. }
  897. switch opts.IsPull {
  898. case util.OptionalBoolTrue:
  899. sess.And("issue.is_pull=?", true)
  900. case util.OptionalBoolFalse:
  901. sess.And("issue.is_pull=?", false)
  902. }
  903. sortIssuesSession(sess, opts.SortType)
  904. if len(opts.Labels) > 0 && opts.Labels != "0" {
  905. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  906. if err != nil {
  907. return nil, err
  908. }
  909. if len(labelIDs) > 0 {
  910. sess.
  911. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  912. In("issue_label.label_id", labelIDs)
  913. }
  914. }
  915. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  916. if err := sess.Find(&issues); err != nil {
  917. return nil, fmt.Errorf("Find: %v", err)
  918. }
  919. // FIXME: use IssueList to improve performance.
  920. for i := range issues {
  921. if err := issues[i].LoadAttributes(); err != nil {
  922. return nil, fmt.Errorf("LoadAttributes [%d]: %v", issues[i].ID, err)
  923. }
  924. }
  925. return issues, nil
  926. }
  927. // .___ ____ ___
  928. // | | ______ ________ __ ____ | | \______ ___________
  929. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  930. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  931. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  932. // \/ \/ \/ \/ \/
  933. // IssueUser represents an issue-user relation.
  934. type IssueUser struct {
  935. ID int64 `xorm:"pk autoincr"`
  936. UID int64 `xorm:"INDEX"` // User ID.
  937. IssueID int64
  938. RepoID int64 `xorm:"INDEX"`
  939. MilestoneID int64
  940. IsRead bool
  941. IsAssigned bool
  942. IsMentioned bool
  943. IsPoster bool
  944. IsClosed bool
  945. }
  946. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  947. assignees, err := repo.getAssignees(e)
  948. if err != nil {
  949. return fmt.Errorf("getAssignees: %v", err)
  950. }
  951. // Poster can be anyone, append later if not one of assignees.
  952. isPosterAssignee := false
  953. // Leave a seat for poster itself to append later, but if poster is one of assignee
  954. // and just waste 1 unit is cheaper than re-allocate memory once.
  955. issueUsers := make([]*IssueUser, 0, len(assignees)+1)
  956. for _, assignee := range assignees {
  957. isPoster := assignee.ID == issue.PosterID
  958. issueUsers = append(issueUsers, &IssueUser{
  959. IssueID: issue.ID,
  960. RepoID: repo.ID,
  961. UID: assignee.ID,
  962. IsPoster: isPoster,
  963. IsAssigned: assignee.ID == issue.AssigneeID,
  964. })
  965. if !isPosterAssignee && isPoster {
  966. isPosterAssignee = true
  967. }
  968. }
  969. if !isPosterAssignee {
  970. issueUsers = append(issueUsers, &IssueUser{
  971. IssueID: issue.ID,
  972. RepoID: repo.ID,
  973. UID: issue.PosterID,
  974. IsPoster: true,
  975. })
  976. }
  977. if _, err = e.Insert(issueUsers); err != nil {
  978. return err
  979. }
  980. return nil
  981. }
  982. // NewIssueUsers adds new issue-user relations for new issue of repository.
  983. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  984. sess := x.NewSession()
  985. defer sessionRelease(sess)
  986. if err = sess.Begin(); err != nil {
  987. return err
  988. }
  989. if err = newIssueUsers(sess, repo, issue); err != nil {
  990. return err
  991. }
  992. return sess.Commit()
  993. }
  994. // PairsContains returns true when pairs list contains given issue.
  995. func PairsContains(ius []*IssueUser, issueID, uid int64) int {
  996. for i := range ius {
  997. if ius[i].IssueID == issueID &&
  998. ius[i].UID == uid {
  999. return i
  1000. }
  1001. }
  1002. return -1
  1003. }
  1004. // GetIssueUsers returns issue-user pairs by given repository and user.
  1005. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  1006. ius := make([]*IssueUser, 0, 10)
  1007. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  1008. return ius, err
  1009. }
  1010. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  1011. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  1012. if len(rids) == 0 {
  1013. return []*IssueUser{}, nil
  1014. }
  1015. ius := make([]*IssueUser, 0, 10)
  1016. sess := x.
  1017. Limit(20, (page-1)*20).
  1018. Where("is_closed=?", isClosed).
  1019. In("repo_id", rids)
  1020. err := sess.Find(&ius)
  1021. return ius, err
  1022. }
  1023. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  1024. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  1025. ius := make([]*IssueUser, 0, 10)
  1026. sess := x.
  1027. Limit(20, (page-1)*20).
  1028. Where("uid=?", uid).
  1029. And("is_closed=?", isClosed)
  1030. if rid > 0 {
  1031. sess.And("repo_id=?", rid)
  1032. }
  1033. switch filterMode {
  1034. case FilterModeAssign:
  1035. sess.And("is_assigned=?", true)
  1036. case FilterModeCreate:
  1037. sess.And("is_poster=?", true)
  1038. default:
  1039. return ius, nil
  1040. }
  1041. err := sess.Find(&ius)
  1042. return ius, err
  1043. }
  1044. // UpdateIssueMentions extracts mentioned people from content and
  1045. // updates issue-user relations for them.
  1046. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  1047. if len(mentions) == 0 {
  1048. return nil
  1049. }
  1050. for i := range mentions {
  1051. mentions[i] = strings.ToLower(mentions[i])
  1052. }
  1053. users := make([]*User, 0, len(mentions))
  1054. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  1055. return fmt.Errorf("find mentioned users: %v", err)
  1056. }
  1057. ids := make([]int64, 0, len(mentions))
  1058. for _, user := range users {
  1059. ids = append(ids, user.ID)
  1060. if !user.IsOrganization() || user.NumMembers == 0 {
  1061. continue
  1062. }
  1063. memberIDs := make([]int64, 0, user.NumMembers)
  1064. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  1065. if err != nil {
  1066. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  1067. }
  1068. for _, orgUser := range orgUsers {
  1069. memberIDs = append(memberIDs, orgUser.ID)
  1070. }
  1071. ids = append(ids, memberIDs...)
  1072. }
  1073. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  1074. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1075. }
  1076. return nil
  1077. }
  1078. // IssueStats represents issue statistic information.
  1079. type IssueStats struct {
  1080. OpenCount, ClosedCount int64
  1081. AllCount int64
  1082. AssignCount int64
  1083. CreateCount int64
  1084. MentionCount int64
  1085. }
  1086. // Filter modes.
  1087. const (
  1088. FilterModeAll = iota
  1089. FilterModeAssign
  1090. FilterModeCreate
  1091. FilterModeMention
  1092. )
  1093. func parseCountResult(results []map[string][]byte) int64 {
  1094. if len(results) == 0 {
  1095. return 0
  1096. }
  1097. for _, result := range results[0] {
  1098. return com.StrTo(string(result)).MustInt64()
  1099. }
  1100. return 0
  1101. }
  1102. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1103. type IssueStatsOptions struct {
  1104. RepoID int64
  1105. Labels string
  1106. MilestoneID int64
  1107. AssigneeID int64
  1108. MentionedID int64
  1109. PosterID int64
  1110. IsPull bool
  1111. IssueIDs []int64
  1112. }
  1113. // GetIssueStats returns issue statistic information by given conditions.
  1114. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1115. stats := &IssueStats{}
  1116. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1117. sess := x.
  1118. Where("issue.repo_id = ?", opts.RepoID).
  1119. And("is_pull = ?", opts.IsPull)
  1120. if len(opts.IssueIDs) > 0 {
  1121. sess.In("issue.id", opts.IssueIDs)
  1122. }
  1123. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1124. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1125. if err != nil {
  1126. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1127. } else if len(labelIDs) > 0 {
  1128. sess.Join("INNER", "issue_label", "issue.id = issue_id").
  1129. In("label_id", labelIDs)
  1130. }
  1131. }
  1132. if opts.MilestoneID > 0 {
  1133. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1134. }
  1135. if opts.AssigneeID > 0 {
  1136. sess.And("assignee_id = ?", opts.AssigneeID)
  1137. }
  1138. if opts.PosterID > 0 {
  1139. sess.And("poster_id = ?", opts.PosterID)
  1140. }
  1141. if opts.MentionedID > 0 {
  1142. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1143. And("issue_user.uid = ?", opts.MentionedID).
  1144. And("issue_user.is_mentioned = ?", true)
  1145. }
  1146. return sess
  1147. }
  1148. var err error
  1149. stats.OpenCount, err = countSession(opts).
  1150. And("is_closed = ?", false).
  1151. Count(&Issue{})
  1152. if err != nil {
  1153. return nil, err
  1154. }
  1155. stats.ClosedCount, err = countSession(opts).
  1156. And("is_closed = ?", true).
  1157. Count(&Issue{})
  1158. if err != nil {
  1159. return nil, err
  1160. }
  1161. return stats, nil
  1162. }
  1163. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1164. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  1165. stats := &IssueStats{}
  1166. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1167. sess := x.
  1168. Where("issue.is_closed = ?", isClosed).
  1169. And("issue.is_pull = ?", isPull)
  1170. if repoID > 0 {
  1171. sess.And("repo_id = ?", repoID)
  1172. } else if len(repoIDs) > 0 {
  1173. sess.In("repo_id", repoIDs)
  1174. }
  1175. return sess
  1176. }
  1177. stats.AssignCount, _ = countSession(false, isPull, repoID, repoIDs).
  1178. And("assignee_id = ?", uid).
  1179. Count(&Issue{})
  1180. stats.CreateCount, _ = countSession(false, isPull, repoID, repoIDs).
  1181. And("poster_id = ?", uid).
  1182. Count(&Issue{})
  1183. openCountSession := countSession(false, isPull, repoID, repoIDs)
  1184. closedCountSession := countSession(true, isPull, repoID, repoIDs)
  1185. switch filterMode {
  1186. case FilterModeAssign:
  1187. openCountSession.And("assignee_id = ?", uid)
  1188. closedCountSession.And("assignee_id = ?", uid)
  1189. case FilterModeCreate:
  1190. openCountSession.And("poster_id = ?", uid)
  1191. closedCountSession.And("poster_id = ?", uid)
  1192. }
  1193. stats.OpenCount, _ = openCountSession.Count(&Issue{})
  1194. stats.ClosedCount, _ = closedCountSession.Count(&Issue{})
  1195. return stats
  1196. }
  1197. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1198. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1199. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1200. sess := x.
  1201. Where("issue.repo_id = ?", isClosed).
  1202. And("is_pull = ?", isPull).
  1203. And("repo_id = ?", repoID)
  1204. return sess
  1205. }
  1206. openCountSession := countSession(false, isPull, repoID)
  1207. closedCountSession := countSession(true, isPull, repoID)
  1208. switch filterMode {
  1209. case FilterModeAssign:
  1210. openCountSession.And("assignee_id = ?", uid)
  1211. closedCountSession.And("assignee_id = ?", uid)
  1212. case FilterModeCreate:
  1213. openCountSession.And("poster_id = ?", uid)
  1214. closedCountSession.And("poster_id = ?", uid)
  1215. }
  1216. openResult, _ := openCountSession.Count(&Issue{})
  1217. closedResult, _ := closedCountSession.Count(&Issue{})
  1218. return openResult, closedResult
  1219. }
  1220. func updateIssue(e Engine, issue *Issue) error {
  1221. _, err := e.Id(issue.ID).AllCols().Update(issue)
  1222. if err != nil {
  1223. return err
  1224. }
  1225. UpdateIssueIndexer(issue)
  1226. return nil
  1227. }
  1228. // UpdateIssue updates all fields of given issue.
  1229. func UpdateIssue(issue *Issue) error {
  1230. return updateIssue(x, issue)
  1231. }
  1232. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  1233. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  1234. return err
  1235. }
  1236. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  1237. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  1238. return updateIssueUsersByStatus(x, issueID, isClosed)
  1239. }
  1240. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  1241. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE issue_id = ?", false, issue.ID); err != nil {
  1242. return err
  1243. }
  1244. // Assignee ID equals to 0 means clear assignee.
  1245. if issue.AssigneeID > 0 {
  1246. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE uid = ? AND issue_id = ?", true, issue.AssigneeID, issue.ID); err != nil {
  1247. return err
  1248. }
  1249. }
  1250. return updateIssue(e, issue)
  1251. }
  1252. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  1253. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  1254. sess := x.NewSession()
  1255. defer sessionRelease(sess)
  1256. if err = sess.Begin(); err != nil {
  1257. return err
  1258. }
  1259. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  1260. return err
  1261. }
  1262. return sess.Commit()
  1263. }
  1264. // UpdateIssueUserByRead updates issue-user relation for reading.
  1265. func UpdateIssueUserByRead(uid, issueID int64) error {
  1266. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  1267. return err
  1268. }
  1269. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
  1270. func UpdateIssueUsersByMentions(e Engine, issueID int64, uids []int64) error {
  1271. for _, uid := range uids {
  1272. iu := &IssueUser{
  1273. UID: uid,
  1274. IssueID: issueID,
  1275. }
  1276. has, err := e.Get(iu)
  1277. if err != nil {
  1278. return err
  1279. }
  1280. iu.IsMentioned = true
  1281. if has {
  1282. _, err = e.Id(iu.ID).AllCols().Update(iu)
  1283. } else {
  1284. _, err = e.Insert(iu)
  1285. }
  1286. if err != nil {
  1287. return err
  1288. }
  1289. }
  1290. return nil
  1291. }
  1292. // _____ .__.__ __
  1293. // / \ |__| | ____ _______/ |_ ____ ____ ____
  1294. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  1295. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  1296. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  1297. // \/ \/ \/ \/ \/
  1298. // Milestone represents a milestone of repository.
  1299. type Milestone struct {
  1300. ID int64 `xorm:"pk autoincr"`
  1301. RepoID int64 `xorm:"INDEX"`
  1302. Name string
  1303. Content string `xorm:"TEXT"`
  1304. RenderedContent string `xorm:"-"`
  1305. IsClosed bool
  1306. NumIssues int
  1307. NumClosedIssues int
  1308. NumOpenIssues int `xorm:"-"`
  1309. Completeness int // Percentage(1-100).
  1310. IsOverDue bool `xorm:"-"`
  1311. DeadlineString string `xorm:"-"`
  1312. Deadline time.Time `xorm:"-"`
  1313. DeadlineUnix int64
  1314. ClosedDate time.Time `xorm:"-"`
  1315. ClosedDateUnix int64
  1316. }
  1317. // BeforeInsert is invoked from XORM before inserting an object of this type.
  1318. func (m *Milestone) BeforeInsert() {
  1319. m.DeadlineUnix = m.Deadline.Unix()
  1320. }
  1321. // BeforeUpdate is invoked from XORM before updating this object.
  1322. func (m *Milestone) BeforeUpdate() {
  1323. if m.NumIssues > 0 {
  1324. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  1325. } else {
  1326. m.Completeness = 0
  1327. }
  1328. m.DeadlineUnix = m.Deadline.Unix()
  1329. m.ClosedDateUnix = m.ClosedDate.Unix()
  1330. }
  1331. // AfterSet is invoked from XORM after setting the value of a field of
  1332. // this object.
  1333. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  1334. switch colName {
  1335. case "num_closed_issues":
  1336. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  1337. case "deadline_unix":
  1338. m.Deadline = time.Unix(m.DeadlineUnix, 0).Local()
  1339. if m.Deadline.Year() == 9999 {
  1340. return
  1341. }
  1342. m.DeadlineString = m.Deadline.Format("2006-01-02")
  1343. if time.Now().Local().After(m.Deadline) {
  1344. m.IsOverDue = true
  1345. }
  1346. case "closed_date_unix":
  1347. m.ClosedDate = time.Unix(m.ClosedDateUnix, 0).Local()
  1348. }
  1349. }
  1350. // State returns string representation of milestone status.
  1351. func (m *Milestone) State() api.StateType {
  1352. if m.IsClosed {
  1353. return api.StateClosed
  1354. }
  1355. return api.StateOpen
  1356. }
  1357. // APIFormat returns this Milestone in API format.
  1358. func (m *Milestone) APIFormat() *api.Milestone {
  1359. apiMilestone := &api.Milestone{
  1360. ID: m.ID,
  1361. State: m.State(),
  1362. Title: m.Name,
  1363. Description: m.Content,
  1364. OpenIssues: m.NumOpenIssues,
  1365. ClosedIssues: m.NumClosedIssues,
  1366. }
  1367. if m.IsClosed {
  1368. apiMilestone.Closed = &m.ClosedDate
  1369. }
  1370. if m.Deadline.Year() < 9999 {
  1371. apiMilestone.Deadline = &m.Deadline
  1372. }
  1373. return apiMilestone
  1374. }
  1375. // NewMilestone creates new milestone of repository.
  1376. func NewMilestone(m *Milestone) (err error) {
  1377. sess := x.NewSession()
  1378. defer sessionRelease(sess)
  1379. if err = sess.Begin(); err != nil {
  1380. return err
  1381. }
  1382. if _, err = sess.Insert(m); err != nil {
  1383. return err
  1384. }
  1385. if _, err = sess.Exec("UPDATE `repository` SET num_milestones = num_milestones + 1 WHERE id = ?", m.RepoID); err != nil {
  1386. return err
  1387. }
  1388. return sess.Commit()
  1389. }
  1390. func getMilestoneByRepoID(e Engine, repoID, id int64) (*Milestone, error) {
  1391. m := &Milestone{
  1392. ID: id,
  1393. RepoID: repoID,
  1394. }
  1395. has, err := e.Get(m)
  1396. if err != nil {
  1397. return nil, err
  1398. } else if !has {
  1399. return nil, ErrMilestoneNotExist{id, repoID}
  1400. }
  1401. return m, nil
  1402. }
  1403. // GetMilestoneByRepoID returns the milestone in a repository.
  1404. func GetMilestoneByRepoID(repoID, id int64) (*Milestone, error) {
  1405. return getMilestoneByRepoID(x, repoID, id)
  1406. }
  1407. // GetMilestonesByRepoID returns all milestones of a repository.
  1408. func GetMilestonesByRepoID(repoID int64) ([]*Milestone, error) {
  1409. miles := make([]*Milestone, 0, 10)
  1410. return miles, x.Where("repo_id = ?", repoID).Find(&miles)
  1411. }
  1412. // GetMilestones returns a list of milestones of given repository and status.
  1413. func GetMilestones(repoID int64, page int, isClosed bool, sortType string) ([]*Milestone, error) {
  1414. miles := make([]*Milestone, 0, setting.UI.IssuePagingNum)
  1415. sess := x.Where("repo_id = ? AND is_closed = ?", repoID, isClosed)
  1416. if page > 0 {
  1417. sess = sess.Limit(setting.UI.IssuePagingNum, (page-1)*setting.UI.IssuePagingNum)
  1418. }
  1419. switch sortType {
  1420. case "furthestduedate":
  1421. sess.Desc("deadline_unix")
  1422. case "leastcomplete":
  1423. sess.Asc("completeness")
  1424. case "mostcomplete":
  1425. sess.Desc("completeness")
  1426. case "leastissues":
  1427. sess.Asc("num_issues")
  1428. case "mostissues":
  1429. sess.Desc("num_issues")
  1430. default:
  1431. sess.Asc("deadline_unix")
  1432. }
  1433. return miles, sess.Find(&miles)
  1434. }
  1435. func updateMilestone(e Engine, m *Milestone) error {
  1436. _, err := e.Id(m.ID).AllCols().Update(m)
  1437. return err
  1438. }
  1439. // UpdateMilestone updates information of given milestone.
  1440. func UpdateMilestone(m *Milestone) error {
  1441. return updateMilestone(x, m)
  1442. }
  1443. func countRepoMilestones(e Engine, repoID int64) int64 {
  1444. count, _ := e.
  1445. Where("repo_id=?", repoID).
  1446. Count(new(Milestone))
  1447. return count
  1448. }
  1449. // CountRepoMilestones returns number of milestones in given repository.
  1450. func CountRepoMilestones(repoID int64) int64 {
  1451. return countRepoMilestones(x, repoID)
  1452. }
  1453. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  1454. closed, _ := e.
  1455. Where("repo_id=? AND is_closed=?", repoID, true).
  1456. Count(new(Milestone))
  1457. return closed
  1458. }
  1459. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  1460. func CountRepoClosedMilestones(repoID int64) int64 {
  1461. return countRepoClosedMilestones(x, repoID)
  1462. }
  1463. // MilestoneStats returns number of open and closed milestones of given repository.
  1464. func MilestoneStats(repoID int64) (open int64, closed int64) {
  1465. open, _ = x.
  1466. Where("repo_id=? AND is_closed=?", repoID, false).
  1467. Count(new(Milestone))
  1468. return open, CountRepoClosedMilestones(repoID)
  1469. }
  1470. // ChangeMilestoneStatus changes the milestone open/closed status.
  1471. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  1472. repo, err := GetRepositoryByID(m.RepoID)
  1473. if err != nil {
  1474. return err
  1475. }
  1476. sess := x.NewSession()
  1477. defer sessionRelease(sess)
  1478. if err = sess.Begin(); err != nil {
  1479. return err
  1480. }
  1481. m.IsClosed = isClosed
  1482. if err = updateMilestone(sess, m); err != nil {
  1483. return err
  1484. }
  1485. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1486. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1487. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1488. return err
  1489. }
  1490. return sess.Commit()
  1491. }
  1492. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  1493. if issue.MilestoneID == 0 {
  1494. return nil
  1495. }
  1496. m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  1497. if err != nil {
  1498. return err
  1499. }
  1500. if issue.IsClosed {
  1501. m.NumOpenIssues--
  1502. m.NumClosedIssues++
  1503. } else {
  1504. m.NumOpenIssues++
  1505. m.NumClosedIssues--
  1506. }
  1507. return updateMilestone(e, m)
  1508. }
  1509. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  1510. // for the milestone associated with the given issue.
  1511. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  1512. sess := x.NewSession()
  1513. defer sessionRelease(sess)
  1514. if err = sess.Begin(); err != nil {
  1515. return err
  1516. }
  1517. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  1518. return err
  1519. }
  1520. return sess.Commit()
  1521. }
  1522. func changeMilestoneAssign(e *xorm.Session, doer *User, issue *Issue, oldMilestoneID int64) error {
  1523. if oldMilestoneID > 0 {
  1524. m, err := getMilestoneByRepoID(e, issue.RepoID, oldMilestoneID)
  1525. if err != nil {
  1526. return err
  1527. }
  1528. m.NumIssues--
  1529. if issue.IsClosed {
  1530. m.NumClosedIssues--
  1531. }
  1532. if err = updateMilestone(e, m); err != nil {
  1533. return err
  1534. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id = 0 WHERE issue_id = ?", issue.ID); err != nil {
  1535. return err
  1536. }
  1537. }
  1538. if issue.MilestoneID > 0 {
  1539. m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  1540. if err != nil {
  1541. return err
  1542. }
  1543. m.NumIssues++
  1544. if issue.IsClosed {
  1545. m.NumClosedIssues++
  1546. }
  1547. if err = updateMilestone(e, m); err != nil {
  1548. return err
  1549. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id = ? WHERE issue_id = ?", m.ID, issue.ID); err != nil {
  1550. return err
  1551. }
  1552. }
  1553. if err := issue.loadRepo(e); err != nil {
  1554. return err
  1555. }
  1556. if oldMilestoneID > 0 || issue.MilestoneID > 0 {
  1557. if _, err := createMilestoneComment(e, doer, issue.Repo, issue, oldMilestoneID, issue.MilestoneID); err != nil {
  1558. return err
  1559. }
  1560. }
  1561. return updateIssue(e, issue)
  1562. }
  1563. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1564. func ChangeMilestoneAssign(issue *Issue, doer *User, oldMilestoneID int64) (err error) {
  1565. sess := x.NewSession()
  1566. defer sess.Close()
  1567. if err = sess.Begin(); err != nil {
  1568. return err
  1569. }
  1570. if err = changeMilestoneAssign(sess, doer, issue, oldMilestoneID); err != nil {
  1571. return err
  1572. }
  1573. return sess.Commit()
  1574. }
  1575. // DeleteMilestoneByRepoID deletes a milestone from a repository.
  1576. func DeleteMilestoneByRepoID(repoID, id int64) error {
  1577. m, err := GetMilestoneByRepoID(repoID, id)
  1578. if err != nil {
  1579. if IsErrMilestoneNotExist(err) {
  1580. return nil
  1581. }
  1582. return err
  1583. }
  1584. repo, err := GetRepositoryByID(m.RepoID)
  1585. if err != nil {
  1586. return err
  1587. }
  1588. sess := x.NewSession()
  1589. defer sessionRelease(sess)
  1590. if err = sess.Begin(); err != nil {
  1591. return err
  1592. }
  1593. if _, err = sess.Id(m.ID).Delete(new(Milestone)); err != nil {
  1594. return err
  1595. }
  1596. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1597. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1598. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1599. return err
  1600. }
  1601. if _, err = sess.Exec("UPDATE `issue` SET milestone_id = 0 WHERE milestone_id = ?", m.ID); err != nil {
  1602. return err
  1603. } else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id = 0 WHERE milestone_id = ?", m.ID); err != nil {
  1604. return err
  1605. }
  1606. return sess.Commit()
  1607. }