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 43KB

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
8 years ago
8 years ago
8 years ago
8 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
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
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
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
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
9 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
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
8 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "mime/multipart"
  11. "os"
  12. "path"
  13. "strconv"
  14. "strings"
  15. "time"
  16. "github.com/Unknwon/com"
  17. "github.com/go-xorm/xorm"
  18. "github.com/gogits/gogs/modules/base"
  19. "github.com/gogits/gogs/modules/log"
  20. "github.com/gogits/gogs/modules/setting"
  21. gouuid "github.com/gogits/gogs/modules/uuid"
  22. )
  23. var (
  24. ErrWrongIssueCounter = errors.New("Invalid number of issues for this milestone")
  25. ErrAttachmentNotLinked = errors.New("Attachment does not belong to this issue")
  26. ErrMissingIssueNumber = errors.New("No issue number specified")
  27. )
  28. // Issue represents an issue or pull request of repository.
  29. type Issue struct {
  30. ID int64 `xorm:"pk autoincr"`
  31. RepoID int64 `xorm:"INDEX"`
  32. Index int64 // Index in one repository.
  33. Name string
  34. Repo *Repository `xorm:"-"`
  35. PosterID int64
  36. Poster *User `xorm:"-"`
  37. Labels []*Label `xorm:"-"`
  38. MilestoneID int64
  39. Milestone *Milestone `xorm:"-"`
  40. AssigneeID int64
  41. Assignee *User `xorm:"-"`
  42. IsRead bool `xorm:"-"`
  43. IsPull bool // Indicates whether is a pull request or not.
  44. IsClosed bool
  45. Content string `xorm:"TEXT"`
  46. RenderedContent string `xorm:"-"`
  47. Priority int
  48. NumComments int
  49. Deadline time.Time
  50. Created time.Time `xorm:"CREATED"`
  51. Updated time.Time `xorm:"UPDATED"`
  52. Attachments []*Attachment `xorm:"-"`
  53. Comments []*Comment `xorm:"-"`
  54. }
  55. func (i *Issue) AfterSet(colName string, _ xorm.Cell) {
  56. var err error
  57. switch colName {
  58. case "id":
  59. i.Attachments, err = GetAttachmentsByIssueID(i.ID)
  60. if err != nil {
  61. log.Error(3, "GetAttachmentsByIssueID[%d]: %v", i.ID, err)
  62. }
  63. i.Comments, err = GetCommentsByIssueID(i.ID)
  64. if err != nil {
  65. log.Error(3, "GetCommentsByIssueID[%d]: %v", i.ID, err)
  66. }
  67. case "milestone_id":
  68. if i.MilestoneID == 0 {
  69. return
  70. }
  71. i.Milestone, err = GetMilestoneByID(i.MilestoneID)
  72. if err != nil {
  73. log.Error(3, "GetMilestoneById[%d]: %v", i.ID, err)
  74. }
  75. case "assignee_id":
  76. if i.AssigneeID == 0 {
  77. return
  78. }
  79. i.Assignee, err = GetUserByID(i.AssigneeID)
  80. if err != nil {
  81. log.Error(3, "GetUserByID[%d]: %v", i.ID, err)
  82. }
  83. case "created":
  84. i.Created = regulateTimeZone(i.Created)
  85. }
  86. }
  87. // HashTag returns unique hash tag for issue.
  88. func (i *Issue) HashTag() string {
  89. return "issue-" + com.ToStr(i.ID)
  90. }
  91. // IsPoster returns true if given user by ID is the poster.
  92. func (i *Issue) IsPoster(uid int64) bool {
  93. return i.PosterID == uid
  94. }
  95. func (i *Issue) GetPoster() (err error) {
  96. i.Poster, err = GetUserByID(i.PosterID)
  97. if IsErrUserNotExist(err) {
  98. i.PosterID = -1
  99. i.Poster = NewFakeUser()
  100. return nil
  101. }
  102. return err
  103. }
  104. func (i *Issue) hasLabel(e Engine, labelID int64) bool {
  105. return hasIssueLabel(e, i.ID, labelID)
  106. }
  107. // HasLabel returns true if issue has been labeled by given ID.
  108. func (i *Issue) HasLabel(labelID int64) bool {
  109. return i.hasLabel(x, labelID)
  110. }
  111. func (i *Issue) addLabel(e *xorm.Session, label *Label) error {
  112. return newIssueLabel(e, i, label)
  113. }
  114. // AddLabel adds new label to issue by given ID.
  115. func (i *Issue) AddLabel(label *Label) (err error) {
  116. sess := x.NewSession()
  117. defer sessionRelease(sess)
  118. if err = sess.Begin(); err != nil {
  119. return err
  120. }
  121. if err = i.addLabel(sess, label); err != nil {
  122. return err
  123. }
  124. return sess.Commit()
  125. }
  126. func (i *Issue) getLabels(e Engine) (err error) {
  127. if len(i.Labels) > 0 {
  128. return nil
  129. }
  130. i.Labels, err = getLabelsByIssueID(e, i.ID)
  131. if err != nil {
  132. return fmt.Errorf("getLabelsByIssueID: %v", err)
  133. }
  134. return nil
  135. }
  136. // GetLabels retrieves all labels of issue and assign to corresponding field.
  137. func (i *Issue) GetLabels() error {
  138. return i.getLabels(x)
  139. }
  140. func (i *Issue) removeLabel(e *xorm.Session, label *Label) error {
  141. return deleteIssueLabel(e, i, label)
  142. }
  143. // RemoveLabel removes a label from issue by given ID.
  144. func (i *Issue) RemoveLabel(label *Label) (err error) {
  145. sess := x.NewSession()
  146. defer sessionRelease(sess)
  147. if err = sess.Begin(); err != nil {
  148. return err
  149. }
  150. if err = i.removeLabel(sess, label); err != nil {
  151. return err
  152. }
  153. return sess.Commit()
  154. }
  155. func (i *Issue) ClearLabels() (err error) {
  156. sess := x.NewSession()
  157. defer sessionRelease(sess)
  158. if err = sess.Begin(); err != nil {
  159. return err
  160. }
  161. if err = i.getLabels(sess); err != nil {
  162. return err
  163. }
  164. for idx := range i.Labels {
  165. if err = i.removeLabel(sess, i.Labels[idx]); err != nil {
  166. return err
  167. }
  168. }
  169. return sess.Commit()
  170. }
  171. func (i *Issue) GetAssignee() (err error) {
  172. if i.AssigneeID == 0 || i.Assignee != nil {
  173. return nil
  174. }
  175. i.Assignee, err = GetUserByID(i.AssigneeID)
  176. if IsErrUserNotExist(err) {
  177. return nil
  178. }
  179. return err
  180. }
  181. // ReadBy sets issue to be read by given user.
  182. func (i *Issue) ReadBy(uid int64) error {
  183. return UpdateIssueUserByRead(uid, i.ID)
  184. }
  185. func (i *Issue) changeStatus(e *xorm.Session, doer *User, isClosed bool) (err error) {
  186. if i.IsClosed == isClosed {
  187. return nil
  188. }
  189. i.IsClosed = isClosed
  190. if err = updateIssue(e, i); err != nil {
  191. return err
  192. } else if err = updateIssueUsersByStatus(e, i.ID, isClosed); err != nil {
  193. return err
  194. }
  195. // Update labels.
  196. if err = i.getLabels(e); err != nil {
  197. return err
  198. }
  199. for idx := range i.Labels {
  200. if i.IsClosed {
  201. i.Labels[idx].NumClosedIssues++
  202. } else {
  203. i.Labels[idx].NumClosedIssues--
  204. }
  205. if err = updateLabel(e, i.Labels[idx]); err != nil {
  206. return err
  207. }
  208. }
  209. // Update milestone.
  210. if err = changeMilestoneIssueStats(e, i); err != nil {
  211. return err
  212. }
  213. // New action comment.
  214. if _, err = createStatusComment(e, doer, i.Repo, i); err != nil {
  215. return err
  216. }
  217. return nil
  218. }
  219. // ChangeStatus changes issue status to open/closed.
  220. func (i *Issue) ChangeStatus(doer *User, isClosed bool) (err error) {
  221. sess := x.NewSession()
  222. defer sessionRelease(sess)
  223. if err = sess.Begin(); err != nil {
  224. return err
  225. }
  226. if err = i.changeStatus(sess, doer, isClosed); err != nil {
  227. return err
  228. }
  229. return sess.Commit()
  230. }
  231. // CreateIssue creates new issue with labels for repository.
  232. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  233. // Check attachments.
  234. attachments := make([]*Attachment, 0, len(uuids))
  235. for _, uuid := range uuids {
  236. attach, err := GetAttachmentByUUID(uuid)
  237. if err != nil {
  238. if IsErrAttachmentNotExist(err) {
  239. continue
  240. }
  241. return fmt.Errorf("GetAttachmentByUUID[%s]: %v", uuid, err)
  242. }
  243. attachments = append(attachments, attach)
  244. }
  245. sess := x.NewSession()
  246. defer sessionRelease(sess)
  247. if err = sess.Begin(); err != nil {
  248. return err
  249. }
  250. if _, err = sess.Insert(issue); err != nil {
  251. return err
  252. } else if _, err = sess.Exec("UPDATE `repository` SET num_issues=num_issues+1 WHERE id=?", issue.RepoID); err != nil {
  253. return err
  254. }
  255. var label *Label
  256. for _, id := range labelIDs {
  257. if id == 0 {
  258. continue
  259. }
  260. label, err = getLabelByID(sess, id)
  261. if err != nil {
  262. return err
  263. }
  264. if err = issue.addLabel(sess, label); err != nil {
  265. return fmt.Errorf("addLabel: %v", err)
  266. }
  267. }
  268. if issue.MilestoneID > 0 {
  269. if err = changeMilestoneAssign(sess, 0, issue); err != nil {
  270. return err
  271. }
  272. }
  273. if err = newIssueUsers(sess, repo, issue); err != nil {
  274. return err
  275. }
  276. for i := range attachments {
  277. attachments[i].IssueID = issue.ID
  278. // No assign value could be 0, so ignore AllCols().
  279. if _, err = sess.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  280. return fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  281. }
  282. }
  283. // Notify watchers.
  284. act := &Action{
  285. ActUserID: issue.Poster.Id,
  286. ActUserName: issue.Poster.Name,
  287. ActEmail: issue.Poster.Email,
  288. OpType: CREATE_ISSUE,
  289. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Name),
  290. RepoID: repo.ID,
  291. RepoUserName: repo.Owner.Name,
  292. RepoName: repo.Name,
  293. IsPrivate: repo.IsPrivate,
  294. }
  295. if err = notifyWatchers(sess, act); err != nil {
  296. return err
  297. }
  298. return sess.Commit()
  299. }
  300. // GetIssueByRef returns an Issue specified by a GFM reference.
  301. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  302. func GetIssueByRef(ref string) (issue *Issue, err error) {
  303. var issueNumber int64
  304. var repo *Repository
  305. n := strings.IndexByte(ref, byte('#'))
  306. if n == -1 {
  307. return nil, ErrMissingIssueNumber
  308. }
  309. if issueNumber, err = strconv.ParseInt(ref[n+1:], 10, 64); err != nil {
  310. return
  311. }
  312. if repo, err = GetRepositoryByRef(ref[:n]); err != nil {
  313. return
  314. }
  315. return GetIssueByIndex(repo.ID, issueNumber)
  316. }
  317. // GetIssueByIndex returns issue by given index in repository.
  318. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  319. issue := &Issue{
  320. RepoID: repoID,
  321. Index: index,
  322. }
  323. has, err := x.Get(issue)
  324. if err != nil {
  325. return nil, err
  326. } else if !has {
  327. return nil, ErrIssueNotExist{0, repoID, index}
  328. }
  329. return issue, nil
  330. }
  331. // GetIssueByID returns an issue by given ID.
  332. func GetIssueByID(id int64) (*Issue, error) {
  333. issue := new(Issue)
  334. has, err := x.Id(id).Get(issue)
  335. if err != nil {
  336. return nil, err
  337. } else if !has {
  338. return nil, ErrIssueNotExist{id, 0, 0}
  339. }
  340. return issue, nil
  341. }
  342. // Issues returns a list of issues by given conditions.
  343. func Issues(uid, assigneeID, repoID, posterID, milestoneID int64, page int, isClosed, isMention bool, labels, sortType string) ([]*Issue, error) {
  344. sess := x.Limit(setting.IssuePagingNum, (page-1)*setting.IssuePagingNum)
  345. if repoID > 0 {
  346. sess.Where("issue.repo_id=?", repoID).And("issue.is_closed=?", isClosed)
  347. } else {
  348. sess.Where("issue.is_closed=?", isClosed)
  349. }
  350. if assigneeID > 0 {
  351. sess.And("issue.assignee_id=?", assigneeID)
  352. } else if posterID > 0 {
  353. sess.And("issue.poster_id=?", posterID)
  354. }
  355. if milestoneID > 0 {
  356. sess.And("issue.milestone_id=?", milestoneID)
  357. }
  358. switch sortType {
  359. case "oldest":
  360. sess.Asc("created")
  361. case "recentupdate":
  362. sess.Desc("updated")
  363. case "leastupdate":
  364. sess.Asc("updated")
  365. case "mostcomment":
  366. sess.Desc("num_comments")
  367. case "leastcomment":
  368. sess.Asc("num_comments")
  369. case "priority":
  370. sess.Desc("priority")
  371. default:
  372. sess.Desc("created")
  373. }
  374. labelIDs := base.StringsToInt64s(strings.Split(labels, ","))
  375. if len(labelIDs) > 0 {
  376. validJoin := false
  377. queryStr := "issue.id=issue_label.issue_id"
  378. for _, id := range labelIDs {
  379. if id == 0 {
  380. continue
  381. }
  382. validJoin = true
  383. queryStr += " AND issue_label.label_id=" + com.ToStr(id)
  384. }
  385. if validJoin {
  386. sess.Join("INNER", "issue_label", queryStr)
  387. }
  388. }
  389. if isMention {
  390. queryStr := "issue.id=issue_user.issue_id AND issue_user.is_mentioned=1"
  391. if uid > 0 {
  392. queryStr += " AND issue_user.uid=" + com.ToStr(uid)
  393. }
  394. sess.Join("INNER", "issue_user", queryStr)
  395. }
  396. issues := make([]*Issue, 0, setting.IssuePagingNum)
  397. return issues, sess.Find(&issues)
  398. }
  399. type IssueStatus int
  400. const (
  401. IS_OPEN = iota + 1
  402. IS_CLOSE
  403. )
  404. // GetIssueCountByPoster returns number of issues of repository by poster.
  405. func GetIssueCountByPoster(uid, rid int64, isClosed bool) int64 {
  406. count, _ := x.Where("repo_id=?", rid).And("poster_id=?", uid).And("is_closed=?", isClosed).Count(new(Issue))
  407. return count
  408. }
  409. // .___ ____ ___
  410. // | | ______ ________ __ ____ | | \______ ___________
  411. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  412. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  413. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  414. // \/ \/ \/ \/ \/
  415. // IssueUser represents an issue-user relation.
  416. type IssueUser struct {
  417. ID int64 `xorm:"pk autoincr"`
  418. UID int64 `xorm:"uid INDEX"` // User ID.
  419. IssueID int64
  420. RepoID int64 `xorm:"INDEX"`
  421. MilestoneID int64
  422. IsRead bool
  423. IsAssigned bool
  424. IsMentioned bool
  425. IsPoster bool
  426. IsClosed bool
  427. }
  428. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  429. users, err := repo.GetAssignees()
  430. if err != nil {
  431. return err
  432. }
  433. iu := &IssueUser{
  434. IssueID: issue.ID,
  435. RepoID: repo.ID,
  436. }
  437. // Poster can be anyone.
  438. isNeedAddPoster := true
  439. for _, u := range users {
  440. iu.ID = 0
  441. iu.UID = u.Id
  442. iu.IsPoster = iu.UID == issue.PosterID
  443. if isNeedAddPoster && iu.IsPoster {
  444. isNeedAddPoster = false
  445. }
  446. iu.IsAssigned = iu.UID == issue.AssigneeID
  447. if _, err = e.Insert(iu); err != nil {
  448. return err
  449. }
  450. }
  451. if isNeedAddPoster {
  452. iu.ID = 0
  453. iu.UID = issue.PosterID
  454. iu.IsPoster = true
  455. if _, err = e.Insert(iu); err != nil {
  456. return err
  457. }
  458. }
  459. return nil
  460. }
  461. // NewIssueUsers adds new issue-user relations for new issue of repository.
  462. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  463. sess := x.NewSession()
  464. defer sessionRelease(sess)
  465. if err = sess.Begin(); err != nil {
  466. return err
  467. }
  468. if err = newIssueUsers(sess, repo, issue); err != nil {
  469. return err
  470. }
  471. return sess.Commit()
  472. }
  473. // PairsContains returns true when pairs list contains given issue.
  474. func PairsContains(ius []*IssueUser, issueId, uid int64) int {
  475. for i := range ius {
  476. if ius[i].IssueID == issueId &&
  477. ius[i].UID == uid {
  478. return i
  479. }
  480. }
  481. return -1
  482. }
  483. // GetIssueUsers returns issue-user pairs by given repository and user.
  484. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  485. ius := make([]*IssueUser, 0, 10)
  486. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  487. return ius, err
  488. }
  489. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  490. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  491. if len(rids) == 0 {
  492. return []*IssueUser{}, nil
  493. }
  494. buf := bytes.NewBufferString("")
  495. for _, rid := range rids {
  496. buf.WriteString("repo_id=")
  497. buf.WriteString(com.ToStr(rid))
  498. buf.WriteString(" OR ")
  499. }
  500. cond := strings.TrimSuffix(buf.String(), " OR ")
  501. ius := make([]*IssueUser, 0, 10)
  502. sess := x.Limit(20, (page-1)*20).Where("is_closed=?", isClosed)
  503. if len(cond) > 0 {
  504. sess.And(cond)
  505. }
  506. err := sess.Find(&ius)
  507. return ius, err
  508. }
  509. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  510. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  511. ius := make([]*IssueUser, 0, 10)
  512. sess := x.Limit(20, (page-1)*20).Where("uid=?", uid).And("is_closed=?", isClosed)
  513. if rid > 0 {
  514. sess.And("repo_id=?", rid)
  515. }
  516. switch filterMode {
  517. case FM_ASSIGN:
  518. sess.And("is_assigned=?", true)
  519. case FM_CREATE:
  520. sess.And("is_poster=?", true)
  521. default:
  522. return ius, nil
  523. }
  524. err := sess.Find(&ius)
  525. return ius, err
  526. }
  527. // IssueStats represents issue statistic information.
  528. type IssueStats struct {
  529. OpenCount, ClosedCount int64
  530. AllCount int64
  531. AssignCount int64
  532. CreateCount int64
  533. MentionCount int64
  534. }
  535. // Filter modes.
  536. const (
  537. FM_ALL = iota
  538. FM_ASSIGN
  539. FM_CREATE
  540. FM_MENTION
  541. )
  542. func parseCountResult(results []map[string][]byte) int64 {
  543. if len(results) == 0 {
  544. return 0
  545. }
  546. for _, result := range results[0] {
  547. return com.StrTo(string(result)).MustInt64()
  548. }
  549. return 0
  550. }
  551. // GetIssueStats returns issue statistic information by given conditions.
  552. func GetIssueStats(repoID, uid, labelID, milestoneID, assigneeID int64, filterMode int) *IssueStats {
  553. stats := &IssueStats{}
  554. queryStr := "SELECT COUNT(*) FROM `issue` "
  555. if labelID > 0 {
  556. queryStr += "INNER JOIN `issue_label` ON `issue`.id=`issue_label`.issue_id AND `issue_label`.label_id=" + com.ToStr(labelID)
  557. }
  558. baseCond := " WHERE issue.repo_id=? AND issue.is_closed=?"
  559. if milestoneID > 0 {
  560. baseCond += " AND issue.milestone_id=" + com.ToStr(milestoneID)
  561. }
  562. if assigneeID > 0 {
  563. baseCond += " AND assignee_id=" + com.ToStr(assigneeID)
  564. }
  565. switch filterMode {
  566. case FM_ALL, FM_ASSIGN:
  567. results, _ := x.Query(queryStr+baseCond, repoID, false)
  568. stats.OpenCount = parseCountResult(results)
  569. results, _ = x.Query(queryStr+baseCond, repoID, true)
  570. stats.ClosedCount = parseCountResult(results)
  571. case FM_CREATE:
  572. baseCond += " AND poster_id=?"
  573. results, _ := x.Query(queryStr+baseCond, repoID, false, uid)
  574. stats.OpenCount = parseCountResult(results)
  575. results, _ = x.Query(queryStr+baseCond, repoID, true, uid)
  576. stats.ClosedCount = parseCountResult(results)
  577. case FM_MENTION:
  578. queryStr += " INNER JOIN `issue_user` ON `issue`.id=`issue_user`.issue_id"
  579. baseCond += " AND `issue_user`.uid=? AND `issue_user`.is_mentioned=?"
  580. results, _ := x.Query(queryStr+baseCond, repoID, false, uid, true)
  581. stats.OpenCount = parseCountResult(results)
  582. results, _ = x.Query(queryStr+baseCond, repoID, true, uid, true)
  583. stats.ClosedCount = parseCountResult(results)
  584. }
  585. return stats
  586. }
  587. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  588. func GetUserIssueStats(repoID, uid int64, filterMode int) *IssueStats {
  589. stats := &IssueStats{}
  590. issue := new(Issue)
  591. stats.AssignCount, _ = x.Where("assignee_id=?", uid).And("is_closed=?", false).Count(issue)
  592. stats.CreateCount, _ = x.Where("poster_id=?", uid).And("is_closed=?", false).Count(issue)
  593. queryStr := "SELECT COUNT(*) FROM `issue` "
  594. baseCond := " WHERE issue.is_closed=?"
  595. if repoID > 0 {
  596. baseCond += " AND issue.repo_id=" + com.ToStr(repoID)
  597. }
  598. switch filterMode {
  599. case FM_ASSIGN:
  600. baseCond += " AND assignee_id=" + com.ToStr(uid)
  601. case FM_CREATE:
  602. baseCond += " AND poster_id=" + com.ToStr(uid)
  603. }
  604. results, _ := x.Query(queryStr+baseCond, false)
  605. stats.OpenCount = parseCountResult(results)
  606. results, _ = x.Query(queryStr+baseCond, true)
  607. stats.ClosedCount = parseCountResult(results)
  608. return stats
  609. }
  610. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  611. func GetRepoIssueStats(repoID, uid int64, filterMode int) (numOpen int64, numClosed int64) {
  612. queryStr := "SELECT COUNT(*) FROM `issue` "
  613. baseCond := " WHERE issue.repo_id=? AND issue.is_closed=?"
  614. switch filterMode {
  615. case FM_ASSIGN:
  616. baseCond += " AND assignee_id=" + com.ToStr(uid)
  617. case FM_CREATE:
  618. baseCond += " AND poster_id=" + com.ToStr(uid)
  619. }
  620. results, _ := x.Query(queryStr+baseCond, repoID, false)
  621. numOpen = parseCountResult(results)
  622. results, _ = x.Query(queryStr+baseCond, repoID, true)
  623. numClosed = parseCountResult(results)
  624. return numOpen, numClosed
  625. }
  626. func updateIssue(e Engine, issue *Issue) error {
  627. _, err := e.Id(issue.ID).AllCols().Update(issue)
  628. return err
  629. }
  630. // UpdateIssue updates information of issue.
  631. func UpdateIssue(issue *Issue) error {
  632. return updateIssue(x, issue)
  633. }
  634. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  635. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  636. return err
  637. }
  638. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  639. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  640. return updateIssueUsersByStatus(x, issueID, isClosed)
  641. }
  642. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  643. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE issue_id=?", false, issue.ID); err != nil {
  644. return err
  645. }
  646. // Assignee ID equals to 0 means clear assignee.
  647. if issue.AssigneeID > 0 {
  648. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE uid=? AND issue_id=?", true, issue.AssigneeID, issue.ID); err != nil {
  649. return err
  650. }
  651. }
  652. return updateIssue(e, issue)
  653. }
  654. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  655. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  656. sess := x.NewSession()
  657. defer sessionRelease(sess)
  658. if err = sess.Begin(); err != nil {
  659. return err
  660. }
  661. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  662. return err
  663. }
  664. return sess.Commit()
  665. }
  666. // UpdateIssueUserByRead updates issue-user relation for reading.
  667. func UpdateIssueUserByRead(uid, issueID int64) error {
  668. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  669. return err
  670. }
  671. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
  672. func UpdateIssueUsersByMentions(uids []int64, iid int64) error {
  673. for _, uid := range uids {
  674. iu := &IssueUser{UID: uid, IssueID: iid}
  675. has, err := x.Get(iu)
  676. if err != nil {
  677. return err
  678. }
  679. iu.IsMentioned = true
  680. if has {
  681. _, err = x.Id(iu.ID).AllCols().Update(iu)
  682. } else {
  683. _, err = x.Insert(iu)
  684. }
  685. if err != nil {
  686. return err
  687. }
  688. }
  689. return nil
  690. }
  691. // .____ ___. .__
  692. // | | _____ \_ |__ ____ | |
  693. // | | \__ \ | __ \_/ __ \| |
  694. // | |___ / __ \| \_\ \ ___/| |__
  695. // |_______ (____ /___ /\___ >____/
  696. // \/ \/ \/ \/
  697. // Label represents a label of repository for issues.
  698. type Label struct {
  699. ID int64 `xorm:"pk autoincr"`
  700. RepoID int64 `xorm:"INDEX"`
  701. Name string
  702. Color string `xorm:"VARCHAR(7)"`
  703. NumIssues int
  704. NumClosedIssues int
  705. NumOpenIssues int `xorm:"-"`
  706. IsChecked bool `xorm:"-"`
  707. }
  708. // CalOpenIssues calculates the open issues of label.
  709. func (m *Label) CalOpenIssues() {
  710. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  711. }
  712. // NewLabel creates new label of repository.
  713. func NewLabel(l *Label) error {
  714. _, err := x.Insert(l)
  715. return err
  716. }
  717. func getLabelByID(e Engine, id int64) (*Label, error) {
  718. if id <= 0 {
  719. return nil, ErrLabelNotExist{id}
  720. }
  721. l := &Label{ID: id}
  722. has, err := x.Get(l)
  723. if err != nil {
  724. return nil, err
  725. } else if !has {
  726. return nil, ErrLabelNotExist{l.ID}
  727. }
  728. return l, nil
  729. }
  730. // GetLabelByID returns a label by given ID.
  731. func GetLabelByID(id int64) (*Label, error) {
  732. return getLabelByID(x, id)
  733. }
  734. // GetLabelsByRepoID returns all labels that belong to given repository by ID.
  735. func GetLabelsByRepoID(repoID int64) ([]*Label, error) {
  736. labels := make([]*Label, 0, 10)
  737. return labels, x.Where("repo_id=?", repoID).Find(&labels)
  738. }
  739. func getLabelsByIssueID(e Engine, issueID int64) ([]*Label, error) {
  740. issueLabels, err := getIssueLabels(e, issueID)
  741. if err != nil {
  742. return nil, fmt.Errorf("getIssueLabels: %v", err)
  743. }
  744. var label *Label
  745. labels := make([]*Label, 0, len(issueLabels))
  746. for idx := range issueLabels {
  747. label, err = getLabelByID(e, issueLabels[idx].LabelID)
  748. if err != nil && !IsErrLabelNotExist(err) {
  749. return nil, fmt.Errorf("getLabelByID: %v", err)
  750. }
  751. labels = append(labels, label)
  752. }
  753. return labels, nil
  754. }
  755. // GetLabelsByIssueID returns all labels that belong to given issue by ID.
  756. func GetLabelsByIssueID(issueID int64) ([]*Label, error) {
  757. return getLabelsByIssueID(x, issueID)
  758. }
  759. func updateLabel(e Engine, l *Label) error {
  760. _, err := e.Id(l.ID).AllCols().Update(l)
  761. return err
  762. }
  763. // UpdateLabel updates label information.
  764. func UpdateLabel(l *Label) error {
  765. return updateLabel(x, l)
  766. }
  767. // DeleteLabel delete a label of given repository.
  768. func DeleteLabel(repoID, labelID int64) error {
  769. l, err := GetLabelByID(labelID)
  770. if err != nil {
  771. if IsErrLabelNotExist(err) {
  772. return nil
  773. }
  774. return err
  775. }
  776. sess := x.NewSession()
  777. defer sessionRelease(sess)
  778. if err = sess.Begin(); err != nil {
  779. return err
  780. }
  781. if _, err = x.Where("label_id=?", labelID).Delete(new(IssueLabel)); err != nil {
  782. return err
  783. } else if _, err = sess.Delete(l); err != nil {
  784. return err
  785. }
  786. return sess.Commit()
  787. }
  788. // .___ .____ ___. .__
  789. // | | ______ ________ __ ____ | | _____ \_ |__ ____ | |
  790. // | |/ ___// ___/ | \_/ __ \| | \__ \ | __ \_/ __ \| |
  791. // | |\___ \ \___ \| | /\ ___/| |___ / __ \| \_\ \ ___/| |__
  792. // |___/____ >____ >____/ \___ >_______ (____ /___ /\___ >____/
  793. // \/ \/ \/ \/ \/ \/ \/
  794. // IssueLabel represetns an issue-lable relation.
  795. type IssueLabel struct {
  796. ID int64 `xorm:"pk autoincr"`
  797. IssueID int64 `xorm:"UNIQUE(s)"`
  798. LabelID int64 `xorm:"UNIQUE(s)"`
  799. }
  800. func hasIssueLabel(e Engine, issueID, labelID int64) bool {
  801. has, _ := e.Where("issue_id=? AND label_id=?", issueID, labelID).Get(new(IssueLabel))
  802. return has
  803. }
  804. // HasIssueLabel returns true if issue has been labeled.
  805. func HasIssueLabel(issueID, labelID int64) bool {
  806. return hasIssueLabel(x, issueID, labelID)
  807. }
  808. func newIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  809. if _, err = e.Insert(&IssueLabel{
  810. IssueID: issue.ID,
  811. LabelID: label.ID,
  812. }); err != nil {
  813. return err
  814. }
  815. label.NumIssues++
  816. if issue.IsClosed {
  817. label.NumClosedIssues++
  818. }
  819. return updateLabel(e, label)
  820. }
  821. // NewIssueLabel creates a new issue-label relation.
  822. func NewIssueLabel(issue *Issue, label *Label) (err error) {
  823. sess := x.NewSession()
  824. defer sessionRelease(sess)
  825. if err = sess.Begin(); err != nil {
  826. return err
  827. }
  828. if err = newIssueLabel(sess, issue, label); err != nil {
  829. return err
  830. }
  831. return sess.Commit()
  832. }
  833. func getIssueLabels(e Engine, issueID int64) ([]*IssueLabel, error) {
  834. issueLabels := make([]*IssueLabel, 0, 10)
  835. return issueLabels, e.Where("issue_id=?", issueID).Asc("label_id").Find(&issueLabels)
  836. }
  837. // GetIssueLabels returns all issue-label relations of given issue by ID.
  838. func GetIssueLabels(issueID int64) ([]*IssueLabel, error) {
  839. return getIssueLabels(x, issueID)
  840. }
  841. func deleteIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  842. if _, err = e.Delete(&IssueLabel{
  843. IssueID: issue.ID,
  844. LabelID: label.ID,
  845. }); err != nil {
  846. return err
  847. }
  848. label.NumIssues--
  849. if issue.IsClosed {
  850. label.NumClosedIssues--
  851. }
  852. return updateLabel(e, label)
  853. }
  854. // DeleteIssueLabel deletes issue-label relation.
  855. func DeleteIssueLabel(issue *Issue, label *Label) (err error) {
  856. sess := x.NewSession()
  857. defer sessionRelease(sess)
  858. if err = sess.Begin(); err != nil {
  859. return err
  860. }
  861. if err = deleteIssueLabel(sess, issue, label); err != nil {
  862. return err
  863. }
  864. return sess.Commit()
  865. }
  866. // _____ .__.__ __
  867. // / \ |__| | ____ _______/ |_ ____ ____ ____
  868. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  869. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  870. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  871. // \/ \/ \/ \/ \/
  872. // Milestone represents a milestone of repository.
  873. type Milestone struct {
  874. ID int64 `xorm:"pk autoincr"`
  875. RepoID int64 `xorm:"INDEX"`
  876. Name string
  877. Content string `xorm:"TEXT"`
  878. RenderedContent string `xorm:"-"`
  879. IsClosed bool
  880. NumIssues int
  881. NumClosedIssues int
  882. NumOpenIssues int `xorm:"-"`
  883. Completeness int // Percentage(1-100).
  884. Deadline time.Time
  885. DeadlineString string `xorm:"-"`
  886. IsOverDue bool `xorm:"-"`
  887. ClosedDate time.Time
  888. }
  889. func (m *Milestone) BeforeUpdate() {
  890. if m.NumIssues > 0 {
  891. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  892. } else {
  893. m.Completeness = 0
  894. }
  895. }
  896. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  897. if colName == "deadline" {
  898. if m.Deadline.Year() == 9999 {
  899. return
  900. }
  901. m.DeadlineString = m.Deadline.Format("2006-01-02")
  902. if time.Now().After(m.Deadline) {
  903. m.IsOverDue = true
  904. }
  905. }
  906. }
  907. // CalOpenIssues calculates the open issues of milestone.
  908. func (m *Milestone) CalOpenIssues() {
  909. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  910. }
  911. // NewMilestone creates new milestone of repository.
  912. func NewMilestone(m *Milestone) (err error) {
  913. sess := x.NewSession()
  914. defer sessionRelease(sess)
  915. if err = sess.Begin(); err != nil {
  916. return err
  917. }
  918. if _, err = sess.Insert(m); err != nil {
  919. return err
  920. }
  921. if _, err = sess.Exec("UPDATE `repository` SET num_milestones=num_milestones+1 WHERE id=?", m.RepoID); err != nil {
  922. return err
  923. }
  924. return sess.Commit()
  925. }
  926. func getMilestoneByID(e Engine, id int64) (*Milestone, error) {
  927. m := &Milestone{ID: id}
  928. has, err := e.Get(m)
  929. if err != nil {
  930. return nil, err
  931. } else if !has {
  932. return nil, ErrMilestoneNotExist{id, 0}
  933. }
  934. return m, nil
  935. }
  936. // GetMilestoneByID returns the milestone of given ID.
  937. func GetMilestoneByID(id int64) (*Milestone, error) {
  938. return getMilestoneByID(x, id)
  939. }
  940. // GetRepoMilestoneByID returns the milestone of given ID and repository.
  941. func GetRepoMilestoneByID(repoID, milestoneID int64) (*Milestone, error) {
  942. m := &Milestone{ID: milestoneID, RepoID: repoID}
  943. has, err := x.Get(m)
  944. if err != nil {
  945. return nil, err
  946. } else if !has {
  947. return nil, ErrMilestoneNotExist{milestoneID, repoID}
  948. }
  949. return m, nil
  950. }
  951. // GetAllRepoMilestones returns all milestones of given repository.
  952. func GetAllRepoMilestones(repoID int64) ([]*Milestone, error) {
  953. miles := make([]*Milestone, 0, 10)
  954. return miles, x.Where("repo_id=?", repoID).Find(&miles)
  955. }
  956. // GetMilestones returns a list of milestones of given repository and status.
  957. func GetMilestones(repoID int64, page int, isClosed bool) ([]*Milestone, error) {
  958. miles := make([]*Milestone, 0, setting.IssuePagingNum)
  959. sess := x.Where("repo_id=? AND is_closed=?", repoID, isClosed)
  960. if page > 0 {
  961. sess = sess.Limit(setting.IssuePagingNum, (page-1)*setting.IssuePagingNum)
  962. }
  963. return miles, sess.Find(&miles)
  964. }
  965. func updateMilestone(e Engine, m *Milestone) error {
  966. _, err := e.Id(m.ID).AllCols().Update(m)
  967. return err
  968. }
  969. // UpdateMilestone updates information of given milestone.
  970. func UpdateMilestone(m *Milestone) error {
  971. return updateMilestone(x, m)
  972. }
  973. func countRepoMilestones(e Engine, repoID int64) int64 {
  974. count, _ := e.Where("repo_id=?", repoID).Count(new(Milestone))
  975. return count
  976. }
  977. // CountRepoMilestones returns number of milestones in given repository.
  978. func CountRepoMilestones(repoID int64) int64 {
  979. return countRepoMilestones(x, repoID)
  980. }
  981. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  982. closed, _ := e.Where("repo_id=? AND is_closed=?", repoID, true).Count(new(Milestone))
  983. return closed
  984. }
  985. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  986. func CountRepoClosedMilestones(repoID int64) int64 {
  987. return countRepoClosedMilestones(x, repoID)
  988. }
  989. // MilestoneStats returns number of open and closed milestones of given repository.
  990. func MilestoneStats(repoID int64) (open int64, closed int64) {
  991. open, _ = x.Where("repo_id=? AND is_closed=?", repoID, false).Count(new(Milestone))
  992. return open, CountRepoClosedMilestones(repoID)
  993. }
  994. // ChangeMilestoneStatus changes the milestone open/closed status.
  995. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  996. repo, err := GetRepositoryByID(m.RepoID)
  997. if err != nil {
  998. return err
  999. }
  1000. sess := x.NewSession()
  1001. defer sessionRelease(sess)
  1002. if err = sess.Begin(); err != nil {
  1003. return err
  1004. }
  1005. m.IsClosed = isClosed
  1006. if err = updateMilestone(sess, m); err != nil {
  1007. return err
  1008. }
  1009. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1010. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1011. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1012. return err
  1013. }
  1014. return sess.Commit()
  1015. }
  1016. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  1017. if issue.MilestoneID == 0 {
  1018. return nil
  1019. }
  1020. m, err := getMilestoneByID(e, issue.MilestoneID)
  1021. if err != nil {
  1022. return err
  1023. }
  1024. if issue.IsClosed {
  1025. m.NumOpenIssues--
  1026. m.NumClosedIssues++
  1027. } else {
  1028. m.NumOpenIssues++
  1029. m.NumClosedIssues--
  1030. }
  1031. return updateMilestone(e, m)
  1032. }
  1033. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  1034. // for the milestone associated witht the given issue.
  1035. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  1036. sess := x.NewSession()
  1037. defer sessionRelease(sess)
  1038. if err = sess.Begin(); err != nil {
  1039. return err
  1040. }
  1041. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  1042. return err
  1043. }
  1044. return sess.Commit()
  1045. }
  1046. func changeMilestoneAssign(e *xorm.Session, oldMid int64, issue *Issue) error {
  1047. if oldMid > 0 {
  1048. m, err := getMilestoneByID(e, oldMid)
  1049. if err != nil {
  1050. return err
  1051. }
  1052. m.NumIssues--
  1053. if issue.IsClosed {
  1054. m.NumClosedIssues--
  1055. }
  1056. if err = updateMilestone(e, m); err != nil {
  1057. return err
  1058. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE issue_id=?", issue.ID); err != nil {
  1059. return err
  1060. }
  1061. }
  1062. if issue.MilestoneID > 0 {
  1063. m, err := getMilestoneByID(e, issue.MilestoneID)
  1064. if err != nil {
  1065. return err
  1066. }
  1067. m.NumIssues++
  1068. if issue.IsClosed {
  1069. m.NumClosedIssues++
  1070. }
  1071. if m.NumIssues == 0 {
  1072. return ErrWrongIssueCounter
  1073. }
  1074. if err = updateMilestone(e, m); err != nil {
  1075. return err
  1076. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=? WHERE issue_id=?", m.ID, issue.ID); err != nil {
  1077. return err
  1078. }
  1079. }
  1080. return updateIssue(e, issue)
  1081. }
  1082. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1083. func ChangeMilestoneAssign(oldMid int64, issue *Issue) (err error) {
  1084. sess := x.NewSession()
  1085. defer sess.Close()
  1086. if err = sess.Begin(); err != nil {
  1087. return err
  1088. }
  1089. if err = changeMilestoneAssign(sess, oldMid, issue); err != nil {
  1090. return err
  1091. }
  1092. return sess.Commit()
  1093. }
  1094. // DeleteMilestoneByID deletes a milestone by given ID.
  1095. func DeleteMilestoneByID(mid int64) error {
  1096. m, err := GetMilestoneByID(mid)
  1097. if err != nil {
  1098. if IsErrMilestoneNotExist(err) {
  1099. return nil
  1100. }
  1101. return err
  1102. }
  1103. repo, err := GetRepositoryByID(m.RepoID)
  1104. if err != nil {
  1105. return err
  1106. }
  1107. sess := x.NewSession()
  1108. defer sessionRelease(sess)
  1109. if err = sess.Begin(); err != nil {
  1110. return err
  1111. }
  1112. if _, err = sess.Id(m.ID).Delete(m); err != nil {
  1113. return err
  1114. }
  1115. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1116. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1117. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1118. return err
  1119. }
  1120. if _, err = sess.Exec("UPDATE `issue` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1121. return err
  1122. } else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1123. return err
  1124. }
  1125. return sess.Commit()
  1126. }
  1127. // _________ __
  1128. // \_ ___ \ ____ _____ _____ ____ _____/ |_
  1129. // / \ \/ / _ \ / \ / \_/ __ \ / \ __\
  1130. // \ \___( <_> ) Y Y \ Y Y \ ___/| | \ |
  1131. // \______ /\____/|__|_| /__|_| /\___ >___| /__|
  1132. // \/ \/ \/ \/ \/
  1133. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  1134. type CommentType int
  1135. const (
  1136. // Plain comment, can be associated with a commit (CommitId > 0) and a line (Line > 0)
  1137. COMMENT_TYPE_COMMENT CommentType = iota
  1138. COMMENT_TYPE_REOPEN
  1139. COMMENT_TYPE_CLOSE
  1140. // References.
  1141. COMMENT_TYPE_ISSUE_REF
  1142. // Reference from a commit (not part of a pull request)
  1143. COMMENT_TYPE_COMMIT_REF
  1144. // Reference from a comment
  1145. COMMENT_TYPE_COMMENT_REF
  1146. // Reference from a pull request
  1147. COMMENT_TYPE_PULL_REF
  1148. )
  1149. type CommentTag int
  1150. const (
  1151. COMMENT_TAG_NONE CommentTag = iota
  1152. COMMENT_TAG_POSTER
  1153. COMMENT_TAG_ADMIN
  1154. COMMENT_TAG_OWNER
  1155. )
  1156. // Comment represents a comment in commit and issue page.
  1157. type Comment struct {
  1158. ID int64 `xorm:"pk autoincr"`
  1159. Type CommentType
  1160. PosterID int64
  1161. Poster *User `xorm:"-"`
  1162. IssueID int64 `xorm:"INDEX"`
  1163. CommitID int64
  1164. Line int64
  1165. Content string `xorm:"TEXT"`
  1166. RenderedContent string `xorm:"-"`
  1167. Created time.Time `xorm:"CREATED"`
  1168. Attachments []*Attachment `xorm:"-"`
  1169. // For view issue page.
  1170. ShowTag CommentTag `xorm:"-"`
  1171. }
  1172. func (c *Comment) AfterSet(colName string, _ xorm.Cell) {
  1173. var err error
  1174. switch colName {
  1175. case "id":
  1176. c.Attachments, err = GetAttachmentsByCommentID(c.ID)
  1177. if err != nil {
  1178. log.Error(3, "GetAttachmentsByCommentID[%d]: %v", c.ID, err)
  1179. }
  1180. case "poster_id":
  1181. c.Poster, err = GetUserByID(c.PosterID)
  1182. if err != nil {
  1183. if IsErrUserNotExist(err) {
  1184. c.PosterID = -1
  1185. c.Poster = NewFakeUser()
  1186. } else {
  1187. log.Error(3, "GetUserByID[%d]: %v", c.ID, err)
  1188. }
  1189. }
  1190. case "created":
  1191. c.Created = regulateTimeZone(c.Created)
  1192. }
  1193. }
  1194. func (c *Comment) AfterDelete() {
  1195. _, err := DeleteAttachmentsByComment(c.ID, true)
  1196. if err != nil {
  1197. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  1198. }
  1199. }
  1200. // HashTag returns unique hash tag for comment.
  1201. func (c *Comment) HashTag() string {
  1202. return "issuecomment-" + com.ToStr(c.ID)
  1203. }
  1204. // EventTag returns unique event hash tag for comment.
  1205. func (c *Comment) EventTag() string {
  1206. return "event-" + com.ToStr(c.ID)
  1207. }
  1208. func createComment(e *xorm.Session, u *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content string, uuids []string) (_ *Comment, err error) {
  1209. comment := &Comment{
  1210. PosterID: u.Id,
  1211. Type: cmtType,
  1212. IssueID: issue.ID,
  1213. CommitID: commitID,
  1214. Line: line,
  1215. Content: content,
  1216. }
  1217. if _, err = e.Insert(comment); err != nil {
  1218. return nil, err
  1219. }
  1220. // Check comment type.
  1221. switch cmtType {
  1222. case COMMENT_TYPE_COMMENT:
  1223. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", issue.ID); err != nil {
  1224. return nil, err
  1225. }
  1226. // Check attachments.
  1227. attachments := make([]*Attachment, 0, len(uuids))
  1228. for _, uuid := range uuids {
  1229. attach, err := getAttachmentByUUID(e, uuid)
  1230. if err != nil {
  1231. if IsErrAttachmentNotExist(err) {
  1232. continue
  1233. }
  1234. return nil, fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  1235. }
  1236. attachments = append(attachments, attach)
  1237. }
  1238. for i := range attachments {
  1239. attachments[i].IssueID = issue.ID
  1240. attachments[i].CommentID = comment.ID
  1241. // No assign value could be 0, so ignore AllCols().
  1242. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  1243. return nil, fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  1244. }
  1245. }
  1246. // Notify watchers.
  1247. act := &Action{
  1248. ActUserID: u.Id,
  1249. ActUserName: u.LowerName,
  1250. ActEmail: u.Email,
  1251. OpType: COMMENT_ISSUE,
  1252. Content: fmt.Sprintf("%d|%s", issue.Index, strings.Split(content, "\n")[0]),
  1253. RepoID: repo.ID,
  1254. RepoUserName: repo.Owner.LowerName,
  1255. RepoName: repo.LowerName,
  1256. IsPrivate: repo.IsPrivate,
  1257. }
  1258. if err = notifyWatchers(e, act); err != nil {
  1259. return nil, err
  1260. }
  1261. case COMMENT_TYPE_REOPEN:
  1262. if _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", repo.ID); err != nil {
  1263. return nil, err
  1264. }
  1265. case COMMENT_TYPE_CLOSE:
  1266. if _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", repo.ID); err != nil {
  1267. return nil, err
  1268. }
  1269. }
  1270. return comment, nil
  1271. }
  1272. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  1273. cmtType := COMMENT_TYPE_CLOSE
  1274. if !issue.IsClosed {
  1275. cmtType = COMMENT_TYPE_REOPEN
  1276. }
  1277. return createComment(e, doer, repo, issue, 0, 0, cmtType, "", nil)
  1278. }
  1279. // CreateComment creates comment of issue or commit.
  1280. func CreateComment(doer *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content string, attachments []string) (comment *Comment, err error) {
  1281. sess := x.NewSession()
  1282. defer sessionRelease(sess)
  1283. if err = sess.Begin(); err != nil {
  1284. return nil, err
  1285. }
  1286. comment, err = createComment(sess, doer, repo, issue, commitID, line, cmtType, content, attachments)
  1287. if err != nil {
  1288. return nil, err
  1289. }
  1290. return comment, sess.Commit()
  1291. }
  1292. // CreateIssueComment creates a plain issue comment.
  1293. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  1294. return CreateComment(doer, repo, issue, 0, 0, COMMENT_TYPE_COMMENT, content, attachments)
  1295. }
  1296. // GetCommentByID returns the comment by given ID.
  1297. func GetCommentByID(id int64) (*Comment, error) {
  1298. c := new(Comment)
  1299. has, err := x.Id(id).Get(c)
  1300. if err != nil {
  1301. return nil, err
  1302. } else if !has {
  1303. return nil, ErrCommentNotExist{id}
  1304. }
  1305. return c, nil
  1306. }
  1307. // GetCommentsByIssueID returns all comments of issue by given ID.
  1308. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  1309. comments := make([]*Comment, 0, 10)
  1310. return comments, x.Where("issue_id=?", issueID).Asc("created").Find(&comments)
  1311. }
  1312. // UpdateComment updates information of comment.
  1313. func UpdateComment(c *Comment) error {
  1314. _, err := x.Id(c.ID).AllCols().Update(c)
  1315. return err
  1316. }
  1317. // Attachment represent a attachment of issue/comment/release.
  1318. type Attachment struct {
  1319. ID int64 `xorm:"pk autoincr"`
  1320. UUID string `xorm:"uuid UNIQUE"`
  1321. IssueID int64 `xorm:"INDEX"`
  1322. CommentID int64
  1323. ReleaseID int64 `xorm:"INDEX"`
  1324. Name string
  1325. Created time.Time `xorm:"CREATED"`
  1326. }
  1327. // AttachmentLocalPath returns where attachment is stored in local file system based on given UUID.
  1328. func AttachmentLocalPath(uuid string) string {
  1329. return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid)
  1330. }
  1331. // LocalPath returns where attachment is stored in local file system.
  1332. func (attach *Attachment) LocalPath() string {
  1333. return AttachmentLocalPath(attach.UUID)
  1334. }
  1335. // NewAttachment creates a new attachment object.
  1336. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) {
  1337. attach := &Attachment{
  1338. UUID: gouuid.NewV4().String(),
  1339. Name: name,
  1340. }
  1341. if err = os.MkdirAll(path.Dir(attach.LocalPath()), os.ModePerm); err != nil {
  1342. return nil, fmt.Errorf("MkdirAll: %v", err)
  1343. }
  1344. fw, err := os.Create(attach.LocalPath())
  1345. if err != nil {
  1346. return nil, fmt.Errorf("Create: %v", err)
  1347. }
  1348. defer fw.Close()
  1349. if _, err = fw.Write(buf); err != nil {
  1350. return nil, fmt.Errorf("Write: %v", err)
  1351. } else if _, err = io.Copy(fw, file); err != nil {
  1352. return nil, fmt.Errorf("Copy: %v", err)
  1353. }
  1354. sess := x.NewSession()
  1355. defer sessionRelease(sess)
  1356. if err := sess.Begin(); err != nil {
  1357. return nil, err
  1358. }
  1359. if _, err := sess.Insert(attach); err != nil {
  1360. return nil, err
  1361. }
  1362. return attach, sess.Commit()
  1363. }
  1364. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  1365. attach := &Attachment{UUID: uuid}
  1366. has, err := x.Get(attach)
  1367. if err != nil {
  1368. return nil, err
  1369. } else if !has {
  1370. return nil, ErrAttachmentNotExist{0, uuid}
  1371. }
  1372. return attach, nil
  1373. }
  1374. // GetAttachmentByUUID returns attachment by given UUID.
  1375. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  1376. return getAttachmentByUUID(x, uuid)
  1377. }
  1378. // GetAttachmentsByIssueID returns all attachments for given issue by ID.
  1379. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  1380. attachments := make([]*Attachment, 0, 10)
  1381. return attachments, x.Where("issue_id=? AND comment_id=0", issueID).Find(&attachments)
  1382. }
  1383. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  1384. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  1385. attachments := make([]*Attachment, 0, 10)
  1386. return attachments, x.Where("comment_id=?", commentID).Find(&attachments)
  1387. }
  1388. // DeleteAttachment deletes the given attachment and optionally the associated file.
  1389. func DeleteAttachment(a *Attachment, remove bool) error {
  1390. _, err := DeleteAttachments([]*Attachment{a}, remove)
  1391. return err
  1392. }
  1393. // DeleteAttachments deletes the given attachments and optionally the associated files.
  1394. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  1395. for i, a := range attachments {
  1396. if remove {
  1397. if err := os.Remove(a.LocalPath()); err != nil {
  1398. return i, err
  1399. }
  1400. }
  1401. if _, err := x.Delete(a.ID); err != nil {
  1402. return i, err
  1403. }
  1404. }
  1405. return len(attachments), nil
  1406. }
  1407. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  1408. func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
  1409. attachments, err := GetAttachmentsByIssueID(issueId)
  1410. if err != nil {
  1411. return 0, err
  1412. }
  1413. return DeleteAttachments(attachments, remove)
  1414. }
  1415. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  1416. func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
  1417. attachments, err := GetAttachmentsByCommentID(commentId)
  1418. if err != nil {
  1419. return 0, err
  1420. }
  1421. return DeleteAttachments(attachments, remove)
  1422. }