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

issue.go 52KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2020 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "fmt"
  8. "regexp"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/setting"
  15. "code.gitea.io/gitea/modules/structs"
  16. api "code.gitea.io/gitea/modules/structs"
  17. "code.gitea.io/gitea/modules/timeutil"
  18. "code.gitea.io/gitea/modules/util"
  19. "github.com/unknwon/com"
  20. "xorm.io/builder"
  21. "xorm.io/xorm"
  22. )
  23. // Issue represents an issue or pull request of repository.
  24. type Issue struct {
  25. ID int64 `xorm:"pk autoincr"`
  26. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  27. Repo *Repository `xorm:"-"`
  28. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  29. PosterID int64 `xorm:"INDEX"`
  30. Poster *User `xorm:"-"`
  31. OriginalAuthor string
  32. OriginalAuthorID int64 `xorm:"index"`
  33. Title string `xorm:"name"`
  34. Content string `xorm:"TEXT"`
  35. RenderedContent string `xorm:"-"`
  36. Labels []*Label `xorm:"-"`
  37. MilestoneID int64 `xorm:"INDEX"`
  38. Milestone *Milestone `xorm:"-"`
  39. Priority int
  40. AssigneeID int64 `xorm:"-"`
  41. Assignee *User `xorm:"-"`
  42. IsClosed bool `xorm:"INDEX"`
  43. IsRead bool `xorm:"-"`
  44. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  45. PullRequest *PullRequest `xorm:"-"`
  46. NumComments int
  47. Ref string
  48. DeadlineUnix timeutil.TimeStamp `xorm:"INDEX"`
  49. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  50. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  51. ClosedUnix timeutil.TimeStamp `xorm:"INDEX"`
  52. Attachments []*Attachment `xorm:"-"`
  53. Comments []*Comment `xorm:"-"`
  54. Reactions ReactionList `xorm:"-"`
  55. TotalTrackedTime int64 `xorm:"-"`
  56. Assignees []*User `xorm:"-"`
  57. // IsLocked limits commenting abilities to users on an issue
  58. // with write access
  59. IsLocked bool `xorm:"NOT NULL DEFAULT false"`
  60. }
  61. var (
  62. issueTasksPat *regexp.Regexp
  63. issueTasksDonePat *regexp.Regexp
  64. )
  65. const issueTasksRegexpStr = `(^\s*[-*]\s\[[\sxX]\]\s.)|(\n\s*[-*]\s\[[\sxX]\]\s.)`
  66. const issueTasksDoneRegexpStr = `(^\s*[-*]\s\[[xX]\]\s.)|(\n\s*[-*]\s\[[xX]\]\s.)`
  67. const issueMaxDupIndexAttempts = 3
  68. const maxIssueIDs = 950
  69. func init() {
  70. issueTasksPat = regexp.MustCompile(issueTasksRegexpStr)
  71. issueTasksDonePat = regexp.MustCompile(issueTasksDoneRegexpStr)
  72. }
  73. func (issue *Issue) loadTotalTimes(e Engine) (err error) {
  74. opts := FindTrackedTimesOptions{IssueID: issue.ID}
  75. issue.TotalTrackedTime, err = opts.ToSession(e).SumInt(&TrackedTime{}, "time")
  76. if err != nil {
  77. return err
  78. }
  79. return nil
  80. }
  81. // IsOverdue checks if the issue is overdue
  82. func (issue *Issue) IsOverdue() bool {
  83. return timeutil.TimeStampNow() >= issue.DeadlineUnix
  84. }
  85. // LoadRepo loads issue's repository
  86. func (issue *Issue) LoadRepo() error {
  87. return issue.loadRepo(x)
  88. }
  89. func (issue *Issue) loadRepo(e Engine) (err error) {
  90. if issue.Repo == nil {
  91. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  92. if err != nil {
  93. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  94. }
  95. }
  96. return nil
  97. }
  98. // IsTimetrackerEnabled returns true if the repo enables timetracking
  99. func (issue *Issue) IsTimetrackerEnabled() bool {
  100. return issue.isTimetrackerEnabled(x)
  101. }
  102. func (issue *Issue) isTimetrackerEnabled(e Engine) bool {
  103. if err := issue.loadRepo(e); err != nil {
  104. log.Error(fmt.Sprintf("loadRepo: %v", err))
  105. return false
  106. }
  107. return issue.Repo.IsTimetrackerEnabled()
  108. }
  109. // GetPullRequest returns the issue pull request
  110. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  111. if !issue.IsPull {
  112. return nil, fmt.Errorf("Issue is not a pull request")
  113. }
  114. pr, err = getPullRequestByIssueID(x, issue.ID)
  115. if err != nil {
  116. return nil, err
  117. }
  118. pr.Issue = issue
  119. return
  120. }
  121. // LoadLabels loads labels
  122. func (issue *Issue) LoadLabels() error {
  123. return issue.loadLabels(x)
  124. }
  125. func (issue *Issue) loadLabels(e Engine) (err error) {
  126. if issue.Labels == nil {
  127. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  128. if err != nil {
  129. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  130. }
  131. }
  132. return nil
  133. }
  134. // LoadPoster loads poster
  135. func (issue *Issue) LoadPoster() error {
  136. return issue.loadPoster(x)
  137. }
  138. func (issue *Issue) loadPoster(e Engine) (err error) {
  139. if issue.Poster == nil {
  140. issue.Poster, err = getUserByID(e, issue.PosterID)
  141. if err != nil {
  142. issue.PosterID = -1
  143. issue.Poster = NewGhostUser()
  144. if !IsErrUserNotExist(err) {
  145. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  146. }
  147. err = nil
  148. return
  149. }
  150. }
  151. return
  152. }
  153. func (issue *Issue) loadPullRequest(e Engine) (err error) {
  154. if issue.IsPull && issue.PullRequest == nil {
  155. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  156. if err != nil {
  157. if IsErrPullRequestNotExist(err) {
  158. return err
  159. }
  160. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  161. }
  162. issue.PullRequest.Issue = issue
  163. }
  164. return nil
  165. }
  166. // LoadPullRequest loads pull request info
  167. func (issue *Issue) LoadPullRequest() error {
  168. return issue.loadPullRequest(x)
  169. }
  170. func (issue *Issue) loadComments(e Engine) (err error) {
  171. return issue.loadCommentsByType(e, CommentTypeUnknown)
  172. }
  173. // LoadDiscussComments loads discuss comments
  174. func (issue *Issue) LoadDiscussComments() error {
  175. return issue.loadCommentsByType(x, CommentTypeComment)
  176. }
  177. func (issue *Issue) loadCommentsByType(e Engine, tp CommentType) (err error) {
  178. if issue.Comments != nil {
  179. return nil
  180. }
  181. issue.Comments, err = findComments(e, FindCommentsOptions{
  182. IssueID: issue.ID,
  183. Type: tp,
  184. })
  185. return err
  186. }
  187. func (issue *Issue) loadReactions(e Engine) (err error) {
  188. if issue.Reactions != nil {
  189. return nil
  190. }
  191. reactions, err := findReactions(e, FindReactionsOptions{
  192. IssueID: issue.ID,
  193. })
  194. if err != nil {
  195. return err
  196. }
  197. if err = issue.loadRepo(e); err != nil {
  198. return err
  199. }
  200. // Load reaction user data
  201. if _, err := ReactionList(reactions).loadUsers(e, issue.Repo); err != nil {
  202. return err
  203. }
  204. // Cache comments to map
  205. comments := make(map[int64]*Comment)
  206. for _, comment := range issue.Comments {
  207. comments[comment.ID] = comment
  208. }
  209. // Add reactions either to issue or comment
  210. for _, react := range reactions {
  211. if react.CommentID == 0 {
  212. issue.Reactions = append(issue.Reactions, react)
  213. } else if comment, ok := comments[react.CommentID]; ok {
  214. comment.Reactions = append(comment.Reactions, react)
  215. }
  216. }
  217. return nil
  218. }
  219. func (issue *Issue) loadMilestone(e Engine) (err error) {
  220. if issue.Milestone == nil && issue.MilestoneID > 0 {
  221. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  222. if err != nil && !IsErrMilestoneNotExist(err) {
  223. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  224. }
  225. }
  226. return nil
  227. }
  228. func (issue *Issue) loadAttributes(e Engine) (err error) {
  229. if err = issue.loadRepo(e); err != nil {
  230. return
  231. }
  232. if err = issue.loadPoster(e); err != nil {
  233. return
  234. }
  235. if err = issue.loadLabels(e); err != nil {
  236. return
  237. }
  238. if err = issue.loadMilestone(e); err != nil {
  239. return
  240. }
  241. if err = issue.loadAssignees(e); err != nil {
  242. return
  243. }
  244. if err = issue.loadPullRequest(e); err != nil && !IsErrPullRequestNotExist(err) {
  245. // It is possible pull request is not yet created.
  246. return err
  247. }
  248. if issue.Attachments == nil {
  249. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  250. if err != nil {
  251. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  252. }
  253. }
  254. if err = issue.loadComments(e); err != nil {
  255. return err
  256. }
  257. if err = CommentList(issue.Comments).loadAttributes(e); err != nil {
  258. return err
  259. }
  260. if issue.isTimetrackerEnabled(e) {
  261. if err = issue.loadTotalTimes(e); err != nil {
  262. return err
  263. }
  264. }
  265. return issue.loadReactions(e)
  266. }
  267. // LoadAttributes loads the attribute of this issue.
  268. func (issue *Issue) LoadAttributes() error {
  269. return issue.loadAttributes(x)
  270. }
  271. // LoadMilestone load milestone of this issue.
  272. func (issue *Issue) LoadMilestone() error {
  273. return issue.loadMilestone(x)
  274. }
  275. // GetIsRead load the `IsRead` field of the issue
  276. func (issue *Issue) GetIsRead(userID int64) error {
  277. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  278. if has, err := x.Get(issueUser); err != nil {
  279. return err
  280. } else if !has {
  281. issue.IsRead = false
  282. return nil
  283. }
  284. issue.IsRead = issueUser.IsRead
  285. return nil
  286. }
  287. // APIURL returns the absolute APIURL to this issue.
  288. func (issue *Issue) APIURL() string {
  289. if issue.Repo == nil {
  290. err := issue.LoadRepo()
  291. if err != nil {
  292. log.Error("Issue[%d].APIURL(): %v", issue.ID, err)
  293. return ""
  294. }
  295. }
  296. return fmt.Sprintf("%s/issues/%d", issue.Repo.APIURL(), issue.Index)
  297. }
  298. // HTMLURL returns the absolute URL to this issue.
  299. func (issue *Issue) HTMLURL() string {
  300. var path string
  301. if issue.IsPull {
  302. path = "pulls"
  303. } else {
  304. path = "issues"
  305. }
  306. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  307. }
  308. // DiffURL returns the absolute URL to this diff
  309. func (issue *Issue) DiffURL() string {
  310. if issue.IsPull {
  311. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  312. }
  313. return ""
  314. }
  315. // PatchURL returns the absolute URL to this patch
  316. func (issue *Issue) PatchURL() string {
  317. if issue.IsPull {
  318. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  319. }
  320. return ""
  321. }
  322. // State returns string representation of issue status.
  323. func (issue *Issue) State() api.StateType {
  324. if issue.IsClosed {
  325. return api.StateClosed
  326. }
  327. return api.StateOpen
  328. }
  329. // HashTag returns unique hash tag for issue.
  330. func (issue *Issue) HashTag() string {
  331. return "issue-" + com.ToStr(issue.ID)
  332. }
  333. // IsPoster returns true if given user by ID is the poster.
  334. func (issue *Issue) IsPoster(uid int64) bool {
  335. return issue.OriginalAuthorID == 0 && issue.PosterID == uid
  336. }
  337. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  338. return hasIssueLabel(e, issue.ID, labelID)
  339. }
  340. // HasLabel returns true if issue has been labeled by given ID.
  341. func (issue *Issue) HasLabel(labelID int64) bool {
  342. return issue.hasLabel(x, labelID)
  343. }
  344. // ReplyReference returns tokenized address to use for email reply headers
  345. func (issue *Issue) ReplyReference() string {
  346. var path string
  347. if issue.IsPull {
  348. path = "pulls"
  349. } else {
  350. path = "issues"
  351. }
  352. return fmt.Sprintf("%s/%s/%d@%s", issue.Repo.FullName(), path, issue.Index, setting.Domain)
  353. }
  354. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  355. return newIssueLabel(e, issue, label, doer)
  356. }
  357. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  358. return newIssueLabels(e, issue, labels, doer)
  359. }
  360. func (issue *Issue) getLabels(e Engine) (err error) {
  361. if len(issue.Labels) > 0 {
  362. return nil
  363. }
  364. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  365. if err != nil {
  366. return fmt.Errorf("getLabelsByIssueID: %v", err)
  367. }
  368. return nil
  369. }
  370. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  371. return deleteIssueLabel(e, issue, label, doer)
  372. }
  373. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  374. if err = issue.getLabels(e); err != nil {
  375. return fmt.Errorf("getLabels: %v", err)
  376. }
  377. for i := range issue.Labels {
  378. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  379. return fmt.Errorf("removeLabel: %v", err)
  380. }
  381. }
  382. return nil
  383. }
  384. // ClearLabels removes all issue labels as the given user.
  385. // Triggers appropriate WebHooks, if any.
  386. func (issue *Issue) ClearLabels(doer *User) (err error) {
  387. sess := x.NewSession()
  388. defer sess.Close()
  389. if err = sess.Begin(); err != nil {
  390. return err
  391. }
  392. if err := issue.loadRepo(sess); err != nil {
  393. return err
  394. } else if err = issue.loadPullRequest(sess); err != nil {
  395. return err
  396. }
  397. perm, err := getUserRepoPermission(sess, issue.Repo, doer)
  398. if err != nil {
  399. return err
  400. }
  401. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  402. return ErrRepoLabelNotExist{}
  403. }
  404. if err = issue.clearLabels(sess, doer); err != nil {
  405. return err
  406. }
  407. if err = sess.Commit(); err != nil {
  408. return fmt.Errorf("Commit: %v", err)
  409. }
  410. return nil
  411. }
  412. type labelSorter []*Label
  413. func (ts labelSorter) Len() int {
  414. return len([]*Label(ts))
  415. }
  416. func (ts labelSorter) Less(i, j int) bool {
  417. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  418. }
  419. func (ts labelSorter) Swap(i, j int) {
  420. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  421. }
  422. // ReplaceLabels removes all current labels and add new labels to the issue.
  423. // Triggers appropriate WebHooks, if any.
  424. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  425. sess := x.NewSession()
  426. defer sess.Close()
  427. if err = sess.Begin(); err != nil {
  428. return err
  429. }
  430. if err = issue.loadLabels(sess); err != nil {
  431. return err
  432. }
  433. sort.Sort(labelSorter(labels))
  434. sort.Sort(labelSorter(issue.Labels))
  435. var toAdd, toRemove []*Label
  436. addIndex, removeIndex := 0, 0
  437. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  438. addLabel := labels[addIndex]
  439. removeLabel := issue.Labels[removeIndex]
  440. if addLabel.ID == removeLabel.ID {
  441. addIndex++
  442. removeIndex++
  443. } else if addLabel.ID < removeLabel.ID {
  444. toAdd = append(toAdd, addLabel)
  445. addIndex++
  446. } else {
  447. toRemove = append(toRemove, removeLabel)
  448. removeIndex++
  449. }
  450. }
  451. toAdd = append(toAdd, labels[addIndex:]...)
  452. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  453. if len(toAdd) > 0 {
  454. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  455. return fmt.Errorf("addLabels: %v", err)
  456. }
  457. }
  458. for _, l := range toRemove {
  459. if err = issue.removeLabel(sess, doer, l); err != nil {
  460. return fmt.Errorf("removeLabel: %v", err)
  461. }
  462. }
  463. return sess.Commit()
  464. }
  465. // ReadBy sets issue to be read by given user.
  466. func (issue *Issue) ReadBy(userID int64) error {
  467. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  468. return err
  469. }
  470. return setNotificationStatusReadIfUnread(x, userID, issue.ID)
  471. }
  472. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  473. if _, err := e.ID(issue.ID).Cols(cols...).Update(issue); err != nil {
  474. return err
  475. }
  476. return nil
  477. }
  478. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, isClosed, isMergePull bool) (*Comment, error) {
  479. // Reload the issue
  480. currentIssue, err := getIssueByID(e, issue.ID)
  481. if err != nil {
  482. return nil, err
  483. }
  484. // Nothing should be performed if current status is same as target status
  485. if currentIssue.IsClosed == isClosed {
  486. if !issue.IsPull {
  487. return nil, ErrIssueWasClosed{
  488. ID: issue.ID,
  489. }
  490. }
  491. return nil, ErrPullWasClosed{
  492. ID: issue.ID,
  493. }
  494. }
  495. // Check for open dependencies
  496. if isClosed && issue.Repo.isDependenciesEnabled(e) {
  497. // only check if dependencies are enabled and we're about to close an issue, otherwise reopening an issue would fail when there are unsatisfied dependencies
  498. noDeps, err := issueNoDependenciesLeft(e, issue)
  499. if err != nil {
  500. return nil, err
  501. }
  502. if !noDeps {
  503. return nil, ErrDependenciesLeft{issue.ID}
  504. }
  505. }
  506. issue.IsClosed = isClosed
  507. if isClosed {
  508. issue.ClosedUnix = timeutil.TimeStampNow()
  509. } else {
  510. issue.ClosedUnix = 0
  511. }
  512. if err = updateIssueCols(e, issue, "is_closed", "closed_unix"); err != nil {
  513. return nil, err
  514. }
  515. // Update issue count of labels
  516. if err = issue.getLabels(e); err != nil {
  517. return nil, err
  518. }
  519. for idx := range issue.Labels {
  520. if err = updateLabelCols(e, issue.Labels[idx], "num_issues", "num_closed_issue"); err != nil {
  521. return nil, err
  522. }
  523. }
  524. // Update issue count of milestone
  525. if err := updateMilestoneClosedNum(e, issue.MilestoneID); err != nil {
  526. return nil, err
  527. }
  528. if err := issue.updateClosedNum(e); err != nil {
  529. return nil, err
  530. }
  531. // New action comment
  532. cmtType := CommentTypeClose
  533. if !issue.IsClosed {
  534. cmtType = CommentTypeReopen
  535. } else if isMergePull {
  536. cmtType = CommentTypeMergePull
  537. }
  538. return createComment(e, &CreateCommentOptions{
  539. Type: cmtType,
  540. Doer: doer,
  541. Repo: issue.Repo,
  542. Issue: issue,
  543. })
  544. }
  545. // ChangeStatus changes issue status to open or closed.
  546. func (issue *Issue) ChangeStatus(doer *User, isClosed bool) (*Comment, error) {
  547. sess := x.NewSession()
  548. defer sess.Close()
  549. if err := sess.Begin(); err != nil {
  550. return nil, err
  551. }
  552. if err := issue.loadRepo(sess); err != nil {
  553. return nil, err
  554. }
  555. if err := issue.loadPoster(sess); err != nil {
  556. return nil, err
  557. }
  558. comment, err := issue.changeStatus(sess, doer, isClosed, false)
  559. if err != nil {
  560. return nil, err
  561. }
  562. if err = sess.Commit(); err != nil {
  563. return nil, fmt.Errorf("Commit: %v", err)
  564. }
  565. return comment, nil
  566. }
  567. // ChangeTitle changes the title of this issue, as the given user.
  568. func (issue *Issue) ChangeTitle(doer *User, oldTitle string) (err error) {
  569. sess := x.NewSession()
  570. defer sess.Close()
  571. if err = sess.Begin(); err != nil {
  572. return err
  573. }
  574. if err = updateIssueCols(sess, issue, "name"); err != nil {
  575. return fmt.Errorf("updateIssueCols: %v", err)
  576. }
  577. if err = issue.loadRepo(sess); err != nil {
  578. return fmt.Errorf("loadRepo: %v", err)
  579. }
  580. var opts = &CreateCommentOptions{
  581. Type: CommentTypeChangeTitle,
  582. Doer: doer,
  583. Repo: issue.Repo,
  584. Issue: issue,
  585. OldTitle: oldTitle,
  586. NewTitle: issue.Title,
  587. }
  588. if _, err = createComment(sess, opts); err != nil {
  589. return fmt.Errorf("createComment: %v", err)
  590. }
  591. if err = issue.addCrossReferences(sess, doer, true); err != nil {
  592. return err
  593. }
  594. return sess.Commit()
  595. }
  596. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  597. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  598. issue, err := getIssueByID(x, issueID)
  599. if err != nil {
  600. return err
  601. }
  602. sess := x.NewSession()
  603. defer sess.Close()
  604. if err := sess.Begin(); err != nil {
  605. return err
  606. }
  607. var opts = &CreateCommentOptions{
  608. Type: CommentTypeDeleteBranch,
  609. Doer: doer,
  610. Repo: repo,
  611. Issue: issue,
  612. CommitSHA: branchName,
  613. }
  614. if _, err = createComment(sess, opts); err != nil {
  615. return err
  616. }
  617. return sess.Commit()
  618. }
  619. // UpdateAttachments update attachments by UUIDs for the issue
  620. func (issue *Issue) UpdateAttachments(uuids []string) (err error) {
  621. sess := x.NewSession()
  622. defer sess.Close()
  623. if err = sess.Begin(); err != nil {
  624. return err
  625. }
  626. attachments, err := getAttachmentsByUUIDs(sess, uuids)
  627. if err != nil {
  628. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", uuids, err)
  629. }
  630. for i := 0; i < len(attachments); i++ {
  631. attachments[i].IssueID = issue.ID
  632. if err := updateAttachment(sess, attachments[i]); err != nil {
  633. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  634. }
  635. }
  636. return sess.Commit()
  637. }
  638. // ChangeContent changes issue content, as the given user.
  639. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  640. issue.Content = content
  641. sess := x.NewSession()
  642. defer sess.Close()
  643. if err = sess.Begin(); err != nil {
  644. return err
  645. }
  646. if err = updateIssueCols(sess, issue, "content"); err != nil {
  647. return fmt.Errorf("UpdateIssueCols: %v", err)
  648. }
  649. if err = issue.addCrossReferences(sess, doer, true); err != nil {
  650. return err
  651. }
  652. return sess.Commit()
  653. }
  654. // GetTasks returns the amount of tasks in the issues content
  655. func (issue *Issue) GetTasks() int {
  656. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  657. }
  658. // GetTasksDone returns the amount of completed tasks in the issues content
  659. func (issue *Issue) GetTasksDone() int {
  660. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  661. }
  662. // GetLastEventTimestamp returns the last user visible event timestamp, either the creation of this issue or the close.
  663. func (issue *Issue) GetLastEventTimestamp() timeutil.TimeStamp {
  664. if issue.IsClosed {
  665. return issue.ClosedUnix
  666. }
  667. return issue.CreatedUnix
  668. }
  669. // GetLastEventLabel returns the localization label for the current issue.
  670. func (issue *Issue) GetLastEventLabel() string {
  671. if issue.IsClosed {
  672. if issue.IsPull && issue.PullRequest.HasMerged {
  673. return "repo.pulls.merged_by"
  674. }
  675. return "repo.issues.closed_by"
  676. }
  677. return "repo.issues.opened_by"
  678. }
  679. // GetLastComment return last comment for the current issue.
  680. func (issue *Issue) GetLastComment() (*Comment, error) {
  681. var c Comment
  682. exist, err := x.Where("type = ?", CommentTypeComment).
  683. And("issue_id = ?", issue.ID).Desc("id").Get(&c)
  684. if err != nil {
  685. return nil, err
  686. }
  687. if !exist {
  688. return nil, nil
  689. }
  690. return &c, nil
  691. }
  692. // GetLastEventLabelFake returns the localization label for the current issue without providing a link in the username.
  693. func (issue *Issue) GetLastEventLabelFake() string {
  694. if issue.IsClosed {
  695. if issue.IsPull && issue.PullRequest.HasMerged {
  696. return "repo.pulls.merged_by_fake"
  697. }
  698. return "repo.issues.closed_by_fake"
  699. }
  700. return "repo.issues.opened_by_fake"
  701. }
  702. // NewIssueOptions represents the options of a new issue.
  703. type NewIssueOptions struct {
  704. Repo *Repository
  705. Issue *Issue
  706. LabelIDs []int64
  707. Attachments []string // In UUID format.
  708. IsPull bool
  709. }
  710. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  711. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  712. if opts.Issue.MilestoneID > 0 {
  713. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  714. if err != nil && !IsErrMilestoneNotExist(err) {
  715. return fmt.Errorf("getMilestoneByID: %v", err)
  716. }
  717. // Assume milestone is invalid and drop silently.
  718. opts.Issue.MilestoneID = 0
  719. if milestone != nil {
  720. opts.Issue.MilestoneID = milestone.ID
  721. opts.Issue.Milestone = milestone
  722. }
  723. }
  724. // Milestone validation should happen before insert actual object.
  725. if _, err := e.SetExpr("`index`", "coalesce(MAX(`index`),0)+1").
  726. Where("repo_id=?", opts.Issue.RepoID).
  727. Insert(opts.Issue); err != nil {
  728. return ErrNewIssueInsert{err}
  729. }
  730. inserted, err := getIssueByID(e, opts.Issue.ID)
  731. if err != nil {
  732. return err
  733. }
  734. // Patch Index with the value calculated by the database
  735. opts.Issue.Index = inserted.Index
  736. if opts.Issue.MilestoneID > 0 {
  737. if _, err = e.Exec("UPDATE `milestone` SET num_issues=num_issues+1 WHERE id=?", opts.Issue.MilestoneID); err != nil {
  738. return err
  739. }
  740. var opts = &CreateCommentOptions{
  741. Type: CommentTypeMilestone,
  742. Doer: doer,
  743. Repo: opts.Repo,
  744. Issue: opts.Issue,
  745. OldMilestoneID: 0,
  746. MilestoneID: opts.Issue.MilestoneID,
  747. }
  748. if _, err = createComment(e, opts); err != nil {
  749. return err
  750. }
  751. }
  752. if opts.IsPull {
  753. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  754. } else {
  755. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  756. }
  757. if err != nil {
  758. return err
  759. }
  760. if len(opts.LabelIDs) > 0 {
  761. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  762. // So we have to get all needed labels first.
  763. labels := make([]*Label, 0, len(opts.LabelIDs))
  764. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  765. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  766. }
  767. if err = opts.Issue.loadPoster(e); err != nil {
  768. return err
  769. }
  770. for _, label := range labels {
  771. // Silently drop invalid labels.
  772. if label.RepoID != opts.Repo.ID && label.OrgID != opts.Repo.OwnerID {
  773. continue
  774. }
  775. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  776. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  777. }
  778. }
  779. }
  780. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  781. return err
  782. }
  783. if len(opts.Attachments) > 0 {
  784. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  785. if err != nil {
  786. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  787. }
  788. for i := 0; i < len(attachments); i++ {
  789. attachments[i].IssueID = opts.Issue.ID
  790. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  791. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  792. }
  793. }
  794. }
  795. if err = opts.Issue.loadAttributes(e); err != nil {
  796. return err
  797. }
  798. return opts.Issue.addCrossReferences(e, doer, false)
  799. }
  800. // NewIssue creates new issue with labels for repository.
  801. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  802. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  803. i := 0
  804. for {
  805. if err = newIssueAttempt(repo, issue, labelIDs, uuids); err == nil {
  806. return nil
  807. }
  808. if !IsErrNewIssueInsert(err) {
  809. return err
  810. }
  811. if i++; i == issueMaxDupIndexAttempts {
  812. break
  813. }
  814. log.Error("NewIssue: error attempting to insert the new issue; will retry. Original error: %v", err)
  815. }
  816. return fmt.Errorf("NewIssue: too many errors attempting to insert the new issue. Last error was: %v", err)
  817. }
  818. func newIssueAttempt(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  819. sess := x.NewSession()
  820. defer sess.Close()
  821. if err = sess.Begin(); err != nil {
  822. return err
  823. }
  824. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  825. Repo: repo,
  826. Issue: issue,
  827. LabelIDs: labelIDs,
  828. Attachments: uuids,
  829. }); err != nil {
  830. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  831. return err
  832. }
  833. return fmt.Errorf("newIssue: %v", err)
  834. }
  835. if err = sess.Commit(); err != nil {
  836. return fmt.Errorf("Commit: %v", err)
  837. }
  838. return nil
  839. }
  840. // GetIssueByIndex returns raw issue without loading attributes by index in a repository.
  841. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  842. issue := &Issue{
  843. RepoID: repoID,
  844. Index: index,
  845. }
  846. has, err := x.Get(issue)
  847. if err != nil {
  848. return nil, err
  849. } else if !has {
  850. return nil, ErrIssueNotExist{0, repoID, index}
  851. }
  852. return issue, nil
  853. }
  854. // GetIssueWithAttrsByIndex returns issue by index in a repository.
  855. func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
  856. issue, err := GetIssueByIndex(repoID, index)
  857. if err != nil {
  858. return nil, err
  859. }
  860. return issue, issue.LoadAttributes()
  861. }
  862. func getIssueByID(e Engine, id int64) (*Issue, error) {
  863. issue := new(Issue)
  864. has, err := e.ID(id).Get(issue)
  865. if err != nil {
  866. return nil, err
  867. } else if !has {
  868. return nil, ErrIssueNotExist{id, 0, 0}
  869. }
  870. return issue, nil
  871. }
  872. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
  873. func GetIssueWithAttrsByID(id int64) (*Issue, error) {
  874. issue, err := getIssueByID(x, id)
  875. if err != nil {
  876. return nil, err
  877. }
  878. return issue, issue.loadAttributes(x)
  879. }
  880. // GetIssueByID returns an issue by given ID.
  881. func GetIssueByID(id int64) (*Issue, error) {
  882. return getIssueByID(x, id)
  883. }
  884. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  885. issues := make([]*Issue, 0, 10)
  886. return issues, e.In("id", issueIDs).Find(&issues)
  887. }
  888. func getIssueIDsByRepoID(e Engine, repoID int64) ([]int64, error) {
  889. var ids = make([]int64, 0, 10)
  890. err := e.Table("issue").Where("repo_id = ?", repoID).Find(&ids)
  891. return ids, err
  892. }
  893. // GetIssueIDsByRepoID returns all issue ids by repo id
  894. func GetIssueIDsByRepoID(repoID int64) ([]int64, error) {
  895. return getIssueIDsByRepoID(x, repoID)
  896. }
  897. // GetIssuesByIDs return issues with the given IDs.
  898. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  899. return getIssuesByIDs(x, issueIDs)
  900. }
  901. // IssuesOptions represents options of an issue.
  902. type IssuesOptions struct {
  903. ListOptions
  904. RepoIDs []int64 // include all repos if empty
  905. AssigneeID int64
  906. PosterID int64
  907. MentionedID int64
  908. MilestoneID int64
  909. IsClosed util.OptionalBool
  910. IsPull util.OptionalBool
  911. LabelIDs []int64
  912. IncludedLabelNames []string
  913. ExcludedLabelNames []string
  914. SortType string
  915. IssueIDs []int64
  916. // prioritize issues from this repo
  917. PriorityRepoID int64
  918. }
  919. // sortIssuesSession sort an issues-related session based on the provided
  920. // sortType string
  921. func sortIssuesSession(sess *xorm.Session, sortType string, priorityRepoID int64) {
  922. switch sortType {
  923. case "oldest":
  924. sess.Asc("issue.created_unix")
  925. case "recentupdate":
  926. sess.Desc("issue.updated_unix")
  927. case "leastupdate":
  928. sess.Asc("issue.updated_unix")
  929. case "mostcomment":
  930. sess.Desc("issue.num_comments")
  931. case "leastcomment":
  932. sess.Asc("issue.num_comments")
  933. case "priority":
  934. sess.Desc("issue.priority")
  935. case "nearduedate":
  936. // 253370764800 is 01/01/9999 @ 12:00am (UTC)
  937. sess.OrderBy("CASE WHEN issue.deadline_unix = 0 THEN 253370764800 ELSE issue.deadline_unix END ASC")
  938. case "farduedate":
  939. sess.Desc("issue.deadline_unix")
  940. case "priorityrepo":
  941. sess.OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(priorityRepoID, 10) + " THEN 1 ELSE 2 END, issue.created_unix DESC")
  942. default:
  943. sess.Desc("issue.created_unix")
  944. }
  945. }
  946. func (opts *IssuesOptions) setupSession(sess *xorm.Session) {
  947. if opts.Page >= 0 && opts.PageSize > 0 {
  948. var start int
  949. if opts.Page == 0 {
  950. start = 0
  951. } else {
  952. start = (opts.Page - 1) * opts.PageSize
  953. }
  954. sess.Limit(opts.PageSize, start)
  955. }
  956. if len(opts.IssueIDs) > 0 {
  957. if len(opts.IssueIDs) > maxIssueIDs {
  958. opts.IssueIDs = opts.IssueIDs[:maxIssueIDs]
  959. }
  960. sess.In("issue.id", opts.IssueIDs)
  961. }
  962. if len(opts.RepoIDs) > 0 {
  963. // In case repository IDs are provided but actually no repository has issue.
  964. sess.In("issue.repo_id", opts.RepoIDs)
  965. }
  966. switch opts.IsClosed {
  967. case util.OptionalBoolTrue:
  968. sess.And("issue.is_closed=?", true)
  969. case util.OptionalBoolFalse:
  970. sess.And("issue.is_closed=?", false)
  971. }
  972. if opts.AssigneeID > 0 {
  973. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  974. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  975. }
  976. if opts.PosterID > 0 {
  977. sess.And("issue.poster_id=?", opts.PosterID)
  978. }
  979. if opts.MentionedID > 0 {
  980. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  981. And("issue_user.is_mentioned = ?", true).
  982. And("issue_user.uid = ?", opts.MentionedID)
  983. }
  984. if opts.MilestoneID > 0 {
  985. sess.And("issue.milestone_id=?", opts.MilestoneID)
  986. }
  987. switch opts.IsPull {
  988. case util.OptionalBoolTrue:
  989. sess.And("issue.is_pull=?", true)
  990. case util.OptionalBoolFalse:
  991. sess.And("issue.is_pull=?", false)
  992. }
  993. if opts.LabelIDs != nil {
  994. for i, labelID := range opts.LabelIDs {
  995. if labelID > 0 {
  996. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  997. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  998. } else {
  999. sess.Where("issue.id not in (select issue_id from issue_label where label_id = ?)", -labelID)
  1000. }
  1001. }
  1002. }
  1003. if len(opts.IncludedLabelNames) > 0 {
  1004. sess.In("issue.id", BuildLabelNamesIssueIDsCondition(opts.IncludedLabelNames))
  1005. }
  1006. if len(opts.ExcludedLabelNames) > 0 {
  1007. sess.And(builder.NotIn("issue.id", BuildLabelNamesIssueIDsCondition(opts.ExcludedLabelNames)))
  1008. }
  1009. }
  1010. // CountIssuesByRepo map from repoID to number of issues matching the options
  1011. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1012. sess := x.NewSession()
  1013. defer sess.Close()
  1014. opts.setupSession(sess)
  1015. countsSlice := make([]*struct {
  1016. RepoID int64
  1017. Count int64
  1018. }, 0, 10)
  1019. if err := sess.GroupBy("issue.repo_id").
  1020. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1021. Table("issue").
  1022. Find(&countsSlice); err != nil {
  1023. return nil, err
  1024. }
  1025. countMap := make(map[int64]int64, len(countsSlice))
  1026. for _, c := range countsSlice {
  1027. countMap[c.RepoID] = c.Count
  1028. }
  1029. return countMap, nil
  1030. }
  1031. // GetRepoIDsForIssuesOptions find all repo ids for the given options
  1032. func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *User) ([]int64, error) {
  1033. repoIDs := make([]int64, 0, 5)
  1034. sess := x.NewSession()
  1035. defer sess.Close()
  1036. opts.setupSession(sess)
  1037. accessCond := accessibleRepositoryCondition(user)
  1038. if err := sess.Where(accessCond).
  1039. Join("INNER", "repository", "`issue`.repo_id = `repository`.id").
  1040. Distinct("issue.repo_id").
  1041. Table("issue").
  1042. Find(&repoIDs); err != nil {
  1043. return nil, err
  1044. }
  1045. return repoIDs, nil
  1046. }
  1047. // Issues returns a list of issues by given conditions.
  1048. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1049. sess := x.NewSession()
  1050. defer sess.Close()
  1051. opts.setupSession(sess)
  1052. sortIssuesSession(sess, opts.SortType, opts.PriorityRepoID)
  1053. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1054. if err := sess.Find(&issues); err != nil {
  1055. return nil, fmt.Errorf("Find: %v", err)
  1056. }
  1057. sess.Close()
  1058. if err := IssueList(issues).LoadAttributes(); err != nil {
  1059. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1060. }
  1061. return issues, nil
  1062. }
  1063. // GetParticipantsIDsByIssueID returns the IDs of all users who participated in comments of an issue,
  1064. // but skips joining with `user` for performance reasons.
  1065. // User permissions must be verified elsewhere if required.
  1066. func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) {
  1067. userIDs := make([]int64, 0, 5)
  1068. return userIDs, x.Table("comment").
  1069. Cols("poster_id").
  1070. Where("issue_id = ?", issueID).
  1071. And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1072. Distinct("poster_id").
  1073. Find(&userIDs)
  1074. }
  1075. // IsUserParticipantsOfIssue return true if user is participants of an issue
  1076. func IsUserParticipantsOfIssue(user *User, issue *Issue) bool {
  1077. userIDs, err := issue.getParticipantIDsByIssue(x)
  1078. if err != nil {
  1079. log.Error(err.Error())
  1080. return false
  1081. }
  1082. return util.IsInt64InSlice(user.ID, userIDs)
  1083. }
  1084. // UpdateIssueMentions updates issue-user relations for mentioned users.
  1085. func UpdateIssueMentions(ctx DBContext, issueID int64, mentions []*User) error {
  1086. if len(mentions) == 0 {
  1087. return nil
  1088. }
  1089. ids := make([]int64, len(mentions))
  1090. for i, u := range mentions {
  1091. ids[i] = u.ID
  1092. }
  1093. if err := UpdateIssueUsersByMentions(ctx, issueID, ids); err != nil {
  1094. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1095. }
  1096. return nil
  1097. }
  1098. // IssueStats represents issue statistic information.
  1099. type IssueStats struct {
  1100. OpenCount, ClosedCount int64
  1101. YourRepositoriesCount int64
  1102. AssignCount int64
  1103. CreateCount int64
  1104. MentionCount int64
  1105. }
  1106. // Filter modes.
  1107. const (
  1108. FilterModeAll = iota
  1109. FilterModeAssign
  1110. FilterModeCreate
  1111. FilterModeMention
  1112. )
  1113. func parseCountResult(results []map[string][]byte) int64 {
  1114. if len(results) == 0 {
  1115. return 0
  1116. }
  1117. for _, result := range results[0] {
  1118. return com.StrTo(string(result)).MustInt64()
  1119. }
  1120. return 0
  1121. }
  1122. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1123. type IssueStatsOptions struct {
  1124. RepoID int64
  1125. Labels string
  1126. MilestoneID int64
  1127. AssigneeID int64
  1128. MentionedID int64
  1129. PosterID int64
  1130. IsPull util.OptionalBool
  1131. IssueIDs []int64
  1132. }
  1133. // GetIssueStats returns issue statistic information by given conditions.
  1134. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1135. if len(opts.IssueIDs) <= maxQueryParameters {
  1136. return getIssueStatsChunk(opts, opts.IssueIDs)
  1137. }
  1138. // If too long a list of IDs is provided, we get the statistics in
  1139. // smaller chunks and get accumulates. Note: this could potentially
  1140. // get us invalid results. The alternative is to insert the list of
  1141. // ids in a temporary table and join from them.
  1142. accum := &IssueStats{}
  1143. for i := 0; i < len(opts.IssueIDs); {
  1144. chunk := i + maxQueryParameters
  1145. if chunk > len(opts.IssueIDs) {
  1146. chunk = len(opts.IssueIDs)
  1147. }
  1148. stats, err := getIssueStatsChunk(opts, opts.IssueIDs[i:chunk])
  1149. if err != nil {
  1150. return nil, err
  1151. }
  1152. accum.OpenCount += stats.OpenCount
  1153. accum.ClosedCount += stats.ClosedCount
  1154. accum.YourRepositoriesCount += stats.YourRepositoriesCount
  1155. accum.AssignCount += stats.AssignCount
  1156. accum.CreateCount += stats.CreateCount
  1157. accum.OpenCount += stats.MentionCount
  1158. i = chunk
  1159. }
  1160. return accum, nil
  1161. }
  1162. func getIssueStatsChunk(opts *IssueStatsOptions, issueIDs []int64) (*IssueStats, error) {
  1163. stats := &IssueStats{}
  1164. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1165. sess := x.
  1166. Where("issue.repo_id = ?", opts.RepoID)
  1167. if len(opts.IssueIDs) > 0 {
  1168. if len(opts.IssueIDs) > maxIssueIDs {
  1169. opts.IssueIDs = opts.IssueIDs[:maxIssueIDs]
  1170. }
  1171. sess.In("issue.id", opts.IssueIDs)
  1172. }
  1173. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1174. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1175. if err != nil {
  1176. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1177. } else {
  1178. for i, labelID := range labelIDs {
  1179. if labelID > 0 {
  1180. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1181. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1182. } else {
  1183. sess.Where("issue.id NOT IN (SELECT issue_id FROM issue_label WHERE label_id = ?)", -labelID)
  1184. }
  1185. }
  1186. }
  1187. }
  1188. if opts.MilestoneID > 0 {
  1189. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1190. }
  1191. if opts.AssigneeID > 0 {
  1192. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1193. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1194. }
  1195. if opts.PosterID > 0 {
  1196. sess.And("issue.poster_id = ?", opts.PosterID)
  1197. }
  1198. if opts.MentionedID > 0 {
  1199. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1200. And("issue_user.uid = ?", opts.MentionedID).
  1201. And("issue_user.is_mentioned = ?", true)
  1202. }
  1203. switch opts.IsPull {
  1204. case util.OptionalBoolTrue:
  1205. sess.And("issue.is_pull=?", true)
  1206. case util.OptionalBoolFalse:
  1207. sess.And("issue.is_pull=?", false)
  1208. }
  1209. return sess
  1210. }
  1211. var err error
  1212. stats.OpenCount, err = countSession(opts).
  1213. And("issue.is_closed = ?", false).
  1214. Count(new(Issue))
  1215. if err != nil {
  1216. return stats, err
  1217. }
  1218. stats.ClosedCount, err = countSession(opts).
  1219. And("issue.is_closed = ?", true).
  1220. Count(new(Issue))
  1221. return stats, err
  1222. }
  1223. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1224. type UserIssueStatsOptions struct {
  1225. UserID int64
  1226. RepoIDs []int64
  1227. UserRepoIDs []int64
  1228. FilterMode int
  1229. IsPull bool
  1230. IsClosed bool
  1231. IssueIDs []int64
  1232. }
  1233. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1234. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1235. var err error
  1236. stats := &IssueStats{}
  1237. cond := builder.NewCond()
  1238. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1239. if len(opts.RepoIDs) > 0 {
  1240. cond = cond.And(builder.In("issue.repo_id", opts.RepoIDs))
  1241. }
  1242. if len(opts.IssueIDs) > 0 {
  1243. if len(opts.IssueIDs) > maxIssueIDs {
  1244. opts.IssueIDs = opts.IssueIDs[:maxIssueIDs]
  1245. }
  1246. cond = cond.And(builder.In("issue.id", opts.IssueIDs))
  1247. }
  1248. switch opts.FilterMode {
  1249. case FilterModeAll:
  1250. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1251. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1252. Count(new(Issue))
  1253. if err != nil {
  1254. return nil, err
  1255. }
  1256. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1257. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1258. Count(new(Issue))
  1259. if err != nil {
  1260. return nil, err
  1261. }
  1262. case FilterModeAssign:
  1263. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1264. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1265. And("issue_assignees.assignee_id = ?", opts.UserID).
  1266. Count(new(Issue))
  1267. if err != nil {
  1268. return nil, err
  1269. }
  1270. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1271. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1272. And("issue_assignees.assignee_id = ?", opts.UserID).
  1273. Count(new(Issue))
  1274. if err != nil {
  1275. return nil, err
  1276. }
  1277. case FilterModeCreate:
  1278. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1279. And("issue.poster_id = ?", opts.UserID).
  1280. Count(new(Issue))
  1281. if err != nil {
  1282. return nil, err
  1283. }
  1284. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1285. And("issue.poster_id = ?", opts.UserID).
  1286. Count(new(Issue))
  1287. if err != nil {
  1288. return nil, err
  1289. }
  1290. case FilterModeMention:
  1291. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1292. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1293. And("issue_user.uid = ?", opts.UserID).
  1294. Count(new(Issue))
  1295. if err != nil {
  1296. return nil, err
  1297. }
  1298. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1299. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1300. And("issue_user.uid = ?", opts.UserID).
  1301. Count(new(Issue))
  1302. if err != nil {
  1303. return nil, err
  1304. }
  1305. }
  1306. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1307. stats.AssignCount, err = x.Where(cond).
  1308. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1309. And("issue_assignees.assignee_id = ?", opts.UserID).
  1310. Count(new(Issue))
  1311. if err != nil {
  1312. return nil, err
  1313. }
  1314. stats.CreateCount, err = x.Where(cond).
  1315. And("poster_id = ?", opts.UserID).
  1316. Count(new(Issue))
  1317. if err != nil {
  1318. return nil, err
  1319. }
  1320. stats.MentionCount, err = x.Where(cond).
  1321. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1322. And("issue_user.uid = ?", opts.UserID).
  1323. Count(new(Issue))
  1324. if err != nil {
  1325. return nil, err
  1326. }
  1327. stats.YourRepositoriesCount, err = x.Where(cond).
  1328. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1329. Count(new(Issue))
  1330. if err != nil {
  1331. return nil, err
  1332. }
  1333. return stats, nil
  1334. }
  1335. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1336. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1337. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1338. sess := x.
  1339. Where("is_closed = ?", isClosed).
  1340. And("is_pull = ?", isPull).
  1341. And("repo_id = ?", repoID)
  1342. return sess
  1343. }
  1344. openCountSession := countSession(false, isPull, repoID)
  1345. closedCountSession := countSession(true, isPull, repoID)
  1346. switch filterMode {
  1347. case FilterModeAssign:
  1348. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1349. And("issue_assignees.assignee_id = ?", uid)
  1350. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1351. And("issue_assignees.assignee_id = ?", uid)
  1352. case FilterModeCreate:
  1353. openCountSession.And("poster_id = ?", uid)
  1354. closedCountSession.And("poster_id = ?", uid)
  1355. }
  1356. openResult, _ := openCountSession.Count(new(Issue))
  1357. closedResult, _ := closedCountSession.Count(new(Issue))
  1358. return openResult, closedResult
  1359. }
  1360. // SearchIssueIDsByKeyword search issues on database
  1361. func SearchIssueIDsByKeyword(kw string, repoIDs []int64, limit, start int) (int64, []int64, error) {
  1362. var repoCond = builder.In("repo_id", repoIDs)
  1363. var subQuery = builder.Select("id").From("issue").Where(repoCond)
  1364. var cond = builder.And(
  1365. repoCond,
  1366. builder.Or(
  1367. builder.Like{"name", kw},
  1368. builder.Like{"content", kw},
  1369. builder.In("id", builder.Select("issue_id").
  1370. From("comment").
  1371. Where(builder.And(
  1372. builder.Eq{"type": CommentTypeComment},
  1373. builder.In("issue_id", subQuery),
  1374. builder.Like{"content", kw},
  1375. )),
  1376. ),
  1377. ),
  1378. )
  1379. var ids = make([]int64, 0, limit)
  1380. err := x.Distinct("id").Table("issue").Where(cond).Limit(limit, start).Find(&ids)
  1381. if err != nil {
  1382. return 0, nil, err
  1383. }
  1384. total, err := x.Distinct("id").Table("issue").Where(cond).Count()
  1385. if err != nil {
  1386. return 0, nil, err
  1387. }
  1388. return total, ids, nil
  1389. }
  1390. // UpdateIssueByAPI updates all allowed fields of given issue.
  1391. func UpdateIssueByAPI(issue *Issue) error {
  1392. sess := x.NewSession()
  1393. defer sess.Close()
  1394. if err := sess.Begin(); err != nil {
  1395. return err
  1396. }
  1397. if _, err := sess.ID(issue.ID).Cols(
  1398. "name", "is_closed", "content", "milestone_id", "priority",
  1399. "deadline_unix", "updated_unix", "closed_unix", "is_locked").
  1400. Update(issue); err != nil {
  1401. return err
  1402. }
  1403. if err := issue.loadPoster(sess); err != nil {
  1404. return err
  1405. }
  1406. if err := issue.addCrossReferences(sess, issue.Poster, true); err != nil {
  1407. return err
  1408. }
  1409. return sess.Commit()
  1410. }
  1411. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1412. func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *User) (err error) {
  1413. // if the deadline hasn't changed do nothing
  1414. if issue.DeadlineUnix == deadlineUnix {
  1415. return nil
  1416. }
  1417. sess := x.NewSession()
  1418. defer sess.Close()
  1419. if err := sess.Begin(); err != nil {
  1420. return err
  1421. }
  1422. // Update the deadline
  1423. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1424. return err
  1425. }
  1426. // Make the comment
  1427. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1428. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1429. }
  1430. return sess.Commit()
  1431. }
  1432. // DependencyInfo represents high level information about an issue which is a dependency of another issue.
  1433. type DependencyInfo struct {
  1434. Issue `xorm:"extends"`
  1435. Repository `xorm:"extends"`
  1436. }
  1437. // getParticipantIDsByIssue returns all userIDs who are participated in comments of an issue and issue author
  1438. func (issue *Issue) getParticipantIDsByIssue(e Engine) ([]int64, error) {
  1439. if issue == nil {
  1440. return nil, nil
  1441. }
  1442. userIDs := make([]int64, 0, 5)
  1443. if err := e.Table("comment").Cols("poster_id").
  1444. Where("`comment`.issue_id = ?", issue.ID).
  1445. And("`comment`.type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1446. And("`user`.is_active = ?", true).
  1447. And("`user`.prohibit_login = ?", false).
  1448. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1449. Distinct("poster_id").
  1450. Find(&userIDs); err != nil {
  1451. return nil, fmt.Errorf("get poster IDs: %v", err)
  1452. }
  1453. if !util.IsInt64InSlice(issue.PosterID, userIDs) {
  1454. return append(userIDs, issue.PosterID), nil
  1455. }
  1456. return userIDs, nil
  1457. }
  1458. // Get Blocked By Dependencies, aka all issues this issue is blocked by.
  1459. func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1460. return issueDeps, e.
  1461. Table("issue").
  1462. Join("INNER", "repository", "repository.id = issue.repo_id").
  1463. Join("INNER", "issue_dependency", "issue_dependency.dependency_id = issue.id").
  1464. Where("issue_id = ?", issue.ID).
  1465. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1466. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1467. Find(&issueDeps)
  1468. }
  1469. // Get Blocking Dependencies, aka all issues this issue blocks.
  1470. func (issue *Issue) getBlockingDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1471. return issueDeps, e.
  1472. Table("issue").
  1473. Join("INNER", "repository", "repository.id = issue.repo_id").
  1474. Join("INNER", "issue_dependency", "issue_dependency.issue_id = issue.id").
  1475. Where("dependency_id = ?", issue.ID).
  1476. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1477. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1478. Find(&issueDeps)
  1479. }
  1480. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1481. func (issue *Issue) BlockedByDependencies() ([]*DependencyInfo, error) {
  1482. return issue.getBlockedByDependencies(x)
  1483. }
  1484. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
  1485. func (issue *Issue) BlockingDependencies() ([]*DependencyInfo, error) {
  1486. return issue.getBlockingDependencies(x)
  1487. }
  1488. func (issue *Issue) updateClosedNum(e Engine) (err error) {
  1489. if issue.IsPull {
  1490. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1491. issue.RepoID,
  1492. true,
  1493. true,
  1494. issue.RepoID,
  1495. )
  1496. } else {
  1497. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1498. issue.RepoID,
  1499. false,
  1500. true,
  1501. issue.RepoID,
  1502. )
  1503. }
  1504. return
  1505. }
  1506. // ResolveMentionsByVisibility returns the users mentioned in an issue, removing those that
  1507. // don't have access to reading it. Teams are expanded into their users, but organizations are ignored.
  1508. func (issue *Issue) ResolveMentionsByVisibility(ctx DBContext, doer *User, mentions []string) (users []*User, err error) {
  1509. if len(mentions) == 0 {
  1510. return
  1511. }
  1512. if err = issue.loadRepo(ctx.e); err != nil {
  1513. return
  1514. }
  1515. resolved := make(map[string]bool, 20)
  1516. names := make([]string, 0, 20)
  1517. resolved[doer.LowerName] = true
  1518. for _, name := range mentions {
  1519. name := strings.ToLower(name)
  1520. if _, ok := resolved[name]; ok {
  1521. continue
  1522. }
  1523. resolved[name] = false
  1524. names = append(names, name)
  1525. }
  1526. if err := issue.Repo.getOwner(ctx.e); err != nil {
  1527. return nil, err
  1528. }
  1529. if issue.Repo.Owner.IsOrganization() {
  1530. // Since there can be users with names that match the name of a team,
  1531. // if the team exists and can read the issue, the team takes precedence.
  1532. teams := make([]*Team, 0, len(names))
  1533. if err := ctx.e.
  1534. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  1535. Where("team_repo.repo_id=?", issue.Repo.ID).
  1536. In("team.lower_name", names).
  1537. Find(&teams); err != nil {
  1538. return nil, fmt.Errorf("find mentioned teams: %v", err)
  1539. }
  1540. if len(teams) != 0 {
  1541. checked := make([]int64, 0, len(teams))
  1542. unittype := UnitTypeIssues
  1543. if issue.IsPull {
  1544. unittype = UnitTypePullRequests
  1545. }
  1546. for _, team := range teams {
  1547. if team.Authorize >= AccessModeOwner {
  1548. checked = append(checked, team.ID)
  1549. resolved[team.LowerName] = true
  1550. continue
  1551. }
  1552. has, err := ctx.e.Get(&TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype})
  1553. if err != nil {
  1554. return nil, fmt.Errorf("get team units (%d): %v", team.ID, err)
  1555. }
  1556. if has {
  1557. checked = append(checked, team.ID)
  1558. resolved[team.LowerName] = true
  1559. }
  1560. }
  1561. if len(checked) != 0 {
  1562. teamusers := make([]*User, 0, 20)
  1563. if err := ctx.e.
  1564. Join("INNER", "team_user", "team_user.uid = `user`.id").
  1565. In("`team_user`.team_id", checked).
  1566. And("`user`.is_active = ?", true).
  1567. And("`user`.prohibit_login = ?", false).
  1568. Find(&teamusers); err != nil {
  1569. return nil, fmt.Errorf("get teams users: %v", err)
  1570. }
  1571. if len(teamusers) > 0 {
  1572. users = make([]*User, 0, len(teamusers))
  1573. for _, user := range teamusers {
  1574. if already, ok := resolved[user.LowerName]; !ok || !already {
  1575. users = append(users, user)
  1576. resolved[user.LowerName] = true
  1577. }
  1578. }
  1579. }
  1580. }
  1581. }
  1582. // Remove names already in the list to avoid querying the database if pending names remain
  1583. names = make([]string, 0, len(resolved))
  1584. for name, already := range resolved {
  1585. if !already {
  1586. names = append(names, name)
  1587. }
  1588. }
  1589. if len(names) == 0 {
  1590. return
  1591. }
  1592. }
  1593. unchecked := make([]*User, 0, len(names))
  1594. if err := ctx.e.
  1595. Where("`user`.is_active = ?", true).
  1596. And("`user`.prohibit_login = ?", false).
  1597. In("`user`.lower_name", names).
  1598. Find(&unchecked); err != nil {
  1599. return nil, fmt.Errorf("find mentioned users: %v", err)
  1600. }
  1601. for _, user := range unchecked {
  1602. if already := resolved[user.LowerName]; already || user.IsOrganization() {
  1603. continue
  1604. }
  1605. // Normal users must have read access to the referencing issue
  1606. perm, err := getUserRepoPermission(ctx.e, issue.Repo, user)
  1607. if err != nil {
  1608. return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err)
  1609. }
  1610. if !perm.CanReadIssuesOrPulls(issue.IsPull) {
  1611. continue
  1612. }
  1613. users = append(users, user)
  1614. }
  1615. return
  1616. }
  1617. // UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID
  1618. func UpdateIssuesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
  1619. _, err := x.Table("issue").
  1620. Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
  1621. And("original_author_id = ?", originalAuthorID).
  1622. Update(map[string]interface{}{
  1623. "poster_id": posterID,
  1624. "original_author": "",
  1625. "original_author_id": 0,
  1626. })
  1627. return err
  1628. }
  1629. // UpdateReactionsMigrationsByType updates all migrated repositories' reactions from gitServiceType to replace originalAuthorID to posterID
  1630. func UpdateReactionsMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, userID int64) error {
  1631. _, err := x.Table("reaction").
  1632. Where("original_author_id = ?", originalAuthorID).
  1633. And(migratedIssueCond(gitServiceType)).
  1634. Update(map[string]interface{}{
  1635. "user_id": userID,
  1636. "original_author": "",
  1637. "original_author_id": 0,
  1638. })
  1639. return err
  1640. }