issue.go 46 KB

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