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

issue.go 50 kB

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