issue.go 48 KB

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