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