issue.go 35 KB

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