Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

issue.go 49KB

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