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
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
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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891
  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(userID int64) error {
  383. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  384. return err
  385. }
  386. if err := setNotificationStatusRead(x, userID, issue.ID); err != nil {
  387. return err
  388. }
  389. return nil
  390. }
  391. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  392. _, err := e.Id(issue.ID).Cols(cols...).Update(issue)
  393. return err
  394. }
  395. // UpdateIssueCols only updates values of specific columns for given issue.
  396. func UpdateIssueCols(issue *Issue, cols ...string) error {
  397. return updateIssueCols(x, issue, cols...)
  398. }
  399. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
  400. // Nothing should be performed if current status is same as target status
  401. if issue.IsClosed == isClosed {
  402. return nil
  403. }
  404. issue.IsClosed = isClosed
  405. if err = updateIssueCols(e, issue, "is_closed"); err != nil {
  406. return err
  407. } else if err = updateIssueUsersByStatus(e, issue.ID, isClosed); err != nil {
  408. return err
  409. }
  410. // Update issue count of labels
  411. if err = issue.getLabels(e); err != nil {
  412. return err
  413. }
  414. for idx := range issue.Labels {
  415. if issue.IsClosed {
  416. issue.Labels[idx].NumClosedIssues++
  417. } else {
  418. issue.Labels[idx].NumClosedIssues--
  419. }
  420. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  421. return err
  422. }
  423. }
  424. // Update issue count of milestone
  425. if err = changeMilestoneIssueStats(e, issue); err != nil {
  426. return err
  427. }
  428. // New action comment
  429. if _, err = createStatusComment(e, doer, repo, issue); err != nil {
  430. return err
  431. }
  432. return nil
  433. }
  434. // ChangeStatus changes issue status to open or closed.
  435. func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (err error) {
  436. sess := x.NewSession()
  437. defer sessionRelease(sess)
  438. if err = sess.Begin(); err != nil {
  439. return err
  440. }
  441. if err = issue.changeStatus(sess, doer, repo, isClosed); err != nil {
  442. return err
  443. }
  444. if err = sess.Commit(); err != nil {
  445. return fmt.Errorf("Commit: %v", err)
  446. }
  447. if issue.IsPull {
  448. // Merge pull request calls issue.changeStatus so we need to handle separately.
  449. issue.PullRequest.Issue = issue
  450. apiPullRequest := &api.PullRequestPayload{
  451. Index: issue.Index,
  452. PullRequest: issue.PullRequest.APIFormat(),
  453. Repository: repo.APIFormat(AccessModeNone),
  454. Sender: doer.APIFormat(),
  455. }
  456. if isClosed {
  457. apiPullRequest.Action = api.HookIssueClosed
  458. } else {
  459. apiPullRequest.Action = api.HookIssueReOpened
  460. }
  461. err = PrepareWebhooks(repo, HookEventPullRequest, apiPullRequest)
  462. }
  463. if err != nil {
  464. log.Error(4, "PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  465. } else {
  466. go HookQueue.Add(repo.ID)
  467. }
  468. return nil
  469. }
  470. // ChangeTitle changes the title of this issue, as the given user.
  471. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
  472. oldTitle := issue.Title
  473. issue.Title = title
  474. if err = UpdateIssueCols(issue, "name"); err != nil {
  475. return fmt.Errorf("UpdateIssueCols: %v", err)
  476. }
  477. if issue.IsPull {
  478. issue.PullRequest.Issue = issue
  479. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  480. Action: api.HookIssueEdited,
  481. Index: issue.Index,
  482. Changes: &api.ChangesPayload{
  483. Title: &api.ChangesFromPayload{
  484. From: oldTitle,
  485. },
  486. },
  487. PullRequest: issue.PullRequest.APIFormat(),
  488. Repository: issue.Repo.APIFormat(AccessModeNone),
  489. Sender: doer.APIFormat(),
  490. })
  491. }
  492. if err != nil {
  493. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  494. } else {
  495. go HookQueue.Add(issue.RepoID)
  496. }
  497. return nil
  498. }
  499. // ChangeContent changes issue content, as the given user.
  500. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  501. oldContent := issue.Content
  502. issue.Content = content
  503. if err = UpdateIssueCols(issue, "content"); err != nil {
  504. return fmt.Errorf("UpdateIssueCols: %v", err)
  505. }
  506. if issue.IsPull {
  507. issue.PullRequest.Issue = issue
  508. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  509. Action: api.HookIssueEdited,
  510. Index: issue.Index,
  511. Changes: &api.ChangesPayload{
  512. Body: &api.ChangesFromPayload{
  513. From: oldContent,
  514. },
  515. },
  516. PullRequest: issue.PullRequest.APIFormat(),
  517. Repository: issue.Repo.APIFormat(AccessModeNone),
  518. Sender: doer.APIFormat(),
  519. })
  520. }
  521. if err != nil {
  522. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  523. } else {
  524. go HookQueue.Add(issue.RepoID)
  525. }
  526. return nil
  527. }
  528. // ChangeAssignee changes the Asssignee field of this issue.
  529. func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
  530. issue.AssigneeID = assigneeID
  531. if err = UpdateIssueUserByAssignee(issue); err != nil {
  532. return fmt.Errorf("UpdateIssueUserByAssignee: %v", err)
  533. }
  534. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  535. if err != nil && !IsErrUserNotExist(err) {
  536. log.Error(4, "GetUserByID [assignee_id: %v]: %v", issue.AssigneeID, err)
  537. return nil
  538. }
  539. // Error not nil here means user does not exist, which is remove assignee.
  540. isRemoveAssignee := err != nil
  541. if issue.IsPull {
  542. issue.PullRequest.Issue = issue
  543. apiPullRequest := &api.PullRequestPayload{
  544. Index: issue.Index,
  545. PullRequest: issue.PullRequest.APIFormat(),
  546. Repository: issue.Repo.APIFormat(AccessModeNone),
  547. Sender: doer.APIFormat(),
  548. }
  549. if isRemoveAssignee {
  550. apiPullRequest.Action = api.HookIssueUnassigned
  551. } else {
  552. apiPullRequest.Action = api.HookIssueAssigned
  553. }
  554. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest)
  555. }
  556. if err != nil {
  557. log.Error(4, "PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err)
  558. } else {
  559. go HookQueue.Add(issue.RepoID)
  560. }
  561. return nil
  562. }
  563. // NewIssueOptions represents the options of a new issue.
  564. type NewIssueOptions struct {
  565. Repo *Repository
  566. Issue *Issue
  567. LableIDs []int64
  568. Attachments []string // In UUID format.
  569. IsPull bool
  570. }
  571. func newIssue(e *xorm.Session, opts NewIssueOptions) (err error) {
  572. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  573. opts.Issue.Index = opts.Repo.NextIssueIndex()
  574. if opts.Issue.MilestoneID > 0 {
  575. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  576. if err != nil && !IsErrMilestoneNotExist(err) {
  577. return fmt.Errorf("getMilestoneByID: %v", err)
  578. }
  579. // Assume milestone is invalid and drop silently.
  580. opts.Issue.MilestoneID = 0
  581. if milestone != nil {
  582. opts.Issue.MilestoneID = milestone.ID
  583. opts.Issue.Milestone = milestone
  584. if err = changeMilestoneAssign(e, opts.Issue, -1); err != nil {
  585. return err
  586. }
  587. }
  588. }
  589. if opts.Issue.AssigneeID > 0 {
  590. assignee, err := getUserByID(e, opts.Issue.AssigneeID)
  591. if err != nil && !IsErrUserNotExist(err) {
  592. return fmt.Errorf("getUserByID: %v", err)
  593. }
  594. // Assume assignee is invalid and drop silently.
  595. opts.Issue.AssigneeID = 0
  596. if assignee != nil {
  597. valid, err := hasAccess(e, assignee, opts.Repo, AccessModeWrite)
  598. if err != nil {
  599. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assignee.ID, opts.Repo.ID, err)
  600. }
  601. if valid {
  602. opts.Issue.AssigneeID = assignee.ID
  603. opts.Issue.Assignee = assignee
  604. }
  605. }
  606. }
  607. // Milestone and assignee validation should happen before insert actual object.
  608. if _, err = e.Insert(opts.Issue); err != nil {
  609. return err
  610. }
  611. if opts.IsPull {
  612. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  613. } else {
  614. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  615. }
  616. if err != nil {
  617. return err
  618. }
  619. if len(opts.LableIDs) > 0 {
  620. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  621. // So we have to get all needed labels first.
  622. labels := make([]*Label, 0, len(opts.LableIDs))
  623. if err = e.In("id", opts.LableIDs).Find(&labels); err != nil {
  624. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LableIDs, err)
  625. }
  626. for _, label := range labels {
  627. // Silently drop invalid labels.
  628. if label.RepoID != opts.Repo.ID {
  629. continue
  630. }
  631. if err = opts.Issue.addLabel(e, label); err != nil {
  632. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  633. }
  634. }
  635. }
  636. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  637. return err
  638. }
  639. if len(opts.Attachments) > 0 {
  640. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  641. if err != nil {
  642. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  643. }
  644. for i := 0; i < len(attachments); i++ {
  645. attachments[i].IssueID = opts.Issue.ID
  646. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  647. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  648. }
  649. }
  650. }
  651. return opts.Issue.loadAttributes(e)
  652. }
  653. // NewIssue creates new issue with labels for repository.
  654. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  655. sess := x.NewSession()
  656. defer sessionRelease(sess)
  657. if err = sess.Begin(); err != nil {
  658. return err
  659. }
  660. if err = newIssue(sess, NewIssueOptions{
  661. Repo: repo,
  662. Issue: issue,
  663. LableIDs: labelIDs,
  664. Attachments: uuids,
  665. }); err != nil {
  666. return fmt.Errorf("newIssue: %v", err)
  667. }
  668. if err = sess.Commit(); err != nil {
  669. return fmt.Errorf("Commit: %v", err)
  670. }
  671. if err = NotifyWatchers(&Action{
  672. ActUserID: issue.Poster.ID,
  673. ActUserName: issue.Poster.Name,
  674. OpType: ActionCreateIssue,
  675. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  676. RepoID: repo.ID,
  677. RepoUserName: repo.Owner.Name,
  678. RepoName: repo.Name,
  679. IsPrivate: repo.IsPrivate,
  680. }); err != nil {
  681. log.Error(4, "NotifyWatchers: %v", err)
  682. }
  683. if err = issue.MailParticipants(); err != nil {
  684. log.Error(4, "MailParticipants: %v", err)
  685. }
  686. return nil
  687. }
  688. // GetIssueByRef returns an Issue specified by a GFM reference.
  689. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  690. func GetIssueByRef(ref string) (*Issue, error) {
  691. n := strings.IndexByte(ref, byte('#'))
  692. if n == -1 {
  693. return nil, errMissingIssueNumber
  694. }
  695. index, err := com.StrTo(ref[n+1:]).Int64()
  696. if err != nil {
  697. return nil, err
  698. }
  699. repo, err := GetRepositoryByRef(ref[:n])
  700. if err != nil {
  701. return nil, err
  702. }
  703. issue, err := GetIssueByIndex(repo.ID, index)
  704. if err != nil {
  705. return nil, err
  706. }
  707. return issue, issue.LoadAttributes()
  708. }
  709. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  710. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  711. issue := &Issue{
  712. RepoID: repoID,
  713. Index: index,
  714. }
  715. has, err := x.Get(issue)
  716. if err != nil {
  717. return nil, err
  718. } else if !has {
  719. return nil, ErrIssueNotExist{0, repoID, index}
  720. }
  721. return issue, nil
  722. }
  723. // GetIssueByIndex returns issue by index in a repository.
  724. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  725. issue, err := GetRawIssueByIndex(repoID, index)
  726. if err != nil {
  727. return nil, err
  728. }
  729. return issue, issue.LoadAttributes()
  730. }
  731. func getIssueByID(e Engine, id int64) (*Issue, error) {
  732. issue := new(Issue)
  733. has, err := e.Id(id).Get(issue)
  734. if err != nil {
  735. return nil, err
  736. } else if !has {
  737. return nil, ErrIssueNotExist{id, 0, 0}
  738. }
  739. return issue, issue.LoadAttributes()
  740. }
  741. // GetIssueByID returns an issue by given ID.
  742. func GetIssueByID(id int64) (*Issue, error) {
  743. return getIssueByID(x, id)
  744. }
  745. // IssuesOptions represents options of an issue.
  746. type IssuesOptions struct {
  747. RepoID int64
  748. AssigneeID int64
  749. PosterID int64
  750. MentionedID int64
  751. MilestoneID int64
  752. RepoIDs []int64
  753. Page int
  754. IsClosed bool
  755. IsPull bool
  756. Labels string
  757. SortType string
  758. }
  759. // Issues returns a list of issues by given conditions.
  760. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  761. if opts.Page <= 0 {
  762. opts.Page = 1
  763. }
  764. sess := x.Limit(setting.UI.IssuePagingNum, (opts.Page-1)*setting.UI.IssuePagingNum)
  765. if opts.RepoID > 0 {
  766. sess.And("issue.repo_id=?", opts.RepoID)
  767. } else if len(opts.RepoIDs) > 0 {
  768. // In case repository IDs are provided but actually no repository has issue.
  769. sess.In("issue.repo_id", opts.RepoIDs)
  770. }
  771. sess.And("issue.is_closed=?", opts.IsClosed)
  772. if opts.AssigneeID > 0 {
  773. sess.And("issue.assignee_id=?", opts.AssigneeID)
  774. }
  775. if opts.PosterID > 0 {
  776. sess.And("issue.poster_id=?", opts.PosterID)
  777. }
  778. if opts.MentionedID > 0 {
  779. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  780. And("issue_user.is_mentioned = ?", true).
  781. And("issue_user.uid = ?", opts.MentionedID)
  782. }
  783. if opts.MilestoneID > 0 {
  784. sess.And("issue.milestone_id=?", opts.MilestoneID)
  785. }
  786. sess.And("issue.is_pull=?", opts.IsPull)
  787. switch opts.SortType {
  788. case "oldest":
  789. sess.Asc("issue.created_unix")
  790. case "recentupdate":
  791. sess.Desc("issue.updated_unix")
  792. case "leastupdate":
  793. sess.Asc("issue.updated_unix")
  794. case "mostcomment":
  795. sess.Desc("issue.num_comments")
  796. case "leastcomment":
  797. sess.Asc("issue.num_comments")
  798. case "priority":
  799. sess.Desc("issue.priority")
  800. default:
  801. sess.Desc("issue.created_unix")
  802. }
  803. if len(opts.Labels) > 0 && opts.Labels != "0" {
  804. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  805. if err != nil {
  806. return nil, err
  807. }
  808. if len(labelIDs) > 0 {
  809. sess.
  810. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  811. In("issue_label.label_id", labelIDs)
  812. }
  813. }
  814. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  815. if err := sess.Find(&issues); err != nil {
  816. return nil, fmt.Errorf("Find: %v", err)
  817. }
  818. // FIXME: use IssueList to improve performance.
  819. for i := range issues {
  820. if err := issues[i].LoadAttributes(); err != nil {
  821. return nil, fmt.Errorf("LoadAttributes [%d]: %v", issues[i].ID, err)
  822. }
  823. }
  824. return issues, nil
  825. }
  826. // .___ ____ ___
  827. // | | ______ ________ __ ____ | | \______ ___________
  828. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  829. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  830. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  831. // \/ \/ \/ \/ \/
  832. // IssueUser represents an issue-user relation.
  833. type IssueUser struct {
  834. ID int64 `xorm:"pk autoincr"`
  835. UID int64 `xorm:"INDEX"` // User ID.
  836. IssueID int64
  837. RepoID int64 `xorm:"INDEX"`
  838. MilestoneID int64
  839. IsRead bool
  840. IsAssigned bool
  841. IsMentioned bool
  842. IsPoster bool
  843. IsClosed bool
  844. }
  845. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  846. assignees, err := repo.getAssignees(e)
  847. if err != nil {
  848. return fmt.Errorf("getAssignees: %v", err)
  849. }
  850. // Poster can be anyone, append later if not one of assignees.
  851. isPosterAssignee := false
  852. // Leave a seat for poster itself to append later, but if poster is one of assignee
  853. // and just waste 1 unit is cheaper than re-allocate memory once.
  854. issueUsers := make([]*IssueUser, 0, len(assignees)+1)
  855. for _, assignee := range assignees {
  856. isPoster := assignee.ID == issue.PosterID
  857. issueUsers = append(issueUsers, &IssueUser{
  858. IssueID: issue.ID,
  859. RepoID: repo.ID,
  860. UID: assignee.ID,
  861. IsPoster: isPoster,
  862. IsAssigned: assignee.ID == issue.AssigneeID,
  863. })
  864. if !isPosterAssignee && isPoster {
  865. isPosterAssignee = true
  866. }
  867. }
  868. if !isPosterAssignee {
  869. issueUsers = append(issueUsers, &IssueUser{
  870. IssueID: issue.ID,
  871. RepoID: repo.ID,
  872. UID: issue.PosterID,
  873. IsPoster: true,
  874. })
  875. }
  876. if _, err = e.Insert(issueUsers); err != nil {
  877. return err
  878. }
  879. return nil
  880. }
  881. // NewIssueUsers adds new issue-user relations for new issue of repository.
  882. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  883. sess := x.NewSession()
  884. defer sessionRelease(sess)
  885. if err = sess.Begin(); err != nil {
  886. return err
  887. }
  888. if err = newIssueUsers(sess, repo, issue); err != nil {
  889. return err
  890. }
  891. return sess.Commit()
  892. }
  893. // PairsContains returns true when pairs list contains given issue.
  894. func PairsContains(ius []*IssueUser, issueID, uid int64) int {
  895. for i := range ius {
  896. if ius[i].IssueID == issueID &&
  897. ius[i].UID == uid {
  898. return i
  899. }
  900. }
  901. return -1
  902. }
  903. // GetIssueUsers returns issue-user pairs by given repository and user.
  904. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  905. ius := make([]*IssueUser, 0, 10)
  906. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  907. return ius, err
  908. }
  909. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  910. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  911. if len(rids) == 0 {
  912. return []*IssueUser{}, nil
  913. }
  914. ius := make([]*IssueUser, 0, 10)
  915. sess := x.
  916. Limit(20, (page-1)*20).
  917. Where("is_closed=?", isClosed).
  918. In("repo_id", rids)
  919. err := sess.Find(&ius)
  920. return ius, err
  921. }
  922. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  923. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  924. ius := make([]*IssueUser, 0, 10)
  925. sess := x.
  926. Limit(20, (page-1)*20).
  927. Where("uid=?", uid).
  928. And("is_closed=?", isClosed)
  929. if rid > 0 {
  930. sess.And("repo_id=?", rid)
  931. }
  932. switch filterMode {
  933. case FilterModeAssign:
  934. sess.And("is_assigned=?", true)
  935. case FilterModeCreate:
  936. sess.And("is_poster=?", true)
  937. default:
  938. return ius, nil
  939. }
  940. err := sess.Find(&ius)
  941. return ius, err
  942. }
  943. // UpdateIssueMentions extracts mentioned people from content and
  944. // updates issue-user relations for them.
  945. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  946. if len(mentions) == 0 {
  947. return nil
  948. }
  949. for i := range mentions {
  950. mentions[i] = strings.ToLower(mentions[i])
  951. }
  952. users := make([]*User, 0, len(mentions))
  953. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  954. return fmt.Errorf("find mentioned users: %v", err)
  955. }
  956. ids := make([]int64, 0, len(mentions))
  957. for _, user := range users {
  958. ids = append(ids, user.ID)
  959. if !user.IsOrganization() || user.NumMembers == 0 {
  960. continue
  961. }
  962. memberIDs := make([]int64, 0, user.NumMembers)
  963. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  964. if err != nil {
  965. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  966. }
  967. for _, orgUser := range orgUsers {
  968. memberIDs = append(memberIDs, orgUser.ID)
  969. }
  970. ids = append(ids, memberIDs...)
  971. }
  972. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  973. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  974. }
  975. return nil
  976. }
  977. // IssueStats represents issue statistic information.
  978. type IssueStats struct {
  979. OpenCount, ClosedCount int64
  980. AllCount int64
  981. AssignCount int64
  982. CreateCount int64
  983. MentionCount int64
  984. }
  985. // Filter modes.
  986. const (
  987. FilterModeAll = iota
  988. FilterModeAssign
  989. FilterModeCreate
  990. FilterModeMention
  991. )
  992. func parseCountResult(results []map[string][]byte) int64 {
  993. if len(results) == 0 {
  994. return 0
  995. }
  996. for _, result := range results[0] {
  997. return com.StrTo(string(result)).MustInt64()
  998. }
  999. return 0
  1000. }
  1001. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1002. type IssueStatsOptions struct {
  1003. RepoID int64
  1004. Labels string
  1005. MilestoneID int64
  1006. AssigneeID int64
  1007. MentionedID int64
  1008. PosterID int64
  1009. IsPull bool
  1010. }
  1011. // GetIssueStats returns issue statistic information by given conditions.
  1012. func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
  1013. stats := &IssueStats{}
  1014. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1015. sess := x.
  1016. Where("issue.repo_id = ?", opts.RepoID).
  1017. And("is_pull = ?", opts.IsPull)
  1018. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1019. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1020. if err != nil {
  1021. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1022. } else if len(labelIDs) > 0 {
  1023. sess.Join("INNER", "issue_label", "issue.id = issue_id").
  1024. In("label_id", labelIDs)
  1025. }
  1026. }
  1027. if opts.MilestoneID > 0 {
  1028. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1029. }
  1030. if opts.AssigneeID > 0 {
  1031. sess.And("assignee_id = ?", opts.AssigneeID)
  1032. }
  1033. if opts.PosterID > 0 {
  1034. sess.And("poster_id = ?", opts.PosterID)
  1035. }
  1036. if opts.MentionedID > 0 {
  1037. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1038. And("issue_user.uid = ?", opts.MentionedID).
  1039. And("issue_user.is_mentioned = ?", true)
  1040. }
  1041. return sess
  1042. }
  1043. stats.OpenCount, _ = countSession(opts).
  1044. And("is_closed = ?", false).
  1045. Count(&Issue{})
  1046. stats.ClosedCount, _ = countSession(opts).
  1047. And("is_closed = ?", true).
  1048. Count(&Issue{})
  1049. return stats
  1050. }
  1051. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1052. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  1053. stats := &IssueStats{}
  1054. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1055. sess := x.
  1056. Where("issue.is_closed = ?", isClosed).
  1057. And("issue.is_pull = ?", isPull)
  1058. if repoID > 0 {
  1059. sess.And("repo_id = ?", repoID)
  1060. } else if len(repoIDs) > 0 {
  1061. sess.In("repo_id", repoIDs)
  1062. }
  1063. return sess
  1064. }
  1065. stats.AssignCount, _ = countSession(false, isPull, repoID, repoIDs).
  1066. And("assignee_id = ?", uid).
  1067. Count(&Issue{})
  1068. stats.CreateCount, _ = countSession(false, isPull, repoID, repoIDs).
  1069. And("poster_id = ?", uid).
  1070. Count(&Issue{})
  1071. openCountSession := countSession(false, isPull, repoID, repoIDs)
  1072. closedCountSession := countSession(true, isPull, repoID, repoIDs)
  1073. switch filterMode {
  1074. case FilterModeAssign:
  1075. openCountSession.And("assignee_id = ?", uid)
  1076. closedCountSession.And("assignee_id = ?", uid)
  1077. case FilterModeCreate:
  1078. openCountSession.And("poster_id = ?", uid)
  1079. closedCountSession.And("poster_id = ?", uid)
  1080. }
  1081. stats.OpenCount, _ = openCountSession.Count(&Issue{})
  1082. stats.ClosedCount, _ = closedCountSession.Count(&Issue{})
  1083. return stats
  1084. }
  1085. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1086. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1087. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1088. sess := x.
  1089. Where("issue.repo_id = ?", isClosed).
  1090. And("is_pull = ?", isPull).
  1091. And("repo_id = ?", repoID)
  1092. return sess
  1093. }
  1094. openCountSession := countSession(false, isPull, repoID)
  1095. closedCountSession := countSession(true, isPull, repoID)
  1096. switch filterMode {
  1097. case FilterModeAssign:
  1098. openCountSession.And("assignee_id = ?", uid)
  1099. closedCountSession.And("assignee_id = ?", uid)
  1100. case FilterModeCreate:
  1101. openCountSession.And("poster_id = ?", uid)
  1102. closedCountSession.And("poster_id = ?", uid)
  1103. }
  1104. openResult, _ := openCountSession.Count(&Issue{})
  1105. closedResult, _ := closedCountSession.Count(&Issue{})
  1106. return openResult, closedResult
  1107. }
  1108. func updateIssue(e Engine, issue *Issue) error {
  1109. _, err := e.Id(issue.ID).AllCols().Update(issue)
  1110. return err
  1111. }
  1112. // UpdateIssue updates all fields of given issue.
  1113. func UpdateIssue(issue *Issue) error {
  1114. return updateIssue(x, issue)
  1115. }
  1116. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  1117. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  1118. return err
  1119. }
  1120. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  1121. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  1122. return updateIssueUsersByStatus(x, issueID, isClosed)
  1123. }
  1124. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  1125. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE issue_id = ?", false, issue.ID); err != nil {
  1126. return err
  1127. }
  1128. // Assignee ID equals to 0 means clear assignee.
  1129. if issue.AssigneeID > 0 {
  1130. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE uid = ? AND issue_id = ?", true, issue.AssigneeID, issue.ID); err != nil {
  1131. return err
  1132. }
  1133. }
  1134. return updateIssue(e, issue)
  1135. }
  1136. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  1137. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  1138. sess := x.NewSession()
  1139. defer sessionRelease(sess)
  1140. if err = sess.Begin(); err != nil {
  1141. return err
  1142. }
  1143. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  1144. return err
  1145. }
  1146. return sess.Commit()
  1147. }
  1148. // UpdateIssueUserByRead updates issue-user relation for reading.
  1149. func UpdateIssueUserByRead(uid, issueID int64) error {
  1150. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  1151. return err
  1152. }
  1153. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
  1154. func UpdateIssueUsersByMentions(e Engine, issueID int64, uids []int64) error {
  1155. for _, uid := range uids {
  1156. iu := &IssueUser{
  1157. UID: uid,
  1158. IssueID: issueID,
  1159. }
  1160. has, err := e.Get(iu)
  1161. if err != nil {
  1162. return err
  1163. }
  1164. iu.IsMentioned = true
  1165. if has {
  1166. _, err = e.Id(iu.ID).AllCols().Update(iu)
  1167. } else {
  1168. _, err = e.Insert(iu)
  1169. }
  1170. if err != nil {
  1171. return err
  1172. }
  1173. }
  1174. return nil
  1175. }
  1176. // _____ .__.__ __
  1177. // / \ |__| | ____ _______/ |_ ____ ____ ____
  1178. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  1179. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  1180. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  1181. // \/ \/ \/ \/ \/
  1182. // Milestone represents a milestone of repository.
  1183. type Milestone struct {
  1184. ID int64 `xorm:"pk autoincr"`
  1185. RepoID int64 `xorm:"INDEX"`
  1186. Name string
  1187. Content string `xorm:"TEXT"`
  1188. RenderedContent string `xorm:"-"`
  1189. IsClosed bool
  1190. NumIssues int
  1191. NumClosedIssues int
  1192. NumOpenIssues int `xorm:"-"`
  1193. Completeness int // Percentage(1-100).
  1194. IsOverDue bool `xorm:"-"`
  1195. DeadlineString string `xorm:"-"`
  1196. Deadline time.Time `xorm:"-"`
  1197. DeadlineUnix int64
  1198. ClosedDate time.Time `xorm:"-"`
  1199. ClosedDateUnix int64
  1200. }
  1201. // BeforeInsert is invoked from XORM before inserting an object of this type.
  1202. func (m *Milestone) BeforeInsert() {
  1203. m.DeadlineUnix = m.Deadline.Unix()
  1204. }
  1205. // BeforeUpdate is invoked from XORM before updating this object.
  1206. func (m *Milestone) BeforeUpdate() {
  1207. if m.NumIssues > 0 {
  1208. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  1209. } else {
  1210. m.Completeness = 0
  1211. }
  1212. m.DeadlineUnix = m.Deadline.Unix()
  1213. m.ClosedDateUnix = m.ClosedDate.Unix()
  1214. }
  1215. // AfterSet is invoked from XORM after setting the value of a field of
  1216. // this object.
  1217. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  1218. switch colName {
  1219. case "num_closed_issues":
  1220. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  1221. case "deadline_unix":
  1222. m.Deadline = time.Unix(m.DeadlineUnix, 0).Local()
  1223. if m.Deadline.Year() == 9999 {
  1224. return
  1225. }
  1226. m.DeadlineString = m.Deadline.Format("2006-01-02")
  1227. if time.Now().Local().After(m.Deadline) {
  1228. m.IsOverDue = true
  1229. }
  1230. case "closed_date_unix":
  1231. m.ClosedDate = time.Unix(m.ClosedDateUnix, 0).Local()
  1232. }
  1233. }
  1234. // State returns string representation of milestone status.
  1235. func (m *Milestone) State() api.StateType {
  1236. if m.IsClosed {
  1237. return api.StateClosed
  1238. }
  1239. return api.StateOpen
  1240. }
  1241. // APIFormat returns this Milestone in API format.
  1242. func (m *Milestone) APIFormat() *api.Milestone {
  1243. apiMilestone := &api.Milestone{
  1244. ID: m.ID,
  1245. State: m.State(),
  1246. Title: m.Name,
  1247. Description: m.Content,
  1248. OpenIssues: m.NumOpenIssues,
  1249. ClosedIssues: m.NumClosedIssues,
  1250. }
  1251. if m.IsClosed {
  1252. apiMilestone.Closed = &m.ClosedDate
  1253. }
  1254. if m.Deadline.Year() < 9999 {
  1255. apiMilestone.Deadline = &m.Deadline
  1256. }
  1257. return apiMilestone
  1258. }
  1259. // NewMilestone creates new milestone of repository.
  1260. func NewMilestone(m *Milestone) (err error) {
  1261. sess := x.NewSession()
  1262. defer sessionRelease(sess)
  1263. if err = sess.Begin(); err != nil {
  1264. return err
  1265. }
  1266. if _, err = sess.Insert(m); err != nil {
  1267. return err
  1268. }
  1269. if _, err = sess.Exec("UPDATE `repository` SET num_milestones = num_milestones + 1 WHERE id = ?", m.RepoID); err != nil {
  1270. return err
  1271. }
  1272. return sess.Commit()
  1273. }
  1274. func getMilestoneByRepoID(e Engine, repoID, id int64) (*Milestone, error) {
  1275. m := &Milestone{
  1276. ID: id,
  1277. RepoID: repoID,
  1278. }
  1279. has, err := e.Get(m)
  1280. if err != nil {
  1281. return nil, err
  1282. } else if !has {
  1283. return nil, ErrMilestoneNotExist{id, repoID}
  1284. }
  1285. return m, nil
  1286. }
  1287. // GetMilestoneByRepoID returns the milestone in a repository.
  1288. func GetMilestoneByRepoID(repoID, id int64) (*Milestone, error) {
  1289. return getMilestoneByRepoID(x, repoID, id)
  1290. }
  1291. // GetMilestonesByRepoID returns all milestones of a repository.
  1292. func GetMilestonesByRepoID(repoID int64) ([]*Milestone, error) {
  1293. miles := make([]*Milestone, 0, 10)
  1294. return miles, x.Where("repo_id = ?", repoID).Find(&miles)
  1295. }
  1296. // GetMilestones returns a list of milestones of given repository and status.
  1297. func GetMilestones(repoID int64, page int, isClosed bool, sortType string) ([]*Milestone, error) {
  1298. miles := make([]*Milestone, 0, setting.UI.IssuePagingNum)
  1299. sess := x.Where("repo_id = ? AND is_closed = ?", repoID, isClosed)
  1300. if page > 0 {
  1301. sess = sess.Limit(setting.UI.IssuePagingNum, (page-1)*setting.UI.IssuePagingNum)
  1302. }
  1303. switch sortType {
  1304. case "furthestduedate":
  1305. sess.Desc("deadline_unix")
  1306. case "leastcomplete":
  1307. sess.Asc("completeness")
  1308. case "mostcomplete":
  1309. sess.Desc("completeness")
  1310. case "leastissues":
  1311. sess.Asc("num_issues")
  1312. case "mostissues":
  1313. sess.Desc("num_issues")
  1314. default:
  1315. sess.Asc("deadline_unix")
  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. }