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 49KB

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