You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

issue.go 47KB

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