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
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
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
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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  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. // HashTag returns unique hash tag for issue.
  56. func (i *Issue) HashTag() string {
  57. return "issue-" + com.ToStr(i.ID)
  58. }
  59. func (i *Issue) AfterSet(colName string, _ xorm.Cell) {
  60. var err error
  61. switch colName {
  62. case "id":
  63. i.Attachments, err = GetAttachmentsByIssueID(i.ID)
  64. if err != nil {
  65. log.Error(3, "GetAttachmentsByIssueID[%d]: %v", i.ID, err)
  66. }
  67. i.Comments, err = GetCommentsByIssueID(i.ID)
  68. if err != nil {
  69. log.Error(3, "GetCommentsByIssueID[%d]: %v", i.ID, err)
  70. }
  71. case "milestone_id":
  72. if i.MilestoneID == 0 {
  73. return
  74. }
  75. i.Milestone, err = GetMilestoneByID(i.MilestoneID)
  76. if err != nil {
  77. log.Error(3, "GetMilestoneById[%d]: %v", i.ID, err)
  78. }
  79. case "assignee_id":
  80. if i.AssigneeID == 0 {
  81. return
  82. }
  83. i.Assignee, err = GetUserByID(i.AssigneeID)
  84. if err != nil {
  85. log.Error(3, "GetUserByID[%d]: %v", i.ID, err)
  86. }
  87. }
  88. }
  89. // IsPoster returns true if given user by ID is the poster.
  90. func (i *Issue) IsPoster(uid int64) bool {
  91. return i.PosterID == uid
  92. }
  93. func (i *Issue) GetPoster() (err error) {
  94. i.Poster, err = GetUserByID(i.PosterID)
  95. if IsErrUserNotExist(err) {
  96. i.Poster = &User{Name: "Someone"}
  97. return nil
  98. }
  99. return err
  100. }
  101. func (i *Issue) hasLabel(e Engine, labelID int64) bool {
  102. return hasIssueLabel(e, i.ID, labelID)
  103. }
  104. // HasLabel returns true if issue has been labeled by given ID.
  105. func (i *Issue) HasLabel(labelID int64) bool {
  106. return i.hasLabel(x, labelID)
  107. }
  108. func (i *Issue) addLabel(e *xorm.Session, label *Label) error {
  109. return newIssueLabel(e, i, label)
  110. }
  111. // AddLabel adds new label to issue by given ID.
  112. func (i *Issue) AddLabel(label *Label) (err error) {
  113. sess := x.NewSession()
  114. defer sessionRelease(sess)
  115. if err = sess.Begin(); err != nil {
  116. return err
  117. }
  118. if err = i.addLabel(sess, label); err != nil {
  119. return err
  120. }
  121. return sess.Commit()
  122. }
  123. func (i *Issue) getLabels(e Engine) (err error) {
  124. if len(i.Labels) > 0 {
  125. return nil
  126. }
  127. i.Labels, err = getLabelsByIssueID(e, i.ID)
  128. if err != nil {
  129. return fmt.Errorf("getLabelsByIssueID: %v", err)
  130. }
  131. return nil
  132. }
  133. // GetLabels retrieves all labels of issue and assign to corresponding field.
  134. func (i *Issue) GetLabels() error {
  135. return i.getLabels(x)
  136. }
  137. func (i *Issue) removeLabel(e *xorm.Session, label *Label) error {
  138. return deleteIssueLabel(e, i, label)
  139. }
  140. // RemoveLabel removes a label from issue by given ID.
  141. func (i *Issue) RemoveLabel(label *Label) (err error) {
  142. sess := x.NewSession()
  143. defer sessionRelease(sess)
  144. if err = sess.Begin(); err != nil {
  145. return err
  146. }
  147. if err = i.removeLabel(sess, label); err != nil {
  148. return err
  149. }
  150. return sess.Commit()
  151. }
  152. func (i *Issue) ClearLabels() (err error) {
  153. sess := x.NewSession()
  154. defer sessionRelease(sess)
  155. if err = sess.Begin(); err != nil {
  156. return err
  157. }
  158. if err = i.getLabels(sess); err != nil {
  159. return err
  160. }
  161. for idx := range i.Labels {
  162. if err = i.removeLabel(sess, i.Labels[idx]); err != nil {
  163. return err
  164. }
  165. }
  166. return sess.Commit()
  167. }
  168. func (i *Issue) GetAssignee() (err error) {
  169. if i.AssigneeID == 0 || i.Assignee != nil {
  170. return nil
  171. }
  172. i.Assignee, err = GetUserByID(i.AssigneeID)
  173. if IsErrUserNotExist(err) {
  174. return nil
  175. }
  176. return err
  177. }
  178. // ReadBy sets issue to be read by given user.
  179. func (i *Issue) ReadBy(uid int64) error {
  180. return UpdateIssueUserByRead(uid, i.ID)
  181. }
  182. func (i *Issue) changeStatus(e *xorm.Session, doer *User, isClosed bool) (err error) {
  183. if i.IsClosed == isClosed {
  184. return nil
  185. }
  186. i.IsClosed = isClosed
  187. if err = updateIssue(e, i); err != nil {
  188. return err
  189. } else if err = updateIssueUsersByStatus(e, i.ID, isClosed); err != nil {
  190. return err
  191. }
  192. // Update labels.
  193. if err = i.getLabels(e); err != nil {
  194. return err
  195. }
  196. for idx := range i.Labels {
  197. if i.IsClosed {
  198. i.Labels[idx].NumClosedIssues++
  199. } else {
  200. i.Labels[idx].NumClosedIssues--
  201. }
  202. if err = updateLabel(e, i.Labels[idx]); err != nil {
  203. return err
  204. }
  205. }
  206. // Update milestone.
  207. if err = changeMilestoneIssueStats(e, i); err != nil {
  208. return err
  209. }
  210. // New action comment.
  211. if _, err = createStatusComment(e, doer, i.Repo, i); err != nil {
  212. return err
  213. }
  214. return nil
  215. }
  216. // ChangeStatus changes issue status to open/closed.
  217. func (i *Issue) ChangeStatus(doer *User, isClosed bool) (err error) {
  218. sess := x.NewSession()
  219. defer sessionRelease(sess)
  220. if err = sess.Begin(); err != nil {
  221. return err
  222. }
  223. if err = i.changeStatus(sess, doer, isClosed); err != nil {
  224. return err
  225. }
  226. return sess.Commit()
  227. }
  228. // CreateIssue creates new issue with labels for repository.
  229. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  230. // Check attachments.
  231. attachments := make([]*Attachment, 0, len(uuids))
  232. for _, uuid := range uuids {
  233. attach, err := GetAttachmentByUUID(uuid)
  234. if err != nil {
  235. if IsErrAttachmentNotExist(err) {
  236. continue
  237. }
  238. return fmt.Errorf("GetAttachmentByUUID[%s]: %v", uuid, err)
  239. }
  240. attachments = append(attachments, attach)
  241. }
  242. sess := x.NewSession()
  243. defer sessionRelease(sess)
  244. if err = sess.Begin(); err != nil {
  245. return err
  246. }
  247. if _, err = sess.Insert(issue); err != nil {
  248. return err
  249. } else if _, err = sess.Exec("UPDATE `repository` SET num_issues=num_issues+1 WHERE id=?", issue.RepoID); err != nil {
  250. return err
  251. }
  252. var label *Label
  253. for _, id := range labelIDs {
  254. if id == 0 {
  255. continue
  256. }
  257. label, err = getLabelByID(sess, id)
  258. if err != nil {
  259. return err
  260. }
  261. if err = issue.addLabel(sess, label); err != nil {
  262. return fmt.Errorf("addLabel: %v", err)
  263. }
  264. }
  265. if issue.MilestoneID > 0 {
  266. if err = changeMilestoneAssign(sess, 0, issue); err != nil {
  267. return err
  268. }
  269. }
  270. if err = newIssueUsers(sess, repo, issue); err != nil {
  271. return err
  272. }
  273. for i := range attachments {
  274. attachments[i].IssueID = issue.ID
  275. // No assign value could be 0, so ignore AllCols().
  276. if _, err = sess.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  277. return fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  278. }
  279. }
  280. // Notify watchers.
  281. act := &Action{
  282. ActUserID: issue.Poster.Id,
  283. ActUserName: issue.Poster.Name,
  284. ActEmail: issue.Poster.Email,
  285. OpType: CREATE_ISSUE,
  286. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Name),
  287. RepoID: repo.ID,
  288. RepoUserName: repo.Owner.Name,
  289. RepoName: repo.Name,
  290. IsPrivate: repo.IsPrivate,
  291. }
  292. if err = notifyWatchers(sess, act); err != nil {
  293. return err
  294. }
  295. return sess.Commit()
  296. }
  297. // GetIssueByRef returns an Issue specified by a GFM reference.
  298. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  299. func GetIssueByRef(ref string) (issue *Issue, err error) {
  300. var issueNumber int64
  301. var repo *Repository
  302. n := strings.IndexByte(ref, byte('#'))
  303. if n == -1 {
  304. return nil, ErrMissingIssueNumber
  305. }
  306. if issueNumber, err = strconv.ParseInt(ref[n+1:], 10, 64); err != nil {
  307. return
  308. }
  309. if repo, err = GetRepositoryByRef(ref[:n]); err != nil {
  310. return
  311. }
  312. return GetIssueByIndex(repo.ID, issueNumber)
  313. }
  314. // GetIssueByIndex returns issue by given index in repository.
  315. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  316. issue := &Issue{
  317. RepoID: repoID,
  318. Index: index,
  319. }
  320. has, err := x.Get(issue)
  321. if err != nil {
  322. return nil, err
  323. } else if !has {
  324. return nil, ErrIssueNotExist{0, repoID, index}
  325. }
  326. return issue, nil
  327. }
  328. // GetIssueByID returns an issue by given ID.
  329. func GetIssueByID(id int64) (*Issue, error) {
  330. issue := new(Issue)
  331. has, err := x.Id(id).Get(issue)
  332. if err != nil {
  333. return nil, err
  334. } else if !has {
  335. return nil, ErrIssueNotExist{id, 0, 0}
  336. }
  337. return issue, nil
  338. }
  339. // Issues returns a list of issues by given conditions.
  340. func Issues(uid, assigneeID, repoID, posterID, milestoneID int64, page int, isClosed, isMention bool, labels, sortType string) ([]*Issue, error) {
  341. sess := x.Limit(setting.IssuePagingNum, (page-1)*setting.IssuePagingNum)
  342. if repoID > 0 {
  343. sess.Where("issue.repo_id=?", repoID).And("issue.is_closed=?", isClosed)
  344. } else {
  345. sess.Where("issue.is_closed=?", isClosed)
  346. }
  347. if assigneeID > 0 {
  348. sess.And("issue.assignee_id=?", assigneeID)
  349. } else if posterID > 0 {
  350. sess.And("issue.poster_id=?", posterID)
  351. }
  352. if milestoneID > 0 {
  353. sess.And("issue.milestone_id=?", milestoneID)
  354. }
  355. switch sortType {
  356. case "oldest":
  357. sess.Asc("created")
  358. case "recentupdate":
  359. sess.Desc("updated")
  360. case "leastupdate":
  361. sess.Asc("updated")
  362. case "mostcomment":
  363. sess.Desc("num_comments")
  364. case "leastcomment":
  365. sess.Asc("num_comments")
  366. case "priority":
  367. sess.Desc("priority")
  368. default:
  369. sess.Desc("created")
  370. }
  371. labelIDs := base.StringsToInt64s(strings.Split(labels, ","))
  372. if len(labelIDs) > 0 {
  373. validJoin := false
  374. queryStr := "issue.id=issue_label.issue_id"
  375. for _, id := range labelIDs {
  376. if id == 0 {
  377. continue
  378. }
  379. validJoin = true
  380. queryStr += " AND issue_label.label_id=" + com.ToStr(id)
  381. }
  382. if validJoin {
  383. sess.Join("INNER", "issue_label", queryStr)
  384. }
  385. }
  386. if isMention {
  387. queryStr := "issue.id=issue_user.issue_id AND issue_user.is_mentioned=1"
  388. if uid > 0 {
  389. queryStr += " AND issue_user.uid=" + com.ToStr(uid)
  390. }
  391. sess.Join("INNER", "issue_user", queryStr)
  392. }
  393. issues := make([]*Issue, 0, setting.IssuePagingNum)
  394. return issues, sess.Find(&issues)
  395. }
  396. type IssueStatus int
  397. const (
  398. IS_OPEN = iota + 1
  399. IS_CLOSE
  400. )
  401. // GetIssueCountByPoster returns number of issues of repository by poster.
  402. func GetIssueCountByPoster(uid, rid int64, isClosed bool) int64 {
  403. count, _ := x.Where("repo_id=?", rid).And("poster_id=?", uid).And("is_closed=?", isClosed).Count(new(Issue))
  404. return count
  405. }
  406. // .___ ____ ___
  407. // | | ______ ________ __ ____ | | \______ ___________
  408. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  409. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  410. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  411. // \/ \/ \/ \/ \/
  412. // IssueUser represents an issue-user relation.
  413. type IssueUser struct {
  414. ID int64 `xorm:"pk autoincr"`
  415. UID int64 `xorm:"uid INDEX"` // User ID.
  416. IssueID int64
  417. RepoID int64 `xorm:"INDEX"`
  418. MilestoneID int64
  419. IsRead bool
  420. IsAssigned bool
  421. IsMentioned bool
  422. IsPoster bool
  423. IsClosed bool
  424. }
  425. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  426. users, err := repo.GetAssignees()
  427. if err != nil {
  428. return err
  429. }
  430. iu := &IssueUser{
  431. IssueID: issue.ID,
  432. RepoID: repo.ID,
  433. }
  434. // Poster can be anyone.
  435. isNeedAddPoster := true
  436. for _, u := range users {
  437. iu.ID = 0
  438. iu.UID = u.Id
  439. iu.IsPoster = iu.UID == issue.PosterID
  440. if isNeedAddPoster && iu.IsPoster {
  441. isNeedAddPoster = false
  442. }
  443. iu.IsAssigned = iu.UID == issue.AssigneeID
  444. if _, err = e.Insert(iu); err != nil {
  445. return err
  446. }
  447. }
  448. if isNeedAddPoster {
  449. iu.ID = 0
  450. iu.UID = issue.PosterID
  451. iu.IsPoster = true
  452. if _, err = e.Insert(iu); err != nil {
  453. return err
  454. }
  455. }
  456. return nil
  457. }
  458. // NewIssueUsers adds new issue-user relations for new issue of repository.
  459. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  460. sess := x.NewSession()
  461. defer sessionRelease(sess)
  462. if err = sess.Begin(); err != nil {
  463. return err
  464. }
  465. if err = newIssueUsers(sess, repo, issue); err != nil {
  466. return err
  467. }
  468. return sess.Commit()
  469. }
  470. // PairsContains returns true when pairs list contains given issue.
  471. func PairsContains(ius []*IssueUser, issueId, uid int64) int {
  472. for i := range ius {
  473. if ius[i].IssueID == issueId &&
  474. ius[i].UID == uid {
  475. return i
  476. }
  477. }
  478. return -1
  479. }
  480. // GetIssueUsers returns issue-user pairs by given repository and user.
  481. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  482. ius := make([]*IssueUser, 0, 10)
  483. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  484. return ius, err
  485. }
  486. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  487. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  488. if len(rids) == 0 {
  489. return []*IssueUser{}, nil
  490. }
  491. buf := bytes.NewBufferString("")
  492. for _, rid := range rids {
  493. buf.WriteString("repo_id=")
  494. buf.WriteString(com.ToStr(rid))
  495. buf.WriteString(" OR ")
  496. }
  497. cond := strings.TrimSuffix(buf.String(), " OR ")
  498. ius := make([]*IssueUser, 0, 10)
  499. sess := x.Limit(20, (page-1)*20).Where("is_closed=?", isClosed)
  500. if len(cond) > 0 {
  501. sess.And(cond)
  502. }
  503. err := sess.Find(&ius)
  504. return ius, err
  505. }
  506. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  507. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  508. ius := make([]*IssueUser, 0, 10)
  509. sess := x.Limit(20, (page-1)*20).Where("uid=?", uid).And("is_closed=?", isClosed)
  510. if rid > 0 {
  511. sess.And("repo_id=?", rid)
  512. }
  513. switch filterMode {
  514. case FM_ASSIGN:
  515. sess.And("is_assigned=?", true)
  516. case FM_CREATE:
  517. sess.And("is_poster=?", true)
  518. default:
  519. return ius, nil
  520. }
  521. err := sess.Find(&ius)
  522. return ius, err
  523. }
  524. // IssueStats represents issue statistic information.
  525. type IssueStats struct {
  526. OpenCount, ClosedCount int64
  527. AllCount int64
  528. AssignCount int64
  529. CreateCount int64
  530. MentionCount int64
  531. }
  532. // Filter modes.
  533. const (
  534. FM_ALL = iota
  535. FM_ASSIGN
  536. FM_CREATE
  537. FM_MENTION
  538. )
  539. func parseCountResult(results []map[string][]byte) int64 {
  540. if len(results) == 0 {
  541. return 0
  542. }
  543. for _, result := range results[0] {
  544. return com.StrTo(string(result)).MustInt64()
  545. }
  546. return 0
  547. }
  548. // GetIssueStats returns issue statistic information by given conditions.
  549. func GetIssueStats(repoID, uid, labelID, milestoneID int64, isShowClosed bool, filterMode int) *IssueStats {
  550. stats := &IssueStats{}
  551. // issue := new(Issue)
  552. queryStr := "SELECT COUNT(*) FROM `issue` "
  553. if labelID > 0 {
  554. queryStr += "INNER JOIN `issue_label` ON `issue`.id=`issue_label`.issue_id AND `issue_label`.label_id=" + com.ToStr(labelID)
  555. }
  556. baseCond := " WHERE issue.repo_id=? AND issue.is_closed=?"
  557. if milestoneID > 0 {
  558. baseCond += " AND issue.milestone_id=" + com.ToStr(milestoneID)
  559. }
  560. switch filterMode {
  561. case FM_ALL:
  562. resutls, _ := x.Query(queryStr+baseCond, repoID, false)
  563. stats.OpenCount = parseCountResult(resutls)
  564. resutls, _ = x.Query(queryStr+baseCond, repoID, true)
  565. stats.ClosedCount = parseCountResult(resutls)
  566. case FM_ASSIGN:
  567. baseCond += " AND assignee_id=?"
  568. resutls, _ := x.Query(queryStr+baseCond, repoID, false, uid)
  569. stats.OpenCount = parseCountResult(resutls)
  570. resutls, _ = x.Query(queryStr+baseCond, repoID, true, uid)
  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. // HashTag returns unique hash tag for comment.
  1143. func (c *Comment) HashTag() string {
  1144. return "issuecomment-" + com.ToStr(c.ID)
  1145. }
  1146. // EventTag returns unique event hash tag for comment.
  1147. func (c *Comment) EventTag() string {
  1148. return "event-" + com.ToStr(c.ID)
  1149. }
  1150. func (c *Comment) AfterSet(colName string, _ xorm.Cell) {
  1151. var err error
  1152. switch colName {
  1153. case "id":
  1154. c.Attachments, err = GetAttachmentsByCommentID(c.ID)
  1155. if err != nil {
  1156. log.Error(3, "GetAttachmentsByCommentID[%d]: %v", c.ID, err)
  1157. }
  1158. case "poster_id":
  1159. c.Poster, err = GetUserByID(c.PosterID)
  1160. if err != nil {
  1161. if IsErrUserNotExist(err) {
  1162. c.PosterID = -1
  1163. c.Poster = &User{Name: "someone"}
  1164. } else {
  1165. log.Error(3, "GetUserByID[%d]: %v", c.ID, err)
  1166. }
  1167. }
  1168. }
  1169. }
  1170. func createComment(e *xorm.Session, u *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content string, uuids []string) (_ *Comment, err error) {
  1171. comment := &Comment{
  1172. PosterID: u.Id,
  1173. Type: cmtType,
  1174. IssueID: issue.ID,
  1175. CommitID: commitID,
  1176. Line: line,
  1177. Content: content,
  1178. }
  1179. if _, err = e.Insert(comment); err != nil {
  1180. return nil, err
  1181. }
  1182. // Check comment type.
  1183. switch cmtType {
  1184. case COMMENT_TYPE_COMMENT:
  1185. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", issue.ID); err != nil {
  1186. return nil, err
  1187. }
  1188. // Check attachments.
  1189. attachments := make([]*Attachment, 0, len(uuids))
  1190. for _, uuid := range uuids {
  1191. attach, err := getAttachmentByUUID(e, uuid)
  1192. if err != nil {
  1193. if IsErrAttachmentNotExist(err) {
  1194. continue
  1195. }
  1196. return nil, fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  1197. }
  1198. attachments = append(attachments, attach)
  1199. }
  1200. for i := range attachments {
  1201. attachments[i].IssueID = issue.ID
  1202. attachments[i].CommentID = comment.ID
  1203. // No assign value could be 0, so ignore AllCols().
  1204. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  1205. return nil, fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  1206. }
  1207. }
  1208. // Notify watchers.
  1209. act := &Action{
  1210. ActUserID: u.Id,
  1211. ActUserName: u.LowerName,
  1212. ActEmail: u.Email,
  1213. OpType: COMMENT_ISSUE,
  1214. Content: fmt.Sprintf("%d|%s", issue.Index, strings.Split(content, "\n")[0]),
  1215. RepoID: repo.ID,
  1216. RepoUserName: repo.Owner.LowerName,
  1217. RepoName: repo.LowerName,
  1218. IsPrivate: repo.IsPrivate,
  1219. }
  1220. if err = notifyWatchers(e, act); err != nil {
  1221. return nil, err
  1222. }
  1223. case COMMENT_TYPE_REOPEN:
  1224. if _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", repo.ID); err != nil {
  1225. return nil, err
  1226. }
  1227. case COMMENT_TYPE_CLOSE:
  1228. if _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", repo.ID); err != nil {
  1229. return nil, err
  1230. }
  1231. }
  1232. return comment, nil
  1233. }
  1234. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  1235. cmtType := COMMENT_TYPE_CLOSE
  1236. if !issue.IsClosed {
  1237. cmtType = COMMENT_TYPE_REOPEN
  1238. }
  1239. return createComment(e, doer, repo, issue, 0, 0, cmtType, "", nil)
  1240. }
  1241. // CreateComment creates comment of issue or commit.
  1242. func CreateComment(doer *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content string, attachments []string) (comment *Comment, err error) {
  1243. sess := x.NewSession()
  1244. defer sessionRelease(sess)
  1245. if err = sess.Begin(); err != nil {
  1246. return nil, err
  1247. }
  1248. comment, err = createComment(sess, doer, repo, issue, commitID, line, cmtType, content, attachments)
  1249. if err != nil {
  1250. return nil, err
  1251. }
  1252. return comment, sess.Commit()
  1253. }
  1254. // CreateIssueComment creates a plain issue comment.
  1255. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  1256. return CreateComment(doer, repo, issue, 0, 0, COMMENT_TYPE_COMMENT, content, attachments)
  1257. }
  1258. // GetCommentById returns the comment with the given id
  1259. func GetCommentById(id int64) (*Comment, error) {
  1260. c := new(Comment)
  1261. _, err := x.Id(id).Get(c)
  1262. return c, err
  1263. }
  1264. // GetCommentsByIssueID returns all comments of issue by given ID.
  1265. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  1266. comments := make([]*Comment, 0, 10)
  1267. return comments, x.Where("issue_id=?", issueID).Asc("created").Find(&comments)
  1268. }
  1269. func (c *Comment) AfterDelete() {
  1270. _, err := DeleteAttachmentsByComment(c.ID, true)
  1271. if err != nil {
  1272. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  1273. }
  1274. }
  1275. // Attachment represent a attachment of issue/comment/release.
  1276. type Attachment struct {
  1277. ID int64 `xorm:"pk autoincr"`
  1278. UUID string `xorm:"uuid UNIQUE"`
  1279. IssueID int64 `xorm:"INDEX"`
  1280. CommentID int64
  1281. ReleaseID int64 `xorm:"INDEX"`
  1282. Name string
  1283. Created time.Time `xorm:"CREATED"`
  1284. }
  1285. // AttachmentLocalPath returns where attachment is stored in local file system based on given UUID.
  1286. func AttachmentLocalPath(uuid string) string {
  1287. return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid)
  1288. }
  1289. // LocalPath returns where attachment is stored in local file system.
  1290. func (attach *Attachment) LocalPath() string {
  1291. return AttachmentLocalPath(attach.UUID)
  1292. }
  1293. // NewAttachment creates a new attachment object.
  1294. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) {
  1295. attach := &Attachment{
  1296. UUID: gouuid.NewV4().String(),
  1297. Name: name,
  1298. }
  1299. if err = os.MkdirAll(path.Dir(attach.LocalPath()), os.ModePerm); err != nil {
  1300. return nil, fmt.Errorf("MkdirAll: %v", err)
  1301. }
  1302. fw, err := os.Create(attach.LocalPath())
  1303. if err != nil {
  1304. return nil, fmt.Errorf("Create: %v", err)
  1305. }
  1306. defer fw.Close()
  1307. if _, err = fw.Write(buf); err != nil {
  1308. return nil, fmt.Errorf("Write: %v", err)
  1309. } else if _, err = io.Copy(fw, file); err != nil {
  1310. return nil, fmt.Errorf("Copy: %v", err)
  1311. }
  1312. sess := x.NewSession()
  1313. defer sessionRelease(sess)
  1314. if err := sess.Begin(); err != nil {
  1315. return nil, err
  1316. }
  1317. if _, err := sess.Insert(attach); err != nil {
  1318. return nil, err
  1319. }
  1320. return attach, sess.Commit()
  1321. }
  1322. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  1323. attach := &Attachment{UUID: uuid}
  1324. has, err := x.Get(attach)
  1325. if err != nil {
  1326. return nil, err
  1327. } else if !has {
  1328. return nil, ErrAttachmentNotExist{0, uuid}
  1329. }
  1330. return attach, nil
  1331. }
  1332. // GetAttachmentByUUID returns attachment by given UUID.
  1333. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  1334. return getAttachmentByUUID(x, uuid)
  1335. }
  1336. // GetAttachmentsByIssueID returns all attachments for given issue by ID.
  1337. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  1338. attachments := make([]*Attachment, 0, 10)
  1339. return attachments, x.Where("issue_id=? AND comment_id=0", issueID).Find(&attachments)
  1340. }
  1341. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  1342. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  1343. attachments := make([]*Attachment, 0, 10)
  1344. return attachments, x.Where("comment_id=?", commentID).Find(&attachments)
  1345. }
  1346. // DeleteAttachment deletes the given attachment and optionally the associated file.
  1347. func DeleteAttachment(a *Attachment, remove bool) error {
  1348. _, err := DeleteAttachments([]*Attachment{a}, remove)
  1349. return err
  1350. }
  1351. // DeleteAttachments deletes the given attachments and optionally the associated files.
  1352. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  1353. for i, a := range attachments {
  1354. if remove {
  1355. if err := os.Remove(a.LocalPath()); err != nil {
  1356. return i, err
  1357. }
  1358. }
  1359. if _, err := x.Delete(a.ID); err != nil {
  1360. return i, err
  1361. }
  1362. }
  1363. return len(attachments), nil
  1364. }
  1365. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  1366. func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
  1367. attachments, err := GetAttachmentsByIssueID(issueId)
  1368. if err != nil {
  1369. return 0, err
  1370. }
  1371. return DeleteAttachments(attachments, remove)
  1372. }
  1373. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  1374. func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
  1375. attachments, err := GetAttachmentsByCommentID(commentId)
  1376. if err != nil {
  1377. return 0, err
  1378. }
  1379. return DeleteAttachments(attachments, remove)
  1380. }