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

issue.go 38 kB

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