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

issue.go 49KB

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