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

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