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

issue.go 37 kB

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