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 43 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
11 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
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
11 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
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
10 years ago
10 years ago
10 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636
  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, isShowClosed bool, filterMode int) *IssueStats {
  553. stats := &IssueStats{}
  554. // issue := new(Issue)
  555. queryStr := "SELECT COUNT(*) FROM `issue` "
  556. if labelID > 0 {
  557. queryStr += "INNER JOIN `issue_label` ON `issue`.id=`issue_label`.issue_id AND `issue_label`.label_id=" + com.ToStr(labelID)
  558. }
  559. baseCond := " WHERE issue.repo_id=? AND issue.is_closed=?"
  560. if milestoneID > 0 {
  561. baseCond += " AND issue.milestone_id=" + com.ToStr(milestoneID)
  562. }
  563. if assigneeID > 0 {
  564. baseCond += " AND assignee_id=" + com.ToStr(assigneeID)
  565. }
  566. switch filterMode {
  567. case FM_ALL, FM_ASSIGN:
  568. resutls, _ := x.Query(queryStr+baseCond, repoID, false)
  569. stats.OpenCount = parseCountResult(resutls)
  570. resutls, _ = x.Query(queryStr+baseCond, repoID, true)
  571. stats.ClosedCount = parseCountResult(resutls)
  572. case FM_CREATE:
  573. baseCond += " AND poster_id=?"
  574. resutls, _ := x.Query(queryStr+baseCond, repoID, false, uid)
  575. stats.OpenCount = parseCountResult(resutls)
  576. resutls, _ = x.Query(queryStr+baseCond, repoID, true, uid)
  577. stats.ClosedCount = parseCountResult(resutls)
  578. case FM_MENTION:
  579. queryStr += " INNER JOIN `issue_user` ON `issue`.id=`issue_user`.issue_id"
  580. baseCond += " AND `issue_user`.uid=? AND `issue_user`.is_mentioned=?"
  581. resutls, _ := x.Query(queryStr+baseCond, repoID, false, uid, true)
  582. stats.OpenCount = parseCountResult(resutls)
  583. resutls, _ = x.Query(queryStr+baseCond, repoID, true, uid, true)
  584. stats.ClosedCount = parseCountResult(resutls)
  585. }
  586. return stats
  587. }
  588. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  589. func GetUserIssueStats(uid int64, filterMode int) *IssueStats {
  590. stats := &IssueStats{}
  591. issue := new(Issue)
  592. stats.AssignCount, _ = x.Where("assignee_id=?", uid).And("is_closed=?", false).Count(issue)
  593. stats.CreateCount, _ = x.Where("poster_id=?", uid).And("is_closed=?", false).Count(issue)
  594. return stats
  595. }
  596. func updateIssue(e Engine, issue *Issue) error {
  597. _, err := e.Id(issue.ID).AllCols().Update(issue)
  598. return err
  599. }
  600. // UpdateIssue updates information of issue.
  601. func UpdateIssue(issue *Issue) error {
  602. return updateIssue(x, issue)
  603. }
  604. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  605. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  606. return err
  607. }
  608. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  609. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  610. return updateIssueUsersByStatus(x, issueID, isClosed)
  611. }
  612. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  613. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE issue_id=?", false, issue.ID); err != nil {
  614. return err
  615. }
  616. // Assignee ID equals to 0 means clear assignee.
  617. if issue.AssigneeID > 0 {
  618. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE uid=? AND issue_id=?", true, issue.AssigneeID, issue.ID); err != nil {
  619. return err
  620. }
  621. }
  622. return updateIssue(e, issue)
  623. }
  624. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  625. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  626. sess := x.NewSession()
  627. defer sessionRelease(sess)
  628. if err = sess.Begin(); err != nil {
  629. return err
  630. }
  631. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  632. return err
  633. }
  634. return sess.Commit()
  635. }
  636. // UpdateIssueUserByRead updates issue-user relation for reading.
  637. func UpdateIssueUserByRead(uid, issueID int64) error {
  638. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  639. return err
  640. }
  641. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
  642. func UpdateIssueUsersByMentions(uids []int64, iid int64) error {
  643. for _, uid := range uids {
  644. iu := &IssueUser{UID: uid, IssueID: iid}
  645. has, err := x.Get(iu)
  646. if err != nil {
  647. return err
  648. }
  649. iu.IsMentioned = true
  650. if has {
  651. _, err = x.Id(iu.ID).AllCols().Update(iu)
  652. } else {
  653. _, err = x.Insert(iu)
  654. }
  655. if err != nil {
  656. return err
  657. }
  658. }
  659. return nil
  660. }
  661. // .____ ___. .__
  662. // | | _____ \_ |__ ____ | |
  663. // | | \__ \ | __ \_/ __ \| |
  664. // | |___ / __ \| \_\ \ ___/| |__
  665. // |_______ (____ /___ /\___ >____/
  666. // \/ \/ \/ \/
  667. // Label represents a label of repository for issues.
  668. type Label struct {
  669. ID int64 `xorm:"pk autoincr"`
  670. RepoID int64 `xorm:"INDEX"`
  671. Name string
  672. Color string `xorm:"VARCHAR(7)"`
  673. NumIssues int
  674. NumClosedIssues int
  675. NumOpenIssues int `xorm:"-"`
  676. IsChecked bool `xorm:"-"`
  677. }
  678. // CalOpenIssues calculates the open issues of label.
  679. func (m *Label) CalOpenIssues() {
  680. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  681. }
  682. // NewLabel creates new label of repository.
  683. func NewLabel(l *Label) error {
  684. _, err := x.Insert(l)
  685. return err
  686. }
  687. func getLabelByID(e Engine, id int64) (*Label, error) {
  688. if id <= 0 {
  689. return nil, ErrLabelNotExist{id}
  690. }
  691. l := &Label{ID: id}
  692. has, err := x.Get(l)
  693. if err != nil {
  694. return nil, err
  695. } else if !has {
  696. return nil, ErrLabelNotExist{l.ID}
  697. }
  698. return l, nil
  699. }
  700. // GetLabelByID returns a label by given ID.
  701. func GetLabelByID(id int64) (*Label, error) {
  702. return getLabelByID(x, id)
  703. }
  704. // GetLabelsByRepoID returns all labels that belong to given repository by ID.
  705. func GetLabelsByRepoID(repoID int64) ([]*Label, error) {
  706. labels := make([]*Label, 0, 10)
  707. return labels, x.Where("repo_id=?", repoID).Find(&labels)
  708. }
  709. func getLabelsByIssueID(e Engine, issueID int64) ([]*Label, error) {
  710. issueLabels, err := getIssueLabels(e, issueID)
  711. if err != nil {
  712. return nil, fmt.Errorf("getIssueLabels: %v", err)
  713. }
  714. var label *Label
  715. labels := make([]*Label, 0, len(issueLabels))
  716. for idx := range issueLabels {
  717. label, err = getLabelByID(e, issueLabels[idx].LabelID)
  718. if err != nil && !IsErrLabelNotExist(err) {
  719. return nil, fmt.Errorf("getLabelByID: %v", err)
  720. }
  721. labels = append(labels, label)
  722. }
  723. return labels, nil
  724. }
  725. // GetLabelsByIssueID returns all labels that belong to given issue by ID.
  726. func GetLabelsByIssueID(issueID int64) ([]*Label, error) {
  727. return getLabelsByIssueID(x, issueID)
  728. }
  729. func updateLabel(e Engine, l *Label) error {
  730. _, err := e.Id(l.ID).AllCols().Update(l)
  731. return err
  732. }
  733. // UpdateLabel updates label information.
  734. func UpdateLabel(l *Label) error {
  735. return updateLabel(x, l)
  736. }
  737. // DeleteLabel delete a label of given repository.
  738. func DeleteLabel(repoID, labelID int64) error {
  739. l, err := GetLabelByID(labelID)
  740. if err != nil {
  741. if IsErrLabelNotExist(err) {
  742. return nil
  743. }
  744. return err
  745. }
  746. sess := x.NewSession()
  747. defer sessionRelease(sess)
  748. if err = sess.Begin(); err != nil {
  749. return err
  750. }
  751. if _, err = x.Where("label_id=?", labelID).Delete(new(IssueLabel)); err != nil {
  752. return err
  753. } else if _, err = sess.Delete(l); err != nil {
  754. return err
  755. }
  756. return sess.Commit()
  757. }
  758. // .___ .____ ___. .__
  759. // | | ______ ________ __ ____ | | _____ \_ |__ ____ | |
  760. // | |/ ___// ___/ | \_/ __ \| | \__ \ | __ \_/ __ \| |
  761. // | |\___ \ \___ \| | /\ ___/| |___ / __ \| \_\ \ ___/| |__
  762. // |___/____ >____ >____/ \___ >_______ (____ /___ /\___ >____/
  763. // \/ \/ \/ \/ \/ \/ \/
  764. // IssueLabel represetns an issue-lable relation.
  765. type IssueLabel struct {
  766. ID int64 `xorm:"pk autoincr"`
  767. IssueID int64 `xorm:"UNIQUE(s)"`
  768. LabelID int64 `xorm:"UNIQUE(s)"`
  769. }
  770. func hasIssueLabel(e Engine, issueID, labelID int64) bool {
  771. has, _ := e.Where("issue_id=? AND label_id=?", issueID, labelID).Get(new(IssueLabel))
  772. return has
  773. }
  774. // HasIssueLabel returns true if issue has been labeled.
  775. func HasIssueLabel(issueID, labelID int64) bool {
  776. return hasIssueLabel(x, issueID, labelID)
  777. }
  778. func newIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  779. if _, err = e.Insert(&IssueLabel{
  780. IssueID: issue.ID,
  781. LabelID: label.ID,
  782. }); err != nil {
  783. return err
  784. }
  785. label.NumIssues++
  786. if issue.IsClosed {
  787. label.NumClosedIssues++
  788. }
  789. return updateLabel(e, label)
  790. }
  791. // NewIssueLabel creates a new issue-label relation.
  792. func NewIssueLabel(issue *Issue, label *Label) (err error) {
  793. sess := x.NewSession()
  794. defer sessionRelease(sess)
  795. if err = sess.Begin(); err != nil {
  796. return err
  797. }
  798. if err = newIssueLabel(sess, issue, label); err != nil {
  799. return err
  800. }
  801. return sess.Commit()
  802. }
  803. func getIssueLabels(e Engine, issueID int64) ([]*IssueLabel, error) {
  804. issueLabels := make([]*IssueLabel, 0, 10)
  805. return issueLabels, e.Where("issue_id=?", issueID).Asc("label_id").Find(&issueLabels)
  806. }
  807. // GetIssueLabels returns all issue-label relations of given issue by ID.
  808. func GetIssueLabels(issueID int64) ([]*IssueLabel, error) {
  809. return getIssueLabels(x, issueID)
  810. }
  811. func deleteIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  812. if _, err = e.Delete(&IssueLabel{
  813. IssueID: issue.ID,
  814. LabelID: label.ID,
  815. }); err != nil {
  816. return err
  817. }
  818. label.NumIssues--
  819. if issue.IsClosed {
  820. label.NumClosedIssues--
  821. }
  822. return updateLabel(e, label)
  823. }
  824. // DeleteIssueLabel deletes issue-label relation.
  825. func DeleteIssueLabel(issue *Issue, label *Label) (err error) {
  826. sess := x.NewSession()
  827. defer sessionRelease(sess)
  828. if err = sess.Begin(); err != nil {
  829. return err
  830. }
  831. if err = deleteIssueLabel(sess, issue, label); err != nil {
  832. return err
  833. }
  834. return sess.Commit()
  835. }
  836. // _____ .__.__ __
  837. // / \ |__| | ____ _______/ |_ ____ ____ ____
  838. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  839. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  840. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  841. // \/ \/ \/ \/ \/
  842. // Milestone represents a milestone of repository.
  843. type Milestone struct {
  844. ID int64 `xorm:"pk autoincr"`
  845. RepoID int64 `xorm:"INDEX"`
  846. Name string
  847. Content string `xorm:"TEXT"`
  848. RenderedContent string `xorm:"-"`
  849. IsClosed bool
  850. NumIssues int
  851. NumClosedIssues int
  852. NumOpenIssues int `xorm:"-"`
  853. Completeness int // Percentage(1-100).
  854. Deadline time.Time
  855. DeadlineString string `xorm:"-"`
  856. IsOverDue bool `xorm:"-"`
  857. ClosedDate time.Time
  858. }
  859. func (m *Milestone) BeforeUpdate() {
  860. if m.NumIssues > 0 {
  861. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  862. } else {
  863. m.Completeness = 0
  864. }
  865. }
  866. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  867. if colName == "deadline" {
  868. if m.Deadline.Year() == 9999 {
  869. return
  870. }
  871. m.DeadlineString = m.Deadline.Format("2006-01-02")
  872. if time.Now().After(m.Deadline) {
  873. m.IsOverDue = true
  874. }
  875. }
  876. }
  877. // CalOpenIssues calculates the open issues of milestone.
  878. func (m *Milestone) CalOpenIssues() {
  879. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  880. }
  881. // NewMilestone creates new milestone of repository.
  882. func NewMilestone(m *Milestone) (err error) {
  883. sess := x.NewSession()
  884. defer sessionRelease(sess)
  885. if err = sess.Begin(); err != nil {
  886. return err
  887. }
  888. if _, err = sess.Insert(m); err != nil {
  889. return err
  890. }
  891. if _, err = sess.Exec("UPDATE `repository` SET num_milestones=num_milestones+1 WHERE id=?", m.RepoID); err != nil {
  892. return err
  893. }
  894. return sess.Commit()
  895. }
  896. func getMilestoneByID(e Engine, id int64) (*Milestone, error) {
  897. m := &Milestone{ID: id}
  898. has, err := e.Get(m)
  899. if err != nil {
  900. return nil, err
  901. } else if !has {
  902. return nil, ErrMilestoneNotExist{id, 0}
  903. }
  904. return m, nil
  905. }
  906. // GetMilestoneByID returns the milestone of given ID.
  907. func GetMilestoneByID(id int64) (*Milestone, error) {
  908. return getMilestoneByID(x, id)
  909. }
  910. // GetRepoMilestoneByID returns the milestone of given ID and repository.
  911. func GetRepoMilestoneByID(repoID, milestoneID int64) (*Milestone, error) {
  912. m := &Milestone{ID: milestoneID, RepoID: repoID}
  913. has, err := x.Get(m)
  914. if err != nil {
  915. return nil, err
  916. } else if !has {
  917. return nil, ErrMilestoneNotExist{milestoneID, repoID}
  918. }
  919. return m, nil
  920. }
  921. // GetAllRepoMilestones returns all milestones of given repository.
  922. func GetAllRepoMilestones(repoID int64) ([]*Milestone, error) {
  923. miles := make([]*Milestone, 0, 10)
  924. return miles, x.Where("repo_id=?", repoID).Find(&miles)
  925. }
  926. // GetMilestones returns a list of milestones of given repository and status.
  927. func GetMilestones(repoID int64, page int, isClosed bool) ([]*Milestone, error) {
  928. miles := make([]*Milestone, 0, setting.IssuePagingNum)
  929. sess := x.Where("repo_id=? AND is_closed=?", repoID, isClosed)
  930. if page > 0 {
  931. sess = sess.Limit(setting.IssuePagingNum, (page-1)*setting.IssuePagingNum)
  932. }
  933. return miles, sess.Find(&miles)
  934. }
  935. func updateMilestone(e Engine, m *Milestone) error {
  936. _, err := e.Id(m.ID).AllCols().Update(m)
  937. return err
  938. }
  939. // UpdateMilestone updates information of given milestone.
  940. func UpdateMilestone(m *Milestone) error {
  941. return updateMilestone(x, m)
  942. }
  943. func countRepoMilestones(e Engine, repoID int64) int64 {
  944. count, _ := e.Where("repo_id=?", repoID).Count(new(Milestone))
  945. return count
  946. }
  947. // CountRepoMilestones returns number of milestones in given repository.
  948. func CountRepoMilestones(repoID int64) int64 {
  949. return countRepoMilestones(x, repoID)
  950. }
  951. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  952. closed, _ := e.Where("repo_id=? AND is_closed=?", repoID, true).Count(new(Milestone))
  953. return closed
  954. }
  955. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  956. func CountRepoClosedMilestones(repoID int64) int64 {
  957. return countRepoClosedMilestones(x, repoID)
  958. }
  959. // MilestoneStats returns number of open and closed milestones of given repository.
  960. func MilestoneStats(repoID int64) (open int64, closed int64) {
  961. open, _ = x.Where("repo_id=? AND is_closed=?", repoID, false).Count(new(Milestone))
  962. return open, CountRepoClosedMilestones(repoID)
  963. }
  964. // ChangeMilestoneStatus changes the milestone open/closed status.
  965. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  966. repo, err := GetRepositoryByID(m.RepoID)
  967. if err != nil {
  968. return err
  969. }
  970. sess := x.NewSession()
  971. defer sessionRelease(sess)
  972. if err = sess.Begin(); err != nil {
  973. return err
  974. }
  975. m.IsClosed = isClosed
  976. if err = updateMilestone(sess, m); err != nil {
  977. return err
  978. }
  979. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  980. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  981. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  982. return err
  983. }
  984. return sess.Commit()
  985. }
  986. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  987. if issue.MilestoneID == 0 {
  988. return nil
  989. }
  990. m, err := getMilestoneByID(e, issue.MilestoneID)
  991. if err != nil {
  992. return err
  993. }
  994. if issue.IsClosed {
  995. m.NumOpenIssues--
  996. m.NumClosedIssues++
  997. } else {
  998. m.NumOpenIssues++
  999. m.NumClosedIssues--
  1000. }
  1001. return updateMilestone(e, m)
  1002. }
  1003. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  1004. // for the milestone associated witht the given issue.
  1005. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  1006. sess := x.NewSession()
  1007. defer sessionRelease(sess)
  1008. if err = sess.Begin(); err != nil {
  1009. return err
  1010. }
  1011. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  1012. return err
  1013. }
  1014. return sess.Commit()
  1015. }
  1016. func changeMilestoneAssign(e *xorm.Session, oldMid int64, issue *Issue) error {
  1017. if oldMid > 0 {
  1018. m, err := getMilestoneByID(e, oldMid)
  1019. if err != nil {
  1020. return err
  1021. }
  1022. m.NumIssues--
  1023. if issue.IsClosed {
  1024. m.NumClosedIssues--
  1025. }
  1026. if err = updateMilestone(e, m); err != nil {
  1027. return err
  1028. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE issue_id=?", issue.ID); err != nil {
  1029. return err
  1030. }
  1031. }
  1032. if issue.MilestoneID > 0 {
  1033. m, err := getMilestoneByID(e, issue.MilestoneID)
  1034. if err != nil {
  1035. return err
  1036. }
  1037. m.NumIssues++
  1038. if issue.IsClosed {
  1039. m.NumClosedIssues++
  1040. }
  1041. if m.NumIssues == 0 {
  1042. return ErrWrongIssueCounter
  1043. }
  1044. if err = updateMilestone(e, m); err != nil {
  1045. return err
  1046. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=? WHERE issue_id=?", m.ID, issue.ID); err != nil {
  1047. return err
  1048. }
  1049. }
  1050. return updateIssue(e, issue)
  1051. }
  1052. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1053. func ChangeMilestoneAssign(oldMid int64, issue *Issue) (err error) {
  1054. sess := x.NewSession()
  1055. defer sess.Close()
  1056. if err = sess.Begin(); err != nil {
  1057. return err
  1058. }
  1059. if err = changeMilestoneAssign(sess, oldMid, issue); err != nil {
  1060. return err
  1061. }
  1062. return sess.Commit()
  1063. }
  1064. // DeleteMilestoneByID deletes a milestone by given ID.
  1065. func DeleteMilestoneByID(mid int64) error {
  1066. m, err := GetMilestoneByID(mid)
  1067. if err != nil {
  1068. if IsErrMilestoneNotExist(err) {
  1069. return nil
  1070. }
  1071. return err
  1072. }
  1073. repo, err := GetRepositoryByID(m.RepoID)
  1074. if err != nil {
  1075. return err
  1076. }
  1077. sess := x.NewSession()
  1078. defer sessionRelease(sess)
  1079. if err = sess.Begin(); err != nil {
  1080. return err
  1081. }
  1082. if _, err = sess.Id(m.ID).Delete(m); err != nil {
  1083. return err
  1084. }
  1085. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1086. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1087. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1088. return err
  1089. }
  1090. if _, err = sess.Exec("UPDATE `issue` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1091. return err
  1092. } else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1093. return err
  1094. }
  1095. return sess.Commit()
  1096. }
  1097. // _________ __
  1098. // \_ ___ \ ____ _____ _____ ____ _____/ |_
  1099. // / \ \/ / _ \ / \ / \_/ __ \ / \ __\
  1100. // \ \___( <_> ) Y Y \ Y Y \ ___/| | \ |
  1101. // \______ /\____/|__|_| /__|_| /\___ >___| /__|
  1102. // \/ \/ \/ \/ \/
  1103. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  1104. type CommentType int
  1105. const (
  1106. // Plain comment, can be associated with a commit (CommitId > 0) and a line (Line > 0)
  1107. COMMENT_TYPE_COMMENT CommentType = iota
  1108. COMMENT_TYPE_REOPEN
  1109. COMMENT_TYPE_CLOSE
  1110. // References.
  1111. COMMENT_TYPE_ISSUE_REF
  1112. // Reference from a commit (not part of a pull request)
  1113. COMMENT_TYPE_COMMIT_REF
  1114. // Reference from a comment
  1115. COMMENT_TYPE_COMMENT_REF
  1116. // Reference from a pull request
  1117. COMMENT_TYPE_PULL_REF
  1118. )
  1119. type CommentTag int
  1120. const (
  1121. COMMENT_TAG_NONE CommentTag = iota
  1122. COMMENT_TAG_POSTER
  1123. COMMENT_TAG_ADMIN
  1124. COMMENT_TAG_OWNER
  1125. )
  1126. // Comment represents a comment in commit and issue page.
  1127. type Comment struct {
  1128. ID int64 `xorm:"pk autoincr"`
  1129. Type CommentType
  1130. PosterID int64
  1131. Poster *User `xorm:"-"`
  1132. IssueID int64 `xorm:"INDEX"`
  1133. CommitID int64
  1134. Line int64
  1135. Content string `xorm:"TEXT"`
  1136. RenderedContent string `xorm:"-"`
  1137. Created time.Time `xorm:"CREATED"`
  1138. Attachments []*Attachment `xorm:"-"`
  1139. // For view issue page.
  1140. ShowTag CommentTag `xorm:"-"`
  1141. }
  1142. func (c *Comment) AfterSet(colName string, _ xorm.Cell) {
  1143. var err error
  1144. switch colName {
  1145. case "id":
  1146. c.Attachments, err = GetAttachmentsByCommentID(c.ID)
  1147. if err != nil {
  1148. log.Error(3, "GetAttachmentsByCommentID[%d]: %v", c.ID, err)
  1149. }
  1150. case "poster_id":
  1151. c.Poster, err = GetUserByID(c.PosterID)
  1152. if err != nil {
  1153. if IsErrUserNotExist(err) {
  1154. c.PosterID = -1
  1155. c.Poster = NewFakeUser()
  1156. } else {
  1157. log.Error(3, "GetUserByID[%d]: %v", c.ID, err)
  1158. }
  1159. }
  1160. case "created":
  1161. c.Created = regulateTimeZone(c.Created)
  1162. }
  1163. }
  1164. func (c *Comment) AfterDelete() {
  1165. _, err := DeleteAttachmentsByComment(c.ID, true)
  1166. if err != nil {
  1167. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  1168. }
  1169. }
  1170. // HashTag returns unique hash tag for comment.
  1171. func (c *Comment) HashTag() string {
  1172. return "issuecomment-" + com.ToStr(c.ID)
  1173. }
  1174. // EventTag returns unique event hash tag for comment.
  1175. func (c *Comment) EventTag() string {
  1176. return "event-" + com.ToStr(c.ID)
  1177. }
  1178. func createComment(e *xorm.Session, u *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content string, uuids []string) (_ *Comment, err error) {
  1179. comment := &Comment{
  1180. PosterID: u.Id,
  1181. Type: cmtType,
  1182. IssueID: issue.ID,
  1183. CommitID: commitID,
  1184. Line: line,
  1185. Content: content,
  1186. }
  1187. if _, err = e.Insert(comment); err != nil {
  1188. return nil, err
  1189. }
  1190. // Check comment type.
  1191. switch cmtType {
  1192. case COMMENT_TYPE_COMMENT:
  1193. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", issue.ID); err != nil {
  1194. return nil, err
  1195. }
  1196. // Check attachments.
  1197. attachments := make([]*Attachment, 0, len(uuids))
  1198. for _, uuid := range uuids {
  1199. attach, err := getAttachmentByUUID(e, uuid)
  1200. if err != nil {
  1201. if IsErrAttachmentNotExist(err) {
  1202. continue
  1203. }
  1204. return nil, fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  1205. }
  1206. attachments = append(attachments, attach)
  1207. }
  1208. for i := range attachments {
  1209. attachments[i].IssueID = issue.ID
  1210. attachments[i].CommentID = comment.ID
  1211. // No assign value could be 0, so ignore AllCols().
  1212. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  1213. return nil, fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  1214. }
  1215. }
  1216. // Notify watchers.
  1217. act := &Action{
  1218. ActUserID: u.Id,
  1219. ActUserName: u.LowerName,
  1220. ActEmail: u.Email,
  1221. OpType: COMMENT_ISSUE,
  1222. Content: fmt.Sprintf("%d|%s", issue.Index, strings.Split(content, "\n")[0]),
  1223. RepoID: repo.ID,
  1224. RepoUserName: repo.Owner.LowerName,
  1225. RepoName: repo.LowerName,
  1226. IsPrivate: repo.IsPrivate,
  1227. }
  1228. if err = notifyWatchers(e, act); err != nil {
  1229. return nil, err
  1230. }
  1231. case COMMENT_TYPE_REOPEN:
  1232. if _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", repo.ID); err != nil {
  1233. return nil, err
  1234. }
  1235. case COMMENT_TYPE_CLOSE:
  1236. if _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", repo.ID); err != nil {
  1237. return nil, err
  1238. }
  1239. }
  1240. return comment, nil
  1241. }
  1242. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  1243. cmtType := COMMENT_TYPE_CLOSE
  1244. if !issue.IsClosed {
  1245. cmtType = COMMENT_TYPE_REOPEN
  1246. }
  1247. return createComment(e, doer, repo, issue, 0, 0, cmtType, "", nil)
  1248. }
  1249. // CreateComment creates comment of issue or commit.
  1250. func CreateComment(doer *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content string, attachments []string) (comment *Comment, err error) {
  1251. sess := x.NewSession()
  1252. defer sessionRelease(sess)
  1253. if err = sess.Begin(); err != nil {
  1254. return nil, err
  1255. }
  1256. comment, err = createComment(sess, doer, repo, issue, commitID, line, cmtType, content, attachments)
  1257. if err != nil {
  1258. return nil, err
  1259. }
  1260. return comment, sess.Commit()
  1261. }
  1262. // CreateIssueComment creates a plain issue comment.
  1263. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  1264. return CreateComment(doer, repo, issue, 0, 0, COMMENT_TYPE_COMMENT, content, attachments)
  1265. }
  1266. // GetCommentByID returns the comment by given ID.
  1267. func GetCommentByID(id int64) (*Comment, error) {
  1268. c := new(Comment)
  1269. has, err := x.Id(id).Get(c)
  1270. if err != nil {
  1271. return nil, err
  1272. } else if !has {
  1273. return nil, ErrCommentNotExist{id}
  1274. }
  1275. return c, nil
  1276. }
  1277. // GetCommentsByIssueID returns all comments of issue by given ID.
  1278. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  1279. comments := make([]*Comment, 0, 10)
  1280. return comments, x.Where("issue_id=?", issueID).Asc("created").Find(&comments)
  1281. }
  1282. // UpdateComment updates information of comment.
  1283. func UpdateComment(c *Comment) error {
  1284. _, err := x.Id(c.ID).AllCols().Update(c)
  1285. return err
  1286. }
  1287. // Attachment represent a attachment of issue/comment/release.
  1288. type Attachment struct {
  1289. ID int64 `xorm:"pk autoincr"`
  1290. UUID string `xorm:"uuid UNIQUE"`
  1291. IssueID int64 `xorm:"INDEX"`
  1292. CommentID int64
  1293. ReleaseID int64 `xorm:"INDEX"`
  1294. Name string
  1295. Created time.Time `xorm:"CREATED"`
  1296. }
  1297. // AttachmentLocalPath returns where attachment is stored in local file system based on given UUID.
  1298. func AttachmentLocalPath(uuid string) string {
  1299. return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid)
  1300. }
  1301. // LocalPath returns where attachment is stored in local file system.
  1302. func (attach *Attachment) LocalPath() string {
  1303. return AttachmentLocalPath(attach.UUID)
  1304. }
  1305. // NewAttachment creates a new attachment object.
  1306. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) {
  1307. attach := &Attachment{
  1308. UUID: gouuid.NewV4().String(),
  1309. Name: name,
  1310. }
  1311. if err = os.MkdirAll(path.Dir(attach.LocalPath()), os.ModePerm); err != nil {
  1312. return nil, fmt.Errorf("MkdirAll: %v", err)
  1313. }
  1314. fw, err := os.Create(attach.LocalPath())
  1315. if err != nil {
  1316. return nil, fmt.Errorf("Create: %v", err)
  1317. }
  1318. defer fw.Close()
  1319. if _, err = fw.Write(buf); err != nil {
  1320. return nil, fmt.Errorf("Write: %v", err)
  1321. } else if _, err = io.Copy(fw, file); err != nil {
  1322. return nil, fmt.Errorf("Copy: %v", err)
  1323. }
  1324. sess := x.NewSession()
  1325. defer sessionRelease(sess)
  1326. if err := sess.Begin(); err != nil {
  1327. return nil, err
  1328. }
  1329. if _, err := sess.Insert(attach); err != nil {
  1330. return nil, err
  1331. }
  1332. return attach, sess.Commit()
  1333. }
  1334. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  1335. attach := &Attachment{UUID: uuid}
  1336. has, err := x.Get(attach)
  1337. if err != nil {
  1338. return nil, err
  1339. } else if !has {
  1340. return nil, ErrAttachmentNotExist{0, uuid}
  1341. }
  1342. return attach, nil
  1343. }
  1344. // GetAttachmentByUUID returns attachment by given UUID.
  1345. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  1346. return getAttachmentByUUID(x, uuid)
  1347. }
  1348. // GetAttachmentsByIssueID returns all attachments for given issue by ID.
  1349. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  1350. attachments := make([]*Attachment, 0, 10)
  1351. return attachments, x.Where("issue_id=? AND comment_id=0", issueID).Find(&attachments)
  1352. }
  1353. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  1354. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  1355. attachments := make([]*Attachment, 0, 10)
  1356. return attachments, x.Where("comment_id=?", commentID).Find(&attachments)
  1357. }
  1358. // DeleteAttachment deletes the given attachment and optionally the associated file.
  1359. func DeleteAttachment(a *Attachment, remove bool) error {
  1360. _, err := DeleteAttachments([]*Attachment{a}, remove)
  1361. return err
  1362. }
  1363. // DeleteAttachments deletes the given attachments and optionally the associated files.
  1364. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  1365. for i, a := range attachments {
  1366. if remove {
  1367. if err := os.Remove(a.LocalPath()); err != nil {
  1368. return i, err
  1369. }
  1370. }
  1371. if _, err := x.Delete(a.ID); err != nil {
  1372. return i, err
  1373. }
  1374. }
  1375. return len(attachments), nil
  1376. }
  1377. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  1378. func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
  1379. attachments, err := GetAttachmentsByIssueID(issueId)
  1380. if err != nil {
  1381. return 0, err
  1382. }
  1383. return DeleteAttachments(attachments, remove)
  1384. }
  1385. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  1386. func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
  1387. attachments, err := GetAttachmentsByCommentID(commentId)
  1388. if err != nil {
  1389. return 0, err
  1390. }
  1391. return DeleteAttachments(attachments, remove)
  1392. }