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 46 kB

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