issue.go 43 KB

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