issue.go 45 KB

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