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 51KB

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