You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

issue.go 37KB

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