issue.go 38 KB

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