issue.go 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "errors"
  7. "fmt"
  8. "io"
  9. "mime/multipart"
  10. "os"
  11. "path"
  12. "strings"
  13. "time"
  14. "github.com/Unknwon/com"
  15. "github.com/go-xorm/xorm"
  16. gouuid "github.com/satori/go.uuid"
  17. "github.com/gogits/gogs/modules/base"
  18. "github.com/gogits/gogs/modules/log"
  19. "github.com/gogits/gogs/modules/setting"
  20. )
  21. var (
  22. ErrWrongIssueCounter = errors.New("Invalid number of issues for this milestone")
  23. ErrAttachmentNotLinked = errors.New("Attachment does not belong to this issue")
  24. ErrMissingIssueNumber = errors.New("No issue number specified")
  25. )
  26. // Issue represents an issue or pull request of repository.
  27. type Issue struct {
  28. ID int64 `xorm:"pk autoincr"`
  29. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  30. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  31. Name string
  32. Repo *Repository `xorm:"-"`
  33. PosterID int64
  34. Poster *User `xorm:"-"`
  35. Labels []*Label `xorm:"-"`
  36. MilestoneID int64
  37. Milestone *Milestone `xorm:"-"`
  38. AssigneeID int64
  39. Assignee *User `xorm:"-"`
  40. IsRead bool `xorm:"-"`
  41. IsPull bool // Indicates whether is a pull request or not.
  42. *PullRequest `xorm:"-"`
  43. IsClosed bool
  44. Content string `xorm:"TEXT"`
  45. RenderedContent string `xorm:"-"`
  46. Priority int
  47. NumComments int
  48. Deadline time.Time `xorm:"-"`
  49. DeadlineUnix int64
  50. Created time.Time `xorm:"-"`
  51. CreatedUnix int64
  52. Updated time.Time `xorm:"-"`
  53. UpdatedUnix int64
  54. Attachments []*Attachment `xorm:"-"`
  55. Comments []*Comment `xorm:"-"`
  56. }
  57. <<<<<<< HEAD
  58. func (i *Issue) GetPoster() (err error) {
  59. i.Poster, err = GetUserById(i.PosterId)
  60. if err == ErrUserNotExist {
  61. i.Poster = &User{Name: "DeletedUser"}
  62. return nil
  63. }
  64. return err
  65. =======
  66. func (i *Issue) BeforeInsert() {
  67. i.CreatedUnix = time.Now().UTC().Unix()
  68. i.UpdatedUnix = i.CreatedUnix
  69. >>>>>>> upstream/master
  70. }
  71. func (i *Issue) BeforeUpdate() {
  72. i.UpdatedUnix = time.Now().UTC().Unix()
  73. i.DeadlineUnix = i.Deadline.UTC().Unix()
  74. }
  75. func (issue *Issue) loadAttributes(e Engine) (err error) {
  76. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  77. if err != nil {
  78. return fmt.Errorf("getRepositoryByID: %v", err)
  79. }
  80. return nil
  81. }
  82. func (issue *Issue) LoadAttributes() (err error) {
  83. return issue.loadAttributes(x)
  84. }
  85. func (i *Issue) AfterSet(colName string, _ xorm.Cell) {
  86. var err error
  87. switch colName {
  88. case "id":
  89. i.Attachments, err = GetAttachmentsByIssueID(i.ID)
  90. if err != nil {
  91. log.Error(3, "GetAttachmentsByIssueID[%d]: %v", i.ID, err)
  92. }
  93. i.Comments, err = GetCommentsByIssueID(i.ID)
  94. if err != nil {
  95. log.Error(3, "GetCommentsByIssueID[%d]: %v", i.ID, err)
  96. }
  97. i.Labels, err = GetLabelsByIssueID(i.ID)
  98. if err != nil {
  99. log.Error(3, "GetLabelsByIssueID[%d]: %v", i.ID, err)
  100. }
  101. case "poster_id":
  102. i.Poster, err = GetUserByID(i.PosterID)
  103. if err != nil {
  104. if IsErrUserNotExist(err) {
  105. i.PosterID = -1
  106. i.Poster = NewFakeUser()
  107. } else {
  108. log.Error(3, "GetUserByID[%d]: %v", i.ID, err)
  109. }
  110. return
  111. }
  112. case "milestone_id":
  113. if i.MilestoneID == 0 {
  114. return
  115. }
  116. i.Milestone, err = GetMilestoneByID(i.MilestoneID)
  117. if err != nil {
  118. log.Error(3, "GetMilestoneById[%d]: %v", i.ID, err)
  119. }
  120. case "assignee_id":
  121. if i.AssigneeID == 0 {
  122. return
  123. }
  124. i.Assignee, err = GetUserByID(i.AssigneeID)
  125. if err != nil {
  126. log.Error(3, "GetUserByID[%d]: %v", i.ID, err)
  127. }
  128. case "deadline_unix":
  129. i.Deadline = time.Unix(i.DeadlineUnix, 0).Local()
  130. case "created_unix":
  131. i.Created = time.Unix(i.CreatedUnix, 0).Local()
  132. case "updated_unix":
  133. i.Updated = time.Unix(i.UpdatedUnix, 0).Local()
  134. }
  135. }
  136. // HashTag returns unique hash tag for issue.
  137. func (i *Issue) HashTag() string {
  138. return "issue-" + com.ToStr(i.ID)
  139. }
  140. // State returns string representation of issue status.
  141. func (i *Issue) State() string {
  142. if i.IsClosed {
  143. return "closed"
  144. }
  145. return "open"
  146. }
  147. func (issue *Issue) FullLink() string {
  148. return fmt.Sprintf("%s/issues/%d", issue.Repo.FullLink(), issue.Index)
  149. }
  150. // IsPoster returns true if given user by ID is the poster.
  151. func (i *Issue) IsPoster(uid int64) bool {
  152. return i.PosterID == uid
  153. }
  154. func (i *Issue) hasLabel(e Engine, labelID int64) bool {
  155. return hasIssueLabel(e, i.ID, labelID)
  156. }
  157. // HasLabel returns true if issue has been labeled by given ID.
  158. func (i *Issue) HasLabel(labelID int64) bool {
  159. return i.hasLabel(x, labelID)
  160. }
  161. func (i *Issue) addLabel(e *xorm.Session, label *Label) error {
  162. return newIssueLabel(e, i, label)
  163. }
  164. // AddLabel adds new label to issue by given ID.
  165. func (i *Issue) AddLabel(label *Label) (err error) {
  166. sess := x.NewSession()
  167. defer sessionRelease(sess)
  168. if err = sess.Begin(); err != nil {
  169. return err
  170. }
  171. if err = i.addLabel(sess, label); err != nil {
  172. return err
  173. }
  174. return sess.Commit()
  175. }
  176. func (i *Issue) getLabels(e Engine) (err error) {
  177. if len(i.Labels) > 0 {
  178. return nil
  179. }
  180. i.Labels, err = getLabelsByIssueID(e, i.ID)
  181. if err != nil {
  182. return fmt.Errorf("getLabelsByIssueID: %v", err)
  183. }
  184. return nil
  185. }
  186. func (i *Issue) removeLabel(e *xorm.Session, label *Label) error {
  187. return deleteIssueLabel(e, i, label)
  188. }
  189. // RemoveLabel removes a label from issue by given ID.
  190. func (i *Issue) RemoveLabel(label *Label) (err error) {
  191. sess := x.NewSession()
  192. defer sessionRelease(sess)
  193. if err = sess.Begin(); err != nil {
  194. return err
  195. }
  196. if err = i.removeLabel(sess, label); err != nil {
  197. return err
  198. }
  199. return sess.Commit()
  200. }
  201. func (i *Issue) ClearLabels() (err error) {
  202. sess := x.NewSession()
  203. defer sessionRelease(sess)
  204. if err = sess.Begin(); err != nil {
  205. return err
  206. }
  207. if err = i.getLabels(sess); err != nil {
  208. return err
  209. }
  210. for idx := range i.Labels {
  211. if err = i.removeLabel(sess, i.Labels[idx]); err != nil {
  212. return err
  213. }
  214. }
  215. return sess.Commit()
  216. }
  217. func (i *Issue) GetAssignee() (err error) {
  218. if i.AssigneeID == 0 || i.Assignee != nil {
  219. return nil
  220. }
  221. i.Assignee, err = GetUserByID(i.AssigneeID)
  222. if IsErrUserNotExist(err) {
  223. return nil
  224. }
  225. return err
  226. }
  227. // ReadBy sets issue to be read by given user.
  228. func (i *Issue) ReadBy(uid int64) error {
  229. return UpdateIssueUserByRead(uid, i.ID)
  230. }
  231. func (i *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
  232. // Nothing should be performed if current status is same as target status
  233. if i.IsClosed == isClosed {
  234. return nil
  235. }
  236. i.IsClosed = isClosed
  237. if err = updateIssueCols(e, i, "is_closed"); err != nil {
  238. return err
  239. } else if err = updateIssueUsersByStatus(e, i.ID, isClosed); err != nil {
  240. return err
  241. }
  242. // Update issue count of labels
  243. if err = i.getLabels(e); err != nil {
  244. return err
  245. }
  246. for idx := range i.Labels {
  247. if i.IsClosed {
  248. i.Labels[idx].NumClosedIssues++
  249. } else {
  250. i.Labels[idx].NumClosedIssues--
  251. }
  252. if err = updateLabel(e, i.Labels[idx]); err != nil {
  253. return err
  254. }
  255. }
  256. // Update issue count of milestone
  257. if err = changeMilestoneIssueStats(e, i); err != nil {
  258. return err
  259. }
  260. // New action comment
  261. if _, err = createStatusComment(e, doer, repo, i); err != nil {
  262. return err
  263. }
  264. return nil
  265. }
  266. // ChangeStatus changes issue status to open or closed.
  267. func (i *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (err error) {
  268. sess := x.NewSession()
  269. defer sessionRelease(sess)
  270. if err = sess.Begin(); err != nil {
  271. return err
  272. }
  273. if err = i.changeStatus(sess, doer, repo, isClosed); err != nil {
  274. return err
  275. }
  276. return sess.Commit()
  277. }
  278. func (i *Issue) GetPullRequest() (err error) {
  279. if i.PullRequest != nil {
  280. return nil
  281. }
  282. i.PullRequest, err = GetPullRequestByIssueID(i.ID)
  283. return err
  284. }
  285. // It's caller's responsibility to create action.
  286. func newIssue(e *xorm.Session, repo *Repository, issue *Issue, labelIDs []int64, uuids []string, isPull bool) (err error) {
  287. issue.Name = strings.TrimSpace(issue.Name)
  288. issue.Index = repo.NextIssueIndex()
  289. if issue.AssigneeID > 0 {
  290. // Silently drop invalid assignee
  291. valid, err := hasAccess(e, &User{Id: issue.AssigneeID}, repo, ACCESS_MODE_WRITE)
  292. if err != nil {
  293. return fmt.Errorf("hasAccess: %v", err)
  294. } else if !valid {
  295. issue.AssigneeID = 0
  296. }
  297. }
  298. if _, err = e.Insert(issue); err != nil {
  299. return err
  300. }
  301. if isPull {
  302. _, err = e.Exec("UPDATE `repository` SET num_pulls=num_pulls+1 WHERE id=?", issue.RepoID)
  303. } else {
  304. _, err = e.Exec("UPDATE `repository` SET num_issues=num_issues+1 WHERE id=?", issue.RepoID)
  305. }
  306. if err != nil {
  307. return err
  308. }
  309. if len(labelIDs) > 0 {
  310. // During the session, SQLite3 dirver cannot handle retrieve objects after update something.
  311. // So we have to get all needed labels first.
  312. labels := make([]*Label, 0, len(labelIDs))
  313. if err = e.In("id", labelIDs).Find(&labels); err != nil {
  314. return fmt.Errorf("find all labels: %v", err)
  315. }
  316. for _, label := range labels {
  317. if label.RepoID != repo.ID {
  318. continue
  319. }
  320. if err = issue.addLabel(e, label); err != nil {
  321. return fmt.Errorf("addLabel: %v", err)
  322. }
  323. }
  324. }
  325. if issue.MilestoneID > 0 {
  326. if err = changeMilestoneAssign(e, 0, issue); err != nil {
  327. return err
  328. }
  329. }
  330. if err = newIssueUsers(e, repo, issue); err != nil {
  331. return err
  332. }
  333. // Check attachments.
  334. attachments := make([]*Attachment, 0, len(uuids))
  335. for _, uuid := range uuids {
  336. attach, err := getAttachmentByUUID(e, uuid)
  337. if err != nil {
  338. if IsErrAttachmentNotExist(err) {
  339. continue
  340. }
  341. return fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  342. }
  343. attachments = append(attachments, attach)
  344. }
  345. for i := range attachments {
  346. attachments[i].IssueID = issue.ID
  347. // No assign value could be 0, so ignore AllCols().
  348. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  349. return fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  350. }
  351. }
  352. return issue.loadAttributes(e)
  353. }
  354. // NewIssue creates new issue with labels for repository.
  355. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  356. sess := x.NewSession()
  357. defer sessionRelease(sess)
  358. if err = sess.Begin(); err != nil {
  359. return err
  360. }
  361. if err = newIssue(sess, repo, issue, labelIDs, uuids, false); err != nil {
  362. return fmt.Errorf("newIssue: %v", err)
  363. }
  364. if err = sess.Commit(); err != nil {
  365. return fmt.Errorf("Commit: %v", err)
  366. }
  367. // Notify watchers.
  368. act := &Action{
  369. ActUserID: issue.Poster.Id,
  370. ActUserName: issue.Poster.Name,
  371. ActEmail: issue.Poster.Email,
  372. OpType: ACTION_CREATE_ISSUE,
  373. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Name),
  374. RepoID: repo.ID,
  375. RepoUserName: repo.Owner.Name,
  376. RepoName: repo.Name,
  377. IsPrivate: repo.IsPrivate,
  378. }
  379. if err = NotifyWatchers(act); err != nil {
  380. log.Error(4, "NotifyWatchers: %v", err)
  381. } else if err = issue.MailParticipants(); err != nil {
  382. log.Error(4, "MailParticipants: %v", err)
  383. }
  384. return nil
  385. }
  386. // GetIssueByRef returns an Issue specified by a GFM reference.
  387. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  388. func GetIssueByRef(ref string) (*Issue, error) {
  389. n := strings.IndexByte(ref, byte('#'))
  390. if n == -1 {
  391. return nil, ErrMissingIssueNumber
  392. }
  393. index, err := com.StrTo(ref[n+1:]).Int64()
  394. if err != nil {
  395. return nil, err
  396. }
  397. repo, err := GetRepositoryByRef(ref[:n])
  398. if err != nil {
  399. return nil, err
  400. }
  401. issue, err := GetIssueByIndex(repo.ID, index)
  402. if err != nil {
  403. return nil, err
  404. }
  405. return issue, issue.LoadAttributes()
  406. }
  407. // GetIssueByIndex returns issue by given index in repository.
  408. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  409. issue := &Issue{
  410. RepoID: repoID,
  411. Index: index,
  412. }
  413. has, err := x.Get(issue)
  414. if err != nil {
  415. return nil, err
  416. } else if !has {
  417. return nil, ErrIssueNotExist{0, repoID, index}
  418. }
  419. return issue, issue.LoadAttributes()
  420. }
  421. // GetIssueByID returns an issue by given ID.
  422. func GetIssueByID(id int64) (*Issue, error) {
  423. issue := new(Issue)
  424. has, err := x.Id(id).Get(issue)
  425. if err != nil {
  426. return nil, err
  427. } else if !has {
  428. return nil, ErrIssueNotExist{id, 0, 0}
  429. }
  430. return issue, issue.LoadAttributes()
  431. }
  432. type IssuesOptions struct {
  433. UserID int64
  434. AssigneeID int64
  435. RepoID int64
  436. PosterID int64
  437. MilestoneID int64
  438. RepoIDs []int64
  439. Page int
  440. IsClosed bool
  441. IsMention bool
  442. IsPull bool
  443. Labels string
  444. SortType string
  445. }
  446. // Issues returns a list of issues by given conditions.
  447. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  448. if opts.Page <= 0 {
  449. opts.Page = 1
  450. }
  451. sess := x.Limit(setting.IssuePagingNum, (opts.Page-1)*setting.IssuePagingNum)
  452. if opts.RepoID > 0 {
  453. sess.Where("issue.repo_id=?", opts.RepoID).And("issue.is_closed=?", opts.IsClosed)
  454. } else if opts.RepoIDs != nil {
  455. // In case repository IDs are provided but actually no repository has issue.
  456. if len(opts.RepoIDs) == 0 {
  457. return make([]*Issue, 0), nil
  458. }
  459. sess.In("issue.repo_id", base.Int64sToStrings(opts.RepoIDs)).And("issue.is_closed=?", opts.IsClosed)
  460. } else {
  461. sess.Where("issue.is_closed=?", opts.IsClosed)
  462. }
  463. if opts.AssigneeID > 0 {
  464. sess.And("issue.assignee_id=?", opts.AssigneeID)
  465. } else if opts.PosterID > 0 {
  466. sess.And("issue.poster_id=?", opts.PosterID)
  467. }
  468. if opts.MilestoneID > 0 {
  469. sess.And("issue.milestone_id=?", opts.MilestoneID)
  470. }
  471. sess.And("issue.is_pull=?", opts.IsPull)
  472. switch opts.SortType {
  473. case "oldest":
  474. sess.Asc("issue.created_unix")
  475. case "recentupdate":
  476. sess.Desc("issue.updated_unix")
  477. case "leastupdate":
  478. sess.Asc("issue.updated_unix")
  479. case "mostcomment":
  480. sess.Desc("issue.num_comments")
  481. case "leastcomment":
  482. sess.Asc("issue.num_comments")
  483. case "priority":
  484. sess.Desc("issue.priority")
  485. default:
  486. sess.Desc("issue.created_unix")
  487. }
  488. if len(opts.Labels) > 0 && opts.Labels != "0" {
  489. labelIDs := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  490. if len(labelIDs) > 0 {
  491. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").In("issue.label_id", labelIDs)
  492. }
  493. }
  494. if opts.IsMention {
  495. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").And("issue_user.is_mentioned = ?", true)
  496. if opts.UserID > 0 {
  497. sess.And("issue_user.uid = ?", opts.UserID)
  498. }
  499. }
  500. issues := make([]*Issue, 0, setting.IssuePagingNum)
  501. return issues, sess.Find(&issues)
  502. }
  503. type IssueStatus int
  504. const (
  505. IS_OPEN = iota + 1
  506. IS_CLOSE
  507. )
  508. // GetIssueCountByPoster returns number of issues of repository by poster.
  509. func GetIssueCountByPoster(uid, rid int64, isClosed bool) int64 {
  510. count, _ := x.Where("repo_id=?", rid).And("poster_id=?", uid).And("is_closed=?", isClosed).Count(new(Issue))
  511. return count
  512. }
  513. // .___ ____ ___
  514. // | | ______ ________ __ ____ | | \______ ___________
  515. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  516. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  517. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  518. // \/ \/ \/ \/ \/
  519. // IssueUser represents an issue-user relation.
  520. type IssueUser struct {
  521. ID int64 `xorm:"pk autoincr"`
  522. UID int64 `xorm:"INDEX"` // User ID.
  523. IssueID int64
  524. RepoID int64 `xorm:"INDEX"`
  525. MilestoneID int64
  526. IsRead bool
  527. IsAssigned bool
  528. IsMentioned bool
  529. IsPoster bool
  530. IsClosed bool
  531. }
  532. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  533. users, err := repo.GetAssignees()
  534. if err != nil {
  535. return err
  536. }
  537. iu := &IssueUser{
  538. IssueID: issue.ID,
  539. RepoID: repo.ID,
  540. }
  541. // Poster can be anyone.
  542. isNeedAddPoster := true
  543. for _, u := range users {
  544. iu.ID = 0
  545. iu.UID = u.Id
  546. iu.IsPoster = iu.UID == issue.PosterID
  547. if isNeedAddPoster && iu.IsPoster {
  548. isNeedAddPoster = false
  549. }
  550. iu.IsAssigned = iu.UID == issue.AssigneeID
  551. if _, err = e.Insert(iu); err != nil {
  552. return err
  553. }
  554. }
  555. if isNeedAddPoster {
  556. iu.ID = 0
  557. iu.UID = issue.PosterID
  558. iu.IsPoster = true
  559. if _, err = e.Insert(iu); err != nil {
  560. return err
  561. }
  562. }
  563. return nil
  564. }
  565. // NewIssueUsers adds new issue-user relations for new issue of repository.
  566. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  567. sess := x.NewSession()
  568. defer sessionRelease(sess)
  569. if err = sess.Begin(); err != nil {
  570. return err
  571. }
  572. if err = newIssueUsers(sess, repo, issue); err != nil {
  573. return err
  574. }
  575. return sess.Commit()
  576. }
  577. // PairsContains returns true when pairs list contains given issue.
  578. func PairsContains(ius []*IssueUser, issueId, uid int64) int {
  579. for i := range ius {
  580. if ius[i].IssueID == issueId &&
  581. ius[i].UID == uid {
  582. return i
  583. }
  584. }
  585. return -1
  586. }
  587. // GetIssueUsers returns issue-user pairs by given repository and user.
  588. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  589. ius := make([]*IssueUser, 0, 10)
  590. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  591. return ius, err
  592. }
  593. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  594. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  595. if len(rids) == 0 {
  596. return []*IssueUser{}, nil
  597. }
  598. ius := make([]*IssueUser, 0, 10)
  599. sess := x.Limit(20, (page-1)*20).Where("is_closed=?", isClosed).In("repo_id", rids)
  600. err := sess.Find(&ius)
  601. return ius, err
  602. }
  603. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  604. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  605. ius := make([]*IssueUser, 0, 10)
  606. sess := x.Limit(20, (page-1)*20).Where("uid=?", uid).And("is_closed=?", isClosed)
  607. if rid > 0 {
  608. sess.And("repo_id=?", rid)
  609. }
  610. switch filterMode {
  611. case FM_ASSIGN:
  612. sess.And("is_assigned=?", true)
  613. case FM_CREATE:
  614. sess.And("is_poster=?", true)
  615. default:
  616. return ius, nil
  617. }
  618. err := sess.Find(&ius)
  619. return ius, err
  620. }
  621. // UpdateIssueMentions extracts mentioned people from content and
  622. // updates issue-user relations for them.
  623. func UpdateIssueMentions(issueID int64, mentions []string) error {
  624. if len(mentions) == 0 {
  625. return nil
  626. }
  627. for i := range mentions {
  628. mentions[i] = strings.ToLower(mentions[i])
  629. }
  630. users := make([]*User, 0, len(mentions))
  631. if err := x.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  632. return fmt.Errorf("find mentioned users: %v", err)
  633. }
  634. ids := make([]int64, 0, len(mentions))
  635. for _, user := range users {
  636. ids = append(ids, user.Id)
  637. if !user.IsOrganization() || user.NumMembers == 0 {
  638. continue
  639. }
  640. memberIDs := make([]int64, 0, user.NumMembers)
  641. orgUsers, err := GetOrgUsersByOrgID(user.Id)
  642. if err != nil {
  643. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.Id, err)
  644. }
  645. for _, orgUser := range orgUsers {
  646. memberIDs = append(memberIDs, orgUser.ID)
  647. }
  648. ids = append(ids, memberIDs...)
  649. }
  650. if err := UpdateIssueUsersByMentions(issueID, ids); err != nil {
  651. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  652. }
  653. return nil
  654. }
  655. // IssueStats represents issue statistic information.
  656. type IssueStats struct {
  657. OpenCount, ClosedCount int64
  658. AllCount int64
  659. AssignCount int64
  660. CreateCount int64
  661. MentionCount int64
  662. }
  663. // Filter modes.
  664. const (
  665. FM_ALL = iota
  666. FM_ASSIGN
  667. FM_CREATE
  668. FM_MENTION
  669. )
  670. func parseCountResult(results []map[string][]byte) int64 {
  671. if len(results) == 0 {
  672. return 0
  673. }
  674. for _, result := range results[0] {
  675. return com.StrTo(string(result)).MustInt64()
  676. }
  677. return 0
  678. }
  679. type IssueStatsOptions struct {
  680. RepoID int64
  681. UserID int64
  682. Labels string
  683. MilestoneID int64
  684. AssigneeID int64
  685. FilterMode int
  686. IsPull bool
  687. }
  688. // GetIssueStats returns issue statistic information by given conditions.
  689. func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
  690. stats := &IssueStats{}
  691. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  692. sess := x.Where("issue.repo_id = ?", opts.RepoID).And("is_pull = ?", opts.IsPull)
  693. if len(opts.Labels) > 0 && opts.Labels != "0" {
  694. labelIDs := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  695. if len(labelIDs) > 0 {
  696. sess.Join("INNER", "issue_label", "issue.id = issue_id").In("label_id", labelIDs)
  697. }
  698. }
  699. if opts.MilestoneID > 0 {
  700. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  701. }
  702. if opts.AssigneeID > 0 {
  703. sess.And("assignee_id = ?", opts.AssigneeID)
  704. }
  705. return sess
  706. }
  707. switch opts.FilterMode {
  708. case FM_ALL, FM_ASSIGN:
  709. stats.OpenCount, _ = countSession(opts).
  710. And("is_closed = ?", false).
  711. Count(&Issue{})
  712. stats.ClosedCount, _ = countSession(opts).
  713. And("is_closed = ?", true).
  714. Count(&Issue{})
  715. case FM_CREATE:
  716. stats.OpenCount, _ = countSession(opts).
  717. And("poster_id = ?", opts.UserID).
  718. And("is_closed = ?", false).
  719. Count(&Issue{})
  720. stats.ClosedCount, _ = countSession(opts).
  721. And("poster_id = ?", opts.UserID).
  722. And("is_closed = ?", true).
  723. Count(&Issue{})
  724. case FM_MENTION:
  725. stats.OpenCount, _ = countSession(opts).
  726. Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  727. And("issue_user.uid = ?", opts.UserID).
  728. And("issue_user.is_mentioned = ?", true).
  729. And("issue.is_closed = ?", false).
  730. Count(&Issue{})
  731. stats.ClosedCount, _ = countSession(opts).
  732. Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  733. And("issue_user.uid = ?", opts.UserID).
  734. And("issue_user.is_mentioned = ?", true).
  735. And("issue.is_closed = ?", true).
  736. Count(&Issue{})
  737. }
  738. return stats
  739. }
  740. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  741. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  742. stats := &IssueStats{}
  743. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  744. sess := x.Where("issue.is_closed = ?", isClosed).And("issue.is_pull = ?", isPull)
  745. if repoID > 0 || len(repoIDs) == 0 {
  746. sess.And("repo_id = ?", repoID)
  747. } else {
  748. sess.In("repo_id", repoIDs)
  749. }
  750. return sess
  751. }
  752. stats.AssignCount, _ = countSession(false, isPull, repoID, repoIDs).
  753. And("assignee_id = ?", uid).
  754. Count(&Issue{})
  755. stats.CreateCount, _ = countSession(false, isPull, repoID, repoIDs).
  756. And("assignee_id = ?", uid).
  757. Count(&Issue{})
  758. openCountSession := countSession(false, isPull, repoID, repoIDs)
  759. closedCountSession := countSession(true, isPull, repoID, repoIDs)
  760. switch filterMode {
  761. case FM_ASSIGN:
  762. openCountSession.And("assignee_id = ?", uid)
  763. closedCountSession.And("assignee_id = ?", uid)
  764. case FM_CREATE:
  765. openCountSession.And("poster_id = ?", uid)
  766. closedCountSession.And("poster_id = ?", uid)
  767. }
  768. stats.OpenCount, _ = openCountSession.Count(&Issue{})
  769. stats.ClosedCount, _ = closedCountSession.Count(&Issue{})
  770. return stats
  771. }
  772. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  773. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  774. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  775. sess := x.Where("issue.repo_id = ?", isClosed).
  776. And("is_pull = ?", isPull).
  777. And("repo_id = ?", repoID)
  778. return sess
  779. }
  780. openCountSession := countSession(false, isPull, repoID)
  781. closedCountSession := countSession(true, isPull, repoID)
  782. switch filterMode {
  783. case FM_ASSIGN:
  784. openCountSession.And("assignee_id = ?", uid)
  785. closedCountSession.And("assignee_id = ?", uid)
  786. case FM_CREATE:
  787. openCountSession.And("poster_id = ?", uid)
  788. closedCountSession.And("poster_id = ?", uid)
  789. }
  790. openResult, _ := openCountSession.Count(&Issue{})
  791. closedResult, _ := closedCountSession.Count(&Issue{})
  792. return openResult, closedResult
  793. }
  794. func updateIssue(e Engine, issue *Issue) error {
  795. _, err := e.Id(issue.ID).AllCols().Update(issue)
  796. return err
  797. }
  798. // UpdateIssue updates all fields of given issue.
  799. func UpdateIssue(issue *Issue) error {
  800. return updateIssue(x, issue)
  801. }
  802. // updateIssueCols only updates values of specific columns for given issue.
  803. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  804. _, err := e.Id(issue.ID).Cols(cols...).Update(issue)
  805. return err
  806. }
  807. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  808. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  809. return err
  810. }
  811. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  812. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  813. return updateIssueUsersByStatus(x, issueID, isClosed)
  814. }
  815. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  816. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE issue_id=?", false, issue.ID); err != nil {
  817. return err
  818. }
  819. // Assignee ID equals to 0 means clear assignee.
  820. if issue.AssigneeID > 0 {
  821. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE uid=? AND issue_id=?", true, issue.AssigneeID, issue.ID); err != nil {
  822. return err
  823. }
  824. }
  825. return updateIssue(e, issue)
  826. }
  827. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  828. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  829. sess := x.NewSession()
  830. defer sessionRelease(sess)
  831. if err = sess.Begin(); err != nil {
  832. return err
  833. }
  834. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  835. return err
  836. }
  837. return sess.Commit()
  838. }
  839. // UpdateIssueUserByRead updates issue-user relation for reading.
  840. func UpdateIssueUserByRead(uid, issueID int64) error {
  841. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  842. return err
  843. }
  844. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
  845. func UpdateIssueUsersByMentions(issueID int64, uids []int64) error {
  846. for _, uid := range uids {
  847. iu := &IssueUser{
  848. UID: uid,
  849. IssueID: issueID,
  850. }
  851. has, err := x.Get(iu)
  852. if err != nil {
  853. return err
  854. }
  855. iu.IsMentioned = true
  856. if has {
  857. _, err = x.Id(iu.ID).AllCols().Update(iu)
  858. } else {
  859. _, err = x.Insert(iu)
  860. }
  861. if err != nil {
  862. return err
  863. }
  864. }
  865. return nil
  866. }
  867. // _____ .__.__ __
  868. // / \ |__| | ____ _______/ |_ ____ ____ ____
  869. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  870. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  871. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  872. // \/ \/ \/ \/ \/
  873. // Milestone represents a milestone of repository.
  874. type Milestone struct {
  875. ID int64 `xorm:"pk autoincr"`
  876. RepoID int64 `xorm:"INDEX"`
  877. Name string
  878. Content string `xorm:"TEXT"`
  879. RenderedContent string `xorm:"-"`
  880. IsClosed bool
  881. NumIssues int
  882. NumClosedIssues int
  883. NumOpenIssues int `xorm:"-"`
  884. Completeness int // Percentage(1-100).
  885. IsOverDue bool `xorm:"-"`
  886. DeadlineString string `xorm:"-"`
  887. Deadline time.Time `xorm:"-"`
  888. DeadlineUnix int64
  889. ClosedDate time.Time `xorm:"-"`
  890. ClosedDateUnix int64
  891. }
  892. func (m *Milestone) BeforeInsert() {
  893. m.DeadlineUnix = m.Deadline.UTC().Unix()
  894. }
  895. func (m *Milestone) BeforeUpdate() {
  896. if m.NumIssues > 0 {
  897. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  898. } else {
  899. m.Completeness = 0
  900. }
  901. m.DeadlineUnix = m.Deadline.UTC().Unix()
  902. m.ClosedDateUnix = m.ClosedDate.UTC().Unix()
  903. }
  904. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  905. switch colName {
  906. case "num_closed_issues":
  907. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  908. case "deadline_unix":
  909. m.Deadline = time.Unix(m.DeadlineUnix, 0).Local()
  910. if m.Deadline.Year() == 9999 {
  911. return
  912. }
  913. m.DeadlineString = m.Deadline.Format("2006-01-02")
  914. if time.Now().Local().After(m.Deadline) {
  915. m.IsOverDue = true
  916. }
  917. case "closed_date_unix":
  918. m.ClosedDate = time.Unix(m.ClosedDateUnix, 0).Local()
  919. }
  920. }
  921. // State returns string representation of milestone status.
  922. func (m *Milestone) State() string {
  923. if m.IsClosed {
  924. return "closed"
  925. }
  926. return "open"
  927. }
  928. // NewMilestone creates new milestone of repository.
  929. func NewMilestone(m *Milestone) (err error) {
  930. sess := x.NewSession()
  931. defer sessionRelease(sess)
  932. if err = sess.Begin(); err != nil {
  933. return err
  934. }
  935. if _, err = sess.Insert(m); err != nil {
  936. return err
  937. }
  938. if _, err = sess.Exec("UPDATE `repository` SET num_milestones=num_milestones+1 WHERE id=?", m.RepoID); err != nil {
  939. return err
  940. }
  941. return sess.Commit()
  942. }
  943. func getMilestoneByID(e Engine, id int64) (*Milestone, error) {
  944. m := &Milestone{ID: id}
  945. has, err := e.Get(m)
  946. if err != nil {
  947. return nil, err
  948. } else if !has {
  949. return nil, ErrMilestoneNotExist{id, 0}
  950. }
  951. return m, nil
  952. }
  953. // GetMilestoneByID returns the milestone of given ID.
  954. func GetMilestoneByID(id int64) (*Milestone, error) {
  955. return getMilestoneByID(x, id)
  956. }
  957. // GetRepoMilestoneByID returns the milestone of given ID and repository.
  958. func GetRepoMilestoneByID(repoID, milestoneID int64) (*Milestone, error) {
  959. m := &Milestone{ID: milestoneID, RepoID: repoID}
  960. has, err := x.Get(m)
  961. if err != nil {
  962. return nil, err
  963. } else if !has {
  964. return nil, ErrMilestoneNotExist{milestoneID, repoID}
  965. }
  966. return m, nil
  967. }
  968. // GetAllRepoMilestones returns all milestones of given repository.
  969. func GetAllRepoMilestones(repoID int64) ([]*Milestone, error) {
  970. miles := make([]*Milestone, 0, 10)
  971. return miles, x.Where("repo_id=?", repoID).Find(&miles)
  972. }
  973. // GetMilestones returns a list of milestones of given repository and status.
  974. func GetMilestones(repoID int64, page int, isClosed bool) ([]*Milestone, error) {
  975. miles := make([]*Milestone, 0, setting.IssuePagingNum)
  976. sess := x.Where("repo_id=? AND is_closed=?", repoID, isClosed)
  977. if page > 0 {
  978. sess = sess.Limit(setting.IssuePagingNum, (page-1)*setting.IssuePagingNum)
  979. }
  980. return miles, sess.Find(&miles)
  981. }
  982. func updateMilestone(e Engine, m *Milestone) error {
  983. _, err := e.Id(m.ID).AllCols().Update(m)
  984. return err
  985. }
  986. // UpdateMilestone updates information of given milestone.
  987. func UpdateMilestone(m *Milestone) error {
  988. return updateMilestone(x, m)
  989. }
  990. func countRepoMilestones(e Engine, repoID int64) int64 {
  991. count, _ := e.Where("repo_id=?", repoID).Count(new(Milestone))
  992. return count
  993. }
  994. // CountRepoMilestones returns number of milestones in given repository.
  995. func CountRepoMilestones(repoID int64) int64 {
  996. return countRepoMilestones(x, repoID)
  997. }
  998. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  999. closed, _ := e.Where("repo_id=? AND is_closed=?", repoID, true).Count(new(Milestone))
  1000. return closed
  1001. }
  1002. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  1003. func CountRepoClosedMilestones(repoID int64) int64 {
  1004. return countRepoClosedMilestones(x, repoID)
  1005. }
  1006. // MilestoneStats returns number of open and closed milestones of given repository.
  1007. func MilestoneStats(repoID int64) (open int64, closed int64) {
  1008. open, _ = x.Where("repo_id=? AND is_closed=?", repoID, false).Count(new(Milestone))
  1009. return open, CountRepoClosedMilestones(repoID)
  1010. }
  1011. // ChangeMilestoneStatus changes the milestone open/closed status.
  1012. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  1013. repo, err := GetRepositoryByID(m.RepoID)
  1014. if err != nil {
  1015. return err
  1016. }
  1017. sess := x.NewSession()
  1018. defer sessionRelease(sess)
  1019. if err = sess.Begin(); err != nil {
  1020. return err
  1021. }
  1022. m.IsClosed = isClosed
  1023. if err = updateMilestone(sess, m); err != nil {
  1024. return err
  1025. }
  1026. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1027. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1028. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1029. return err
  1030. }
  1031. return sess.Commit()
  1032. }
  1033. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  1034. if issue.MilestoneID == 0 {
  1035. return nil
  1036. }
  1037. m, err := getMilestoneByID(e, issue.MilestoneID)
  1038. if err != nil {
  1039. return err
  1040. }
  1041. if issue.IsClosed {
  1042. m.NumOpenIssues--
  1043. m.NumClosedIssues++
  1044. } else {
  1045. m.NumOpenIssues++
  1046. m.NumClosedIssues--
  1047. }
  1048. return updateMilestone(e, m)
  1049. }
  1050. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  1051. // for the milestone associated with the given issue.
  1052. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  1053. sess := x.NewSession()
  1054. defer sessionRelease(sess)
  1055. if err = sess.Begin(); err != nil {
  1056. return err
  1057. }
  1058. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  1059. return err
  1060. }
  1061. return sess.Commit()
  1062. }
  1063. func changeMilestoneAssign(e *xorm.Session, oldMid int64, issue *Issue) error {
  1064. if oldMid > 0 {
  1065. m, err := getMilestoneByID(e, oldMid)
  1066. if err != nil {
  1067. return err
  1068. }
  1069. m.NumIssues--
  1070. if issue.IsClosed {
  1071. m.NumClosedIssues--
  1072. }
  1073. if err = updateMilestone(e, m); err != nil {
  1074. return err
  1075. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE issue_id=?", issue.ID); err != nil {
  1076. return err
  1077. }
  1078. }
  1079. if issue.MilestoneID > 0 {
  1080. m, err := getMilestoneByID(e, issue.MilestoneID)
  1081. if err != nil {
  1082. return err
  1083. }
  1084. m.NumIssues++
  1085. if issue.IsClosed {
  1086. m.NumClosedIssues++
  1087. }
  1088. if m.NumIssues == 0 {
  1089. return ErrWrongIssueCounter
  1090. }
  1091. if err = updateMilestone(e, m); err != nil {
  1092. return err
  1093. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=? WHERE issue_id=?", m.ID, issue.ID); err != nil {
  1094. return err
  1095. }
  1096. }
  1097. return updateIssue(e, issue)
  1098. }
  1099. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1100. func ChangeMilestoneAssign(oldMid int64, issue *Issue) (err error) {
  1101. sess := x.NewSession()
  1102. defer sess.Close()
  1103. if err = sess.Begin(); err != nil {
  1104. return err
  1105. }
  1106. if err = changeMilestoneAssign(sess, oldMid, issue); err != nil {
  1107. return err
  1108. }
  1109. return sess.Commit()
  1110. }
  1111. // DeleteMilestoneByID deletes a milestone by given ID.
  1112. func DeleteMilestoneByID(id int64) error {
  1113. m, err := GetMilestoneByID(id)
  1114. if err != nil {
  1115. if IsErrMilestoneNotExist(err) {
  1116. return nil
  1117. }
  1118. return err
  1119. }
  1120. repo, err := GetRepositoryByID(m.RepoID)
  1121. if err != nil {
  1122. return err
  1123. }
  1124. sess := x.NewSession()
  1125. defer sessionRelease(sess)
  1126. if err = sess.Begin(); err != nil {
  1127. return err
  1128. }
  1129. if _, err = sess.Id(m.ID).Delete(new(Milestone)); err != nil {
  1130. return err
  1131. }
  1132. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1133. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1134. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1135. return err
  1136. }
  1137. if _, err = sess.Exec("UPDATE `issue` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1138. return err
  1139. } else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1140. return err
  1141. }
  1142. return sess.Commit()
  1143. }
  1144. // Attachment represent a attachment of issue/comment/release.
  1145. type Attachment struct {
  1146. ID int64 `xorm:"pk autoincr"`
  1147. UUID string `xorm:"uuid UNIQUE"`
  1148. IssueID int64 `xorm:"INDEX"`
  1149. CommentID int64
  1150. ReleaseID int64 `xorm:"INDEX"`
  1151. Name string
  1152. Created time.Time `xorm:"-"`
  1153. CreatedUnix int64
  1154. }
  1155. func (a *Attachment) BeforeInsert() {
  1156. a.CreatedUnix = time.Now().UTC().Unix()
  1157. }
  1158. func (a *Attachment) AfterSet(colName string, _ xorm.Cell) {
  1159. switch colName {
  1160. case "created_unix":
  1161. a.Created = time.Unix(a.CreatedUnix, 0).Local()
  1162. }
  1163. }
  1164. // AttachmentLocalPath returns where attachment is stored in local file system based on given UUID.
  1165. func AttachmentLocalPath(uuid string) string {
  1166. return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid)
  1167. }
  1168. // LocalPath returns where attachment is stored in local file system.
  1169. func (attach *Attachment) LocalPath() string {
  1170. return AttachmentLocalPath(attach.UUID)
  1171. }
  1172. // NewAttachment creates a new attachment object.
  1173. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) {
  1174. attach := &Attachment{
  1175. UUID: gouuid.NewV4().String(),
  1176. Name: name,
  1177. }
  1178. if err = os.MkdirAll(path.Dir(attach.LocalPath()), os.ModePerm); err != nil {
  1179. return nil, fmt.Errorf("MkdirAll: %v", err)
  1180. }
  1181. fw, err := os.Create(attach.LocalPath())
  1182. if err != nil {
  1183. return nil, fmt.Errorf("Create: %v", err)
  1184. }
  1185. defer fw.Close()
  1186. if _, err = fw.Write(buf); err != nil {
  1187. return nil, fmt.Errorf("Write: %v", err)
  1188. } else if _, err = io.Copy(fw, file); err != nil {
  1189. return nil, fmt.Errorf("Copy: %v", err)
  1190. }
  1191. sess := x.NewSession()
  1192. defer sessionRelease(sess)
  1193. if err := sess.Begin(); err != nil {
  1194. return nil, err
  1195. }
  1196. if _, err := sess.Insert(attach); err != nil {
  1197. return nil, err
  1198. }
  1199. return attach, sess.Commit()
  1200. }
  1201. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  1202. attach := &Attachment{UUID: uuid}
  1203. has, err := x.Get(attach)
  1204. if err != nil {
  1205. return nil, err
  1206. } else if !has {
  1207. return nil, ErrAttachmentNotExist{0, uuid}
  1208. }
  1209. return attach, nil
  1210. }
  1211. // GetAttachmentByUUID returns attachment by given UUID.
  1212. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  1213. return getAttachmentByUUID(x, uuid)
  1214. }
  1215. // GetAttachmentsByIssueID returns all attachments for given issue by ID.
  1216. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  1217. attachments := make([]*Attachment, 0, 10)
  1218. return attachments, x.Where("issue_id=? AND comment_id=0", issueID).Find(&attachments)
  1219. }
  1220. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  1221. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  1222. attachments := make([]*Attachment, 0, 10)
  1223. return attachments, x.Where("comment_id=?", commentID).Find(&attachments)
  1224. }
  1225. // DeleteAttachment deletes the given attachment and optionally the associated file.
  1226. func DeleteAttachment(a *Attachment, remove bool) error {
  1227. _, err := DeleteAttachments([]*Attachment{a}, remove)
  1228. return err
  1229. }
  1230. // DeleteAttachments deletes the given attachments and optionally the associated files.
  1231. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  1232. for i, a := range attachments {
  1233. if remove {
  1234. if err := os.Remove(a.LocalPath()); err != nil {
  1235. return i, err
  1236. }
  1237. }
  1238. if _, err := x.Delete(a.ID); err != nil {
  1239. return i, err
  1240. }
  1241. }
  1242. return len(attachments), nil
  1243. }
  1244. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  1245. func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
  1246. attachments, err := GetAttachmentsByIssueID(issueId)
  1247. if err != nil {
  1248. return 0, err
  1249. }
  1250. return DeleteAttachments(attachments, remove)
  1251. }
  1252. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  1253. func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
  1254. attachments, err := GetAttachmentsByCommentID(commentId)
  1255. if err != nil {
  1256. return 0, err
  1257. }
  1258. return DeleteAttachments(attachments, remove)
  1259. }