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

issue.go 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515
  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. }