issue.go 47 KB

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